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

152 lines
4.9 KiB
Python

"""Executed only in the worker's leased process group."""
import subprocess
from pathlib import Path
from . import ANALYZE, INSPECT, LATENTSYNC_PREVIEW, SPEECH, SPEECH_INSPECT
from .media import digest, dry_audio, probe, read_tracks, target_boxes
def synthesis_controls(inputs, p):
reference = inputs.get("reference_path")
options = {"reference_wav_path": reference} if reference else {}
control = p.get("style") or ("" if reference else p["voice"])
mode = "controlled_clone" if reference else "voice_design"
# VoxCPM2 的控制文本与提示音频续读互斥,否则模型会朗读风格指令。
if reference and p.get("reference_text") and not control:
mode = "continuation_clone"
options.update(prompt_wav_path=reference, prompt_text=p["reference_text"])
return (f"({control})" if control else "") + inputs["prompt"], options, mode
def speech(inputs, p, root, out):
import numpy as np
import soundfile as sf
from voxcpm import VoxCPM
model = VoxCPM.from_pretrained(
str(root / "voxcpm2"), load_denoiser=False, optimize=False
)
import random
import torch
# VoxCPM 2.0.3 使用进程内生成器;每项作业独占模型子进程。
torch.manual_seed(p["seed"])
np.random.seed(p["seed"])
random.seed(p["seed"])
ref = inputs.get("reference_path")
if ref and not 0.5 <= sf.info(ref).duration <= 30:
raise ValueError("Voice reference must be between 0.5 and 30 seconds")
text, options, mode = synthesis_controls(inputs, p)
wav = model.generate(
text=text, cfg_value=2.0, inference_timesteps=10, retry_badcase=False, **options
)
if not np.isfinite(wav).all() or not wav.size or not np.abs(wav).max() > 0.001:
raise ValueError("Empty or invalid synthesized speech")
path = out / "speech.wav"
src = out / ".runtime" / "speech-native.wav"
sf.write(src, wav, model.tts_model.sample_rate)
subprocess.run(
[
"ffmpeg",
"-nostdin",
"-v",
"error",
"-threads",
"2",
"-i",
str(src),
"-af",
f"atempo={p.get('speed', 1)}",
"-ac",
"1",
"-ar",
"48000",
str(path),
],
check=True,
timeout=120,
)
return [path], {
"voice": p["voice"],
"seed": p["seed"],
"style": p.get("style", ""),
"synthesis_mode": mode,
"reference_sha256": digest(ref) if ref else None,
"sample_rate": 48000,
"sample_count": sf.info(path).frames,
}
def run(request):
import os
import cv2
import torch
threads = max(1, min(2, int(os.environ.get("OMP_NUM_THREADS", "2"))))
cv2.setNumThreads(threads)
torch.set_num_threads(threads)
root = Path("/workspace/models/dialogue-v1")
out = Path(request["output_dir"])
inp = request["input"]
p = request["parameters"]
task = request["task_type"]
if task == SPEECH_INSPECT:
from .audio_quality import inspect_speech
return inspect_speech(inp, p, root, out)
if task == SPEECH:
return speech(inp, p, root, out)
if task == ANALYZE:
from .analysis import analyze
return analyze(inp, p, root, out)
source = inp.get("base_video_path", inp["video_path"])
n = p["num_frames"]
width, height = probe(source, n)
report = read_tracks(inp["face_tracks_path"])
source_sha = digest(source)
stems = inp.get("speech_tracks") or [
{
"speaker_id": p["speaker_id"],
"target_track_id": p["target_track_id"],
"audio_path": inp["audio_path"],
}
]
rows = []
for stem in stems:
boxes = target_boxes(report, {**p, **stem}, source_sha, width, height)
track = next(
x for x in report["tracks"] if x["track_id"] == stem["target_track_id"]
)
wave = dry_audio(stem["audio_path"], n)
rows.append((stem, boxes, track["landmarks"], wave))
if task == INSPECT:
from .quality import inspect
active = {stem["speaker_id"] for stem in stems}
listeners = [tr for tr in report["tracks"] if tr["speaker_id"] not in active]
for tr in listeners:
target_boxes(
report,
{
**p,
"target_track_id": tr["track_id"],
"speaker_id": tr["speaker_id"],
},
source_sha,
width,
height,
)
return inspect(source, inp["video_path"], rows, p, root, out, listeners)
if p["profile"] == LATENTSYNC_PREVIEW:
if len(report["tracks"]) != 1 or len(rows) != 1:
raise ValueError("LatentSync preview requires exactly one visible bound face")
from .latentsync_preview import render
else:
from .lipsync import render
return render(source, width, height, rows, p, root, out)