cmvr-visual/backend/app/domain/native_dialogue.py

269 lines
11 KiB
Python
Raw Normal View History

"""原生对白的纯作者投影;时长预算不是已经测得的语音时间。"""
from copy import deepcopy
from math import ceil
import re
from app.domain.stories import digest
from app.domain.video_generation import (
H3_NATIVE_AV_PROFILE,
H3_NATIVE_AV_TP2_PROFILE,
H3_TP2_PROFILE,
defaults,
)
LANGUAGES = {
"Chinese",
"English",
"Arabic",
"French",
"German",
"Italian",
"Japanese",
"Korean",
"Portuguese",
"Russian",
"Spanish",
}
def enabled(manifest):
return manifest.get("spec", {}).get("dialogue", {}).get("generation") == "native_av"
def _spoken_seconds(lines):
# 仅决定生成容量;字幕和内容验收一定使用生成后实际的词时间戳。
result = 0.0
for line in lines:
text = line.get("spoken_text") or line["text"]
cjk = len(re.findall(r"[\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]", text))
other_text = re.sub(r"[\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]", " ", text)
words = len(re.findall(r"[^\W_]+", other_text, flags=re.UNICODE))
result += cjk / 4 + words / 2.4 + 0.25
return result + 1.0
def compile_native_shots(manifest):
m = deepcopy(manifest)
spec, issues, result = m["spec"], [], []
dialogue = spec["dialogue"]
speakers = {s["id"]: s for s in dialogue["speakers"]}
lines = {u["id"]: u for u in dialogue["utterances"]}
sequences = {q["id"]: q for q in dialogue["sequences"]}
language = dialogue.get("language") or "Chinese"
allocations, used = {}, {}
def issue(code, sid, message):
issues.append(dict(code=code, unit_id=sid, message=message))
if not enabled(m):
issue("native_dialogue_upgrade_required", "dialogue", "请先升级为 H3 原生对白")
if language not in LANGUAGES:
issue("native_language_unsupported", "dialogue", "不支持此对白语言")
for shot in spec["shots"]:
sid, performance = shot["id"], shot["performance"]
seq = sequences.get(performance.get("sequence_id"), {})
assigned = performance.get("native_utterance_ids")
if not dialogue.get("enabled", True):
assigned = []
elif assigned is None:
if len(seq.get("shot_ids", [])) == 1:
assigned = list(seq.get("utterance_ids", []))
elif seq.get("utterance_ids"):
issue(
"native_utterance_assignment_required",
sid,
"请明确为每个镜头分配整句台词;反应镜头选择本镜头无对白",
)
assigned = []
else:
assigned = []
if len(set(assigned)) != len(assigned) or any(
uid not in seq.get("utterance_ids", []) for uid in assigned
):
issue(
"native_utterance_assignment_invalid", sid, "镜头台词必须是所属段落内不重复的台词"
)
allocations[sid] = [uid for uid in assigned if uid in lines]
for uid in assigned:
used.setdefault(uid, []).append(sid)
if dialogue.get("enabled", True):
for seq in dialogue["sequences"]:
for uid in seq["utterance_ids"]:
count = len(used.get(uid, []))
if count != 1:
issue(
"native_utterance_unassigned"
if not count
else "native_utterance_duplicate",
uid,
"每句台词必须且只能分配到一个镜头,不能跨镜截断",
)
position = 0
timing = []
for shot in spec["shots"]:
sid, perf, edit = shot["id"], shot["performance"], shot["edit"]
utterances = [lines[uid] for uid in allocations[sid]]
who = {u["speaker_id"] for u in utterances}
if len(perf.get("visible_speaker_ids", [])) > 1:
issue(
"native_two_faces_unavailable",
sid,
"双人同框尚未通过原生对白认证,请先按说话人切镜",
)
if len(who) > 1:
issue(
"native_multiple_speakers_in_shot", sid, "当前请按说话人切镜,每镜最多一个发言角色"
)
if any(speakers[key].get("voice", {}).get("reference_asset_id") for key in who):
issue(
"native_voice_reference_unsupported",
sid,
"FL2VA 原生对白不使用旧参考录音克隆,请明确解除录音约束并填写声线描述",
)
if any(u.get("source", "tts") == "asset" for u in utterances):
issue(
"native_recording_unsupported",
sid,
"当前 FL2VA 原生对白使用台词和声线描述,不接收指定录音驱动",
)
if shot.get("continuity", {}).get("transition") == "continue":
issue(
"native_continuity_unavailable",
sid,
"原生对白当前使用正常切镜,连续动作衔接需另行认证",
)
if shot.get("continuity", {}).get("endpoint_mode") == "first_last_frame":
issue(
"native_last_frame_unavailable",
sid,
"故事原生对白首版仅使用首帧,尾帧约束需单独配置认证",
)
source = shot["video_parameters"]
profile = (
H3_NATIVE_AV_TP2_PROFILE
if source.get("profile") in {H3_TP2_PROFILE, H3_NATIVE_AV_TP2_PROFILE}
else H3_NATIVE_AV_PROFILE
)
maximum = 158 if profile == H3_NATIVE_AV_TP2_PROFILE else 345
requested = source.get("source_frames", ceil(source.get("source_seconds", 5) * 24))
required = max(124, requested, edit["start_frame"] + edit["duration_frames"])
if perf.get("duration_mode", "auto") == "auto":
required = max(required, ceil(_spoken_seconds(utterances) * 24) if utterances else 124)
frames = 124 + 17 * ceil(max(0, required - 124) / 17)
if frames > maximum:
issue(
"native_dialogue_too_long",
sid,
"整句台词或镜头时长超过原生配置容量,请拆分台词和镜头或改用单卡",
)
frames = maximum
if (
perf.get("duration_mode") == "fixed"
and utterances
and _spoken_seconds(utterances) * 24 > frames
):
issue(
"native_fixed_speech_capacity",
sid,
"固定镜头时长不足以容纳整句台词及闭口余量,请增加原生帧数或拆分镜头",
)
if perf.get("duration_mode") == "fixed" and (
edit["start_frame"] or edit.get("dedup_frames", 0) or edit["duration_frames"] != frames
):
issue(
"native_fixed_timing_invalid",
sid,
"原生对白固定时长须采用完整原生帧数且从第零帧开始,不能截掉台词",
)
edit.update(start_frame=0, duration_frames=frames, dedup_frames=0)
params = defaults(profile)
portrait = spec.get("profile") == "portrait_1080_v1"
params.update(
width=768 if portrait else 1344,
height=1344 if portrait else 768,
num_frames=frames,
num_inference_steps=source.get("steps", source.get("num_inference_steps", 50)),
seed=source.get("seed", 42),
upscale=False,
)
visual = "\n".join(s for s in (shot.get("visual_prompt"), shot.get("motion_prompt")) if s)
spoken = []
for u in utterances:
speaker = speakers[u["speaker_id"]]
number = 1 + next(
i for i, sp in enumerate(dialogue["speakers"]) if sp["id"] == speaker["id"]
)
voice = speaker.get("native_voice") or "自然、清晰且有辨识度的声音"
text = u.get("spoken_text") or u["text"]
if any(token in text for token in ("<d>", "</d>", "<scenetrans>", "<cutoff>")):
issue(
"native_dialogue_control_token", u["id"], "台词不能包含模型的保留对白控制标记"
)
visible = (
speaker["id"] in perf.get("visible_speaker_ids", [])
and perf.get("lip_sync") != "off"
)
delivery = ",".join(x for x in (voice, u.get("delivery", "")) if x)
action = "says" if visible else "says in an off-screen voiceover"
spoken.append(
f"{speaker['name']} (S{number})"
+ f" with the following voice and delivery: {delivery}; {action}: <d>[{language}] {text}</d>"
+ ("" if visible else " while every on-screen character keeps their lips closed.")
)
prompt = (
"integrated_multimodal_description: [Shot 1] "
+ visual
+ "\n"
+ "\n".join(spoken)
+ (
"\nSpeak exactly the supplied dialogue in order. Finish the last sentence before the final half-second, then react naturally with relaxed closed lips. Other people remain silent; no additional words or voices."
if utterances
else "\nNo dialogue, singing, voiceover, or speech. All characters keep their lips naturally at rest while performing visible body and eye movements."
)
+ "\noverall_soundscape: Quiet natural room tone and subtle physical movement sounds, no other voices."
"\nnon_diegetic_music: N/A"
)
context = digest(
{
"contract": "native-dialogue-v1",
"shot": {k: v for k, v in shot.items() if k != "edit"},
"context": spec.get("context"),
"scenes": spec.get("scenes"),
"entities": spec.get("entities"),
"utterances": utterances,
"voices": [
{"id": key, "native_voice": speakers[key].get("native_voice")}
for key in sorted(who)
],
"language": language,
"parameters": params,
"prompt": prompt,
}
)
result.append(
dict(
shot_id=sid,
utterance_ids=allocations[sid],
speaker_id=next(iter(who), None),
parameters=params,
prompt=prompt,
context_hash=context,
)
)
timing.append(
dict(
shot_id=sid,
start_frame=position,
end_frame=position + frames,
contribution_frames=frames,
source_start_frame=0,
)
)
position += frames
return dict(
manifest=m, shots=result, issues=issues, timing={"shots": timing, "total_frames": position}
)