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

359 lines
15 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.

"""原生对白的纯作者投影;时长预算不是已经测得的语音时间。"""
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
TURN_STAGING = "two_person_turns"
def _compile_turns(spec, shot, utterances, speakers, issue):
sid, perf = shot["id"], shot["performance"]
visible = perf.get("visible_speaker_ids", [])
speaking = [u["speaker_id"] for u in utterances]
if (
spec.get("schema_version") != 6
or len(speaking) != 2
or len(set(speaking)) != 2
or len(visible) != 2
or set(visible) != set(speaking)
or not perf.get("native_utterance_ids")
or perf.get("lip_sync") == "off"
):
issue("native_turn_assignment_invalid", sid, "同框首发需要两位在场角色依次各说一句")
return []
if (
spec.get("profile") == "portrait_1080_v1"
or spec["dialogue"].get("language", "Chinese") != "Chinese"
):
issue("native_turn_scope_invalid", sid, "同框首发仅支持中文横屏固定双人中近景")
for field in ("model_speaker_number", "face_reference_asset_id", "voice_reference_asset_id"):
values = [speakers[key].get(field) for key in speaking]
if not all(values) or len(set(values)) != 2:
issue(
"native_turn_reference_required",
sid,
"请分别绑定两位角色的稳定编号、独立参考脸及验声样本",
)
break
if not perf.get("first_frame_sha256"):
issue("native_turn_frame_required", sid, "请确认双人首帧中从左到右的角色对应")
controls = ("<d>", "</d>", "<scenetrans>", "<cutoff>")
author_fields = [
shot.get("visual_prompt", ""),
shot.get("motion_prompt", ""),
*perf.get("listener_reactions", {}).values(),
*(u.get("delivery", "") for u in utterances),
*(speakers[k].get("native_voice") or "" for k in speaking),
]
if any(token in field for field in author_fields for token in controls):
issue(
"native_dialogue_control_token",
sid,
"画面、声线和听者动作不能包含模型保留的对白控制标记",
)
return [
dict(
utterance_id=u["id"],
speaker_id=u["speaker_id"],
listener_id=speaking[1 - i],
listener_reaction=perf.get("listener_reactions", {}).get(u["id"], "安静倾听"),
)
for i, u in enumerate(utterances)
]
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}
duo = perf.get("dialogue_staging") == TURN_STAGING
turns = _compile_turns(spec, shot, utterances, speakers, issue) if duo else []
if not duo and len(perf.get("visible_speaker_ids", [])) > 1:
issue(
"native_two_faces_unavailable",
sid,
"双人同框尚未通过原生对白认证,请先按说话人切镜",
)
if not duo and 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 index, u in enumerate(utterances):
speaker = speakers[u["speaker_id"]]
number = 1 + next(
i for i, sp in enumerate(dialogue["speakers"]) if sp["id"] == speaker["id"]
)
# V6 单人镜头可仅用一个局部编号。已指定编号的角色始终沿用作者编号。
number = speaker.get("model_speaker_number") or (1 if spec["schema_version"] == 6 else number)
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"
if turns:
turn = turns[index]
side = "左侧" if perf["visible_speaker_ids"][0] == speaker["id"] else "右侧"
listener = speakers[turn["listener_id"]]["name"]
spoken.append(
f"{side}{speaker['name']} (S{number}),声线与语气:{delivery},说:<d>[Chinese] {text}</d>。"
f"{listener}闭唇,{turn['listener_reaction']}。发言结束后{speaker['name']}自然闭唇。"
)
continue
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] "
+ ("固定双人中近景,两张脸持续同框,不切镜。\n" if duo else "")
+ 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": (
[s for s in spec.get("scenes", []) if s["id"] == shot.get("scene_id")]
if spec["schema_version"] == 6
else spec.get("scenes")
),
"entities": (
sorted((
e
for e in spec.get("entities", [])
if e["id"] in {c["entity_id"] for c in shot.get("cast", [])}
), key=lambda entity: entity["id"])
if spec["schema_version"] == 6
else 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=None if duo else next(iter(who), None),
**(
dict(turns=turns, first_frame_sha256=perf.get("first_frame_sha256"))
if duo
else {}
),
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}
)