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

303 lines
11 KiB
Python
Raw Permalink Normal View History

"""Operator-only 512px temporal lip preview on the unmodified 24 Hz source grid."""
import subprocess
import sys
from contextlib import chdir
from pathlib import Path
from . import LATENTSYNC_PREVIEW, MOUTH_BLEND_POLICY, SOURCE_REST_POLICY
from .media import digest, frames, probe
REVISION = "a229c3948406bc2cf6eaf4873e662e70c6a04746"
UNET_SHA = "0a478e89eb660f82da4c35dbdde8a5adfb27f99d1b4e50edd03729e1e98316d3"
WHISPER_SHA = "65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9"
def cache_environment(model_root: Path) -> dict[str, str]:
cache = model_root / ".cache"
home = cache / "huggingface"
hub = str(home / "hub")
return {
"HF_HOME": str(home),
"HF_HUB_CACHE": hub,
"HUGGINGFACE_HUB_CACHE": hub,
"TRANSFORMERS_CACHE": hub,
"MPLCONFIGDIR": str(cache / "matplotlib"),
"HF_HUB_OFFLINE": "1",
"TRANSFORMERS_OFFLINE": "1",
}
def windows(count):
# 中间8帧写回,前后最多各4帧提供上下文。两端向内取真实帧,短片不补帧。
for first in range(0, count, 8):
start = max(0, min(first - 4, count - 16))
if start + 16 >= count:
# 已贴齐片尾,剩下的有声帧共享这一次预测,避免重复抽取 VAE 后验。
yield start, count, first, count
return
yield start, start + 16, first, first + 8
def preview_frames(source, active, predict, paste):
if len(source) != len(active):
raise ValueError("Source video and stem lengths differ")
for start, end, first, last in windows(len(source)):
if not active[first:last].any():
yield from source[first:last]
continue
predicted = predict(start, source[start:end])
if predicted.shape != source[start:end].shape:
raise ValueError("LatentSync returned an incomplete or resized window")
for i in range(first, last):
yield paste(i, source[i], predicted[i - start]) if active[i] else source[i]
def load_pipeline(root, seed):
import torch
from diffusers import AutoencoderKL, DDIMScheduler
from latentsync.models.unet import UNet3DConditionModel
from latentsync.pipelines.lipsync_pipeline import LipsyncPipeline
from latentsync.utils.affine_transform import AlignRestore
from latentsync.utils.image_processor import ImageProcessor, load_fixed_mask
from latentsync.whisper.audio2feature import Audio2Feature
from omegaconf import OmegaConf
config = OmegaConf.load("configs/unet/stage2_512.yaml")
if (config.data.resolution, config.data.num_frames, config.data.video_fps) != (
512,
16,
25,
):
raise ValueError("Unexpected LatentSync model configuration")
unet_path = Path("checkpoints/latentsync_unet.pt")
tiny = Path("checkpoints/whisper/tiny.pt")
if digest(unet_path) != UNET_SHA or digest(tiny) != WHISPER_SHA:
raise ValueError("LatentSync model digest mismatch")
torch.manual_seed(seed)
dtype = torch.float16
vae = AutoencoderKL.from_pretrained(
root / "sd-vae-ft-mse", torch_dtype=dtype, local_files_only=True
)
vae.register_to_config(scaling_factor=0.18215, shift_factor=0.0)
encoder = Audio2Feature(
model_path=str(tiny),
device="cuda",
num_frames=16,
audio_feat_length=config.data.audio_feat_length,
)
net, _ = UNet3DConditionModel.from_pretrained(
OmegaConf.to_container(config.model), str(unet_path), device="cpu"
)
net = net.eval().to(dtype=dtype)
pipe = LipsyncPipeline(
vae=vae.eval(),
audio_encoder=encoder,
unet=net,
scheduler=DDIMScheduler.from_pretrained("configs", local_files_only=True),
).to("cuda")
# 复用已验身份的原片框,106点来自实测,避免重新选择全画面最大人脸。
pipe.image_processor = ImageProcessor(
512, device="cpu", mask_image=load_fixed_mask(512, config.data.mask_image_path)
)
pipe.image_processor.restorer = AlignRestore(resolution=512, device="cuda")
return pipe
def align_track(pipe, rgb, boxes):
import numpy as np
import onnxruntime as ort
from insightface.app.common import Face
from insightface.model_zoo.landmark import Landmark
weights = Path("checkpoints/auxiliary/models/buffalo_l/2d106det.onnx").resolve()
if not weights.is_file():
raise ValueError("LatentSync requires local 106-landmark weights")
options = ort.SessionOptions()
options.intra_op_num_threads = 2
options.inter_op_num_threads = 1
session = ort.InferenceSession(
str(weights), sess_options=options, providers=["CPUExecutionProvider"]
)
model = Landmark(model_file=str(weights), session=session)
if model.taskname != "landmark_2d_106":
raise ValueError("Unexpected landmark model")
bounds = iter(boxes)
def detect(image):
box = np.asarray(next(bounds), np.float32)
points = model.get(image, Face(bbox=box))
if points.shape != (106, 2) or not np.isfinite(points).all():
raise ValueError("Missing measured facial landmarks")
return box, np.rint(points).astype(int)
pipe.image_processor.face_detector = detect
return pipe.affine_transform_video(rgb)
def predict_window(pipe, features, aligned, noise, start, rgb):
"""Use official v1.6 components without its implicit 25fps transcode or video looping."""
import torch
device = torch.device("cuda")
dtype = torch.float16
context = torch.stack(
[
pipe.audio_encoder.get_sliced_feature(features, i, fps=24)[0]
for i in range(start, start + len(rgb))
]
).to(device, dtype)
context = torch.cat((torch.zeros_like(context), context))
faces, boxes, transforms = (values[start : start + len(rgb)] for values in aligned)
pixels, masked, masks = pipe.image_processor.prepare_masks_and_masked_images(
faces, affine_transform=False
)
mask, masked_latents = pipe.prepare_mask_latents(
masks, masked, 512, 512, dtype, device, None, True
)
reference = pipe.prepare_image_latents(pixels, device, dtype, None, True)
pipe.scheduler.set_timesteps(20, device=device)
latent = noise[:, :, start : start + len(rgb)]
for step in pipe.scheduler.timesteps:
model_input = pipe.scheduler.scale_model_input(
torch.cat((latent, latent)), step
)
model_input = torch.cat((model_input, mask, masked_latents, reference), dim=1)
negative, positive = pipe.unet(
model_input, step, encoder_hidden_states=context
).sample.chunk(2)
latent = pipe.scheduler.step(
negative + 1.5 * (positive - negative), step, latent
).prev_sample
pixels = pipe.paste_surrounding_pixels_back(
pipe.decode_latents(latent), pixels, 1 - masks, device, dtype
)
return pipe.restore_video(pixels, rgb, boxes, transforms)
def paste_mouth(parser, src, predicted, box, points):
import cv2
import numpy as np
x, y, r, b = box
roi = src[y:b, x:r]
labels = parser.labels(cv2.resize(roi, (256, 256)), (b - y, r - x))
pts = np.asarray(points)
center = np.rint(pts[3:5].mean(0) - [x, y]).astype(int)
radius = max(2, int(np.linalg.norm(pts[3] - pts[4]) * 0.78))
ellipse = np.zeros(roi.shape[:2], np.float32)
cv2.ellipse(
ellipse, tuple(center), (radius, max(2, round(radius * 0.7))), 0, 0, 360, 1, -1
)
alpha = (
cv2.GaussianBlur(ellipse, (0, 0), max(1, radius / 10))
* np.isin(labels, parser.writable)
)[..., None]
result = src.copy()
result[y:b, x:r] = (
(predicted[y:b, x:r] * alpha + roi * (1 - alpha)).clip(0, 255).astype(np.uint8)
)
return result
def render(source, w, h, rows, p, dialogue_root, out):
import cv2
import numpy as np
import soundfile as sf
import torch
from scipy.signal import resample_poly
from .rest import MouthParser
root = dialogue_root.parent / LATENTSYNC_PREVIEW
repo = root / "LatentSync"
if len(rows) != 1 or not repo.is_dir():
raise ValueError("Missing isolated single-person preview runtime")
n = p["num_frames"]
stem, boxes, points, wave = rows[0]
if len(wave) != 2000 * n or p.get("speech_silence_policy") != SOURCE_REST_POLICY:
raise ValueError("Expected a frame-bound 48 kHz source-rest stem")
active = np.max(abs(wave.reshape(n, 2000)), axis=1) > 0.003
src = np.stack([cv2.cvtColor(f, cv2.COLOR_BGR2RGB) for f in frames(source, n)])
target = out / "latentsync-preview.mp4"
sys.path.insert(0, str(repo))
with torch.inference_mode(), chdir(repo):
pipe = load_pipeline(root, p.get("seed", 0))
parser = MouthParser(dialogue_root)
# Resample the entire stem once, preserving the origin even at fractional 16k samples/frame.
wav = out / ".runtime" / "latentsync-16k.wav"
sf.write(str(wav), resample_poly(wave, 1, 3), 16000, subtype="PCM_16")
features = pipe.audio_encoder.audio2feat(str(wav))
if len(features) <= (n - 1) * 50 // 24:
raise ValueError("Whisper features do not cover the source timeline")
aligned = align_track(pipe, src, boxes)
# 官方初始化在整段内复用一次时序噪声,重叠窗口不另抽新噪声。
noise = pipe.prepare_latents(
n,
pipe.vae.config.latent_channels,
512,
512,
torch.float16,
torch.device("cuda"),
None,
)
def predict(start, context):
return predict_window(pipe, features, aligned, noise, start, context)
def paste(i, original, generated):
return paste_mouth(parser, original, generated, boxes[i], points[i])
cmd = [
"ffmpeg",
"-nostdin",
"-v",
"error",
"-f",
"rawvideo",
"-pix_fmt",
"rgb24",
"-s",
f"{w}x{h}",
"-r",
"24",
"-i",
"pipe:0",
"-an",
"-c:v",
"libx264",
"-threads",
"2",
"-crf",
"14",
"-pix_fmt",
"yuv420p",
str(target),
]
with subprocess.Popen(cmd, stdin=subprocess.PIPE) as proc:
try:
for frame in preview_frames(src, active, predict, paste):
proc.stdin.write(frame.tobytes())
finally:
proc.stdin.close()
if proc.wait():
raise ValueError("LatentSync preview encoding failed")
probe(target, n)
return [target], {
"profile": LATENTSYNC_PREVIEW,
"revision": REVISION,
"certified": False,
"speech_silence_policy": SOURCE_REST_POLICY,
"mouth_blend_policy": MOUTH_BLEND_POLICY,
"base_sha256": digest(source),
"synced_sha256": digest(target),
"weights_sha256": UNET_SHA,
"fps": 24,
"model_training_fps": 25,
"num_frames": n,
"has_audio": False,
"source_rest_frames": [
{"speaker_id": stem["speaker_id"], "silent_frames": int((~active).sum())}
],
}