cmvr-visual/inference/llm_services/dialogue/lipsync.py

328 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""One input frame per output frame. Only the selected speaker's mouth is writable."""
import json
import math
import subprocess
from . import (
AUDIO_CONTEXT_SHIFT_POLICY,
MOUTH_BLEND_POLICY,
SILENCE_POLICY,
SOURCE_REST_POLICY,
)
from .media import digest, frames, probe
from .rest import MouthParser
class Muse:
def __init__(self, root):
import torch
from diffusers import AutoencoderKL, UNet2DConditionModel
from transformers import (
WhisperFeatureExtractor,
WhisperModel,
)
self.vae = (
AutoencoderKL.from_pretrained(root / "sd-vae", local_files_only=True)
.half()
.cuda()
.eval()
)
base = root / "musetalk" / "musetalkV15"
self.net = UNet2DConditionModel(
**json.loads((base / "musetalk.json").read_text())
)
self.net.load_state_dict(
torch.load(base / "unet.pth", weights_only=True, map_location="cpu")
)
self.net = self.net.half().cuda().eval()
self.feature = WhisperFeatureExtractor.from_pretrained(
root / "whisper", local_files_only=True
)
self.whisper = (
WhisperModel.from_pretrained(root / "whisper", local_files_only=True)
.half()
.cuda()
.eval()
)
self.parser = MouthParser(root)
def audio(self, y, n):
import torch
from scipy.signal import resample_poly
feats = (
self.feature(
resample_poly(y, 1, 3), sampling_rate=16000, return_tensors="pt"
)
.input_features.half()
.cuda()
)
encoded = self.whisper.encoder(feats, output_hidden_states=True).hidden_states
seq = torch.stack(encoded, dim=2)[:, : math.ceil(n * 50 / 24)]
seq = torch.nn.functional.pad(seq, (0, 0, 0, 0, 6, 18))
chunks = torch.cat(
[seq[:, i * 50 // 24 : i * 50 // 24 + 10] for i in range(n)]
).flatten(1, 2)
phase = torch.arange(chunks.shape[1], device="cuda")[:, None] * torch.exp(
torch.arange(0, 384, 2, device="cuda") * (-math.log(10000) / 384)
)
positional = torch.stack((phase.sin(), phase.cos()), dim=-1).flatten(1)
return chunks + positional.half()
def patch(self, frame, box, points, audio, rest_reference):
import cv2
import numpy as np
import torch
x, y, r, b = box
crop = frame[y:b, x:r]
rgb = cv2.cvtColor(cv2.resize(crop, (256, 256)), cv2.COLOR_BGR2RGB)
face = (
torch.from_numpy(rgb).permute(2, 0, 1).unsqueeze(0).half().cuda() / 127.5
- 1
)
masked = face.clone()
masked[:, :, 128:] = -1
reference = face
if rest_reference is not None:
reference_rgb, reference_points, _ = rest_reference
current_points = (np.asarray(points) - [x, y]) * [
256 / (r - x),
256 / (b - y),
]
transform, _ = cv2.estimateAffinePartial2D(
reference_points, current_points.astype(np.float32), method=cv2.LMEDS
)
if transform is None:
raise ValueError("Rest reference cannot be aligned to this actor")
aligned = cv2.warpAffine(
reference_rgb, transform, (256, 256), borderMode=cv2.BORDER_REPLICATE
)
reference = (
torch.from_numpy(aligned).permute(2, 0, 1).unsqueeze(0).half().cuda()
/ 127.5
- 1
)
distributions = [self.vae.encode(im).latent_dist for im in (masked, reference)]
# 静音时选后验均值,保持跨帧稳定;嘴部依然由当前帧、零声特征和UNet生成。
inputs = torch.cat(
[
d.mode() if rest_reference is not None else d.sample()
for d in distributions
],
dim=1,
)
inputs *= self.vae.config.scaling_factor
result = self.net(
inputs,
torch.zeros(1, device="cuda", dtype=torch.int64),
encoder_hidden_states=audio.unsqueeze(0),
).sample
decoded = self.vae.decode(result / self.vae.config.scaling_factor).sample[0]
img = (
((decoded.float() + 1) * 127.5)
.clamp(0, 255)
.byte()
.permute(1, 2, 0)
.cpu()
.numpy()
)
generated = cv2.resize(cv2.cvtColor(img, cv2.COLOR_RGB2BGR), (r - x, b - y))
labels = self.parser.labels(rgb, (b - y, r - x))
semantic = np.isin(labels, self.parser.writable).astype(np.float32)
pts = np.asarray(points)
center = np.round(pts[3:5].mean(axis=0) - [x, y]).astype(int)
radius = max(2, int(np.linalg.norm(pts[3] - pts[4]) * 0.78))
ellipse = np.zeros((b - y, r - x), np.float32)
cv2.ellipse(
ellipse,
tuple(center),
(radius, max(2, round(radius * 0.7))),
0,
0,
360,
1,
-1,
)
mask = cv2.GaussianBlur(ellipse, (0, 0), max(1, radius / 10)) * semantic
return np.clip(
generated * mask[:, :, None] + crop * (1 - mask[:, :, None]), 0, 255
).astype(np.uint8)
def rest_references(model, source, n, rows):
import cv2
import numpy as np
best = [None] * len(rows)
scores = [float("inf")] * len(rows)
needs_rest = [
np.any(np.max(np.abs(wave.reshape(-1, 2000)), axis=1) <= 0.003)
for _, _, _, wave in rows
]
if not any(needs_rest):
return best
for i, frame in enumerate(frames(source, n)):
if i % max(1, n // 32) and i != n - 1:
continue
for j, (_, boxes, points, _) in enumerate(rows):
if not needs_rest[j]:
continue
score = model.parser.aperture(frame, boxes[i], points[i])
if score is not None and score < scores[j]:
x, y, r, b = boxes[i]
rgb = cv2.cvtColor(
cv2.resize(frame[y:b, x:r], (256, 256)), cv2.COLOR_BGR2RGB
)
normalized = (np.asarray(points[i]) - [x, y]) * [
256 / (r - x),
256 / (b - y),
]
best[j] = (rgb, normalized.astype(np.float32), i)
scores[j] = score
if any(needed and ref is None for needed, ref in zip(needs_rest, best)):
raise ValueError(
"Cannot locate a visible mouth on the bound speaker for rest conditioning"
)
return best
def render_frame(
model,
base,
rows,
contexts,
neutral,
i,
references,
audio_context_shift_frames=0,
speech_silence_policy=SILENCE_POLICY,
):
import numpy as np
active = [
np.max(np.abs(wave[2000 * i : 2000 * (i + 1)])) > 0.003
for _, _, _, wave in rows
]
if sum(active) > 1:
raise ValueError("Overlapping speakers require review")
frame = base.copy()
for j, (_, boxes, landmarks, _) in enumerate(rows):
if not active[j] and speech_silence_policy == SOURCE_REST_POLICY:
continue
box = boxes[i]
x, y, r, b = box
source_index = i + audio_context_shift_frames
context = (
contexts[j][source_index]
if active[j] and 0 <= source_index < len(contexts[j])
else neutral[i]
)
frame[y:b, x:r] = model.patch(
base, box, landmarks[i], context, None if active[j] else references[j]
)
return frame
def render(source, w, h, rows, p, root, out):
import numpy as np
import torch
torch.manual_seed(p.get("seed", 0))
model = Muse(root)
n = p["num_frames"]
path = out / "synced.mp4"
cmd = [
"ffmpeg",
"-nostdin",
"-v",
"error",
"-f",
"rawvideo",
"-pix_fmt",
"bgr24",
"-s",
f"{w}x{h}",
"-r",
"24",
"-i",
"pipe:0",
"-an",
"-c:v",
"libx264",
"-threads",
"2",
"-pix_fmt",
"yuv420p",
"-crf",
"14",
str(path),
]
with torch.inference_mode():
policy = p.get("speech_silence_policy", SILENCE_POLICY)
references = (
rest_references(model, source, n, rows)
if policy == SILENCE_POLICY
else [None] * len(rows)
)
contexts = [model.audio(wave, n) for _, _, _, wave in rows]
shift = p.get("audio_context_shift_frames", 0)
neutral = (
model.audio(np.zeros(n * 2000, dtype=np.float32), n)
if policy == SILENCE_POLICY or shift
else None
)
with subprocess.Popen(cmd, stdin=subprocess.PIPE) as encoder:
try:
for i, base in enumerate(frames(source, n)):
frame = render_frame(
model,
base,
rows,
contexts,
neutral,
i,
references,
shift,
policy,
)
encoder.stdin.write(frame.tobytes())
finally:
encoder.stdin.close()
if encoder.wait() != 0:
raise ValueError("Encoding synced video failed")
probe(path, n)
return [path], {
"fps": 24,
"num_frames": n,
"has_audio": False,
"speech_silence_policy": policy,
**(
{
"source_rest_frames": [
{
"speaker_id": stem["speaker_id"],
"silent_frames": int(
np.count_nonzero(
np.max(np.abs(wave.reshape(-1, 2000)), axis=1) <= 0.003
)
),
}
for stem, _, _, wave in rows
]
}
if policy == SOURCE_REST_POLICY
else {}
),
"mouth_blend_policy": MOUTH_BLEND_POLICY,
"audio_context_shift_policy": AUDIO_CONTEXT_SHIFT_POLICY,
"audio_context_shift_frames": p.get("audio_context_shift_frames", 0),
"rest_reference_frames": [
ref[2] if ref is not None else None for ref in references
],
"synced_sha256": digest(path),
**({"base_sha256": digest(source)} if policy == SOURCE_REST_POLICY else {}),
}