"""对白生成任务仅通过带租约的推理队列调用。""" import re from pathlib import Path from app.domain.errors import MediaError from .contracts import _int, _float, _keys, _string, _invalid ADAPTER_CONTRACT_VERSION = "dialogue-v1" SILENCE_POLICY = "neutral-rest-v1" SOURCE_REST_POLICY = "source-rest-v2" SILENCE_POLICIES = (SILENCE_POLICY, SOURCE_REST_POLICY) LATENTSYNC_PREVIEW_PROFILE = "latentsync16-preview-v1" MOUTH_BLEND_POLICY = "semantic-skin-ellipse-v1" AUDIO_CONTEXT_SHIFT_POLICY = "bounded-feature-shift-v1" CONTENT_REVIEW_POLICY = "whisper-sensevoice-exact-v1" SENSEVOICE_REVISION = "90c1c61912018b70ada0fcc024ea24aca62f2e63" SENSEVOICE_RUNTIME = "6991744856587fa44379e8b5dcc432debffeb1be" SPEECH = "audio.dialogue.speech" SPEECH_INSPECT = "audio.dialogue.inspect" ANALYZE = "video.dialogue.analyze" SYNC = "video.lipsync" INSPECT = "video.dialogue.inspect" KEYS = { SPEECH_INSPECT: "speech_inspect", SPEECH: "speech", ANALYZE: "analyze", SYNC: "lipsync", INSPECT: "inspect", } ASSET_KINDS = { "video_asset_id": "video", "base_video_asset_id": "video", "audio_asset_id": "audio", "reference_asset_id": "audio", "face_tracks_asset_id": "json", } REVISIONS = { SPEECH_INSPECT: "f0c48c298fd835726c27956a5d617bad7115627e", SPEECH: "7936080b41163874f38610f46f438e2c0757f9fd", ANALYZE: "af6d057c9b0ec4071d4c49c80e3539258798b609", SYNC: "c9ac4cdcedcae22c186fbbf67261961e246c4760", INSPECT: "907c0b579c2e2d83f0eae1b2ac9e720cde4e5623", } def enabled(settings, task): flag = ( "dialogue_speech_enabled" if task in (SPEECH, SPEECH_INSPECT) else "dialogue_lipsync_enabled" ) return bool(getattr(settings, flag, False)) def profile(task): if task == SPEECH_INSPECT: return "dialogue-audio-v1" return "voxcpm2-v1" if task == SPEECH else "musetalk-v15-v1" def select_evidence(dialogue, task, policy=SOURCE_REST_POLICY): if not isinstance(dialogue, dict): return {} if task in (SYNC, INSPECT) and "silence_policies" in dialogue: policies = dialogue["silence_policies"] dialogue = policies.get(policy) if isinstance(policies, dict) else None return dialogue.get(KEYS[task], {}) if isinstance(dialogue, dict) else {} def certified(task, evidence, expected_policy=SOURCE_REST_POLICY): return ( isinstance(evidence, dict) and evidence.get("available") is True and evidence.get("profile") == profile(task) and evidence.get("adapter_contract_version") == ADAPTER_CONTRACT_VERSION and evidence.get("task_type") == task and evidence.get("decision") == "pass" and ( task not in (SYNC, INSPECT) or expected_policy in SILENCE_POLICIES and evidence.get("speech_silence_policy") == expected_policy ) and (task not in (SYNC, INSPECT) or evidence.get("mouth_blend_policy") == MOUTH_BLEND_POLICY) and (task != SYNC or evidence.get("audio_context_shift_policy") == AUDIO_CONTEXT_SHIFT_POLICY) and (task != SPEECH_INSPECT or evidence.get("content_review_policy") == CONTENT_REVIEW_POLICY) and bool(re.fullmatch("[0-9a-f]{64}", str(evidence.get("report_sha256", "")))) and task in REVISIONS and evidence.get("revision") == REVISIONS[task] and type(evidence.get("max_people")) is int and evidence["max_people"] in (1, 2) ) def _id(value): if not isinstance(value, str) or not re.fullmatch("[0-9a-f]{32}", value): raise _invalid("需要有效的素材或角色编号。") def validate(task, inputs, p): preview = isinstance(p, dict) and p.get("profile") == LATENTSYNC_PREVIEW_PROFILE if not isinstance(p, dict) or ( p.get("profile") != profile(task) and not (task == SYNC and preview) ): raise _invalid("对白模型版本不匹配。") if task == SPEECH_INSPECT: _keys(inputs, {"audio_asset_id", "reference_asset_id", "speaker_id", "expected_text"}) _keys(p, {"profile", "sample_rate", "source_start_sample", "source_end_sample", "native_av_policy"}) if "native_av_policy" in p and p["native_av_policy"] != "native_av_v1": raise _invalid("原生对白识别策略无效。") start = _int(p.get("source_start_sample", 0), 0, 2**40) if p.get("source_end_sample") is not None: _int(p["source_end_sample"], start + 1, 2**40) _id(inputs.get("audio_asset_id")) _id(inputs.get("speaker_id")) _string(inputs.get("expected_text"), 2000, required=p.get("native_av_policy") != "native_av_v1") _int(p.get("sample_rate"), 48000, 48000) if "reference_asset_id" in inputs: _id(inputs["reference_asset_id"]) if inputs["reference_asset_id"] == inputs["audio_asset_id"]: raise _invalid("标准声线必须来自独立参考。") return if task == SPEECH: _keys(inputs, {"prompt", "reference_asset_id"}) _keys(p, {"profile", "voice", "style", "speed", "seed", "reference_text"}) _string(inputs.get("prompt"), 2000) if "reference_asset_id" in inputs: _id(inputs["reference_asset_id"]) if p.get("reference_text") and "reference_asset_id" not in inputs: raise _invalid("参考文本需要对应语音素材。") _string(p.get("voice"), 200) _string(p.get("style", ""), 500, required=False) _string(p.get("reference_text", ""), 2000, required=False) _float(p.get("speed", 1), 0.5, 2) _int(p.get("seed"), 0, 2**32 - 1) return fields = {"video_asset_id"} controls = {"profile", "fps", "num_frames"} if task == ANALYZE: fields.add("reference_asset_ids") controls.add("speaker_ids") for values in (inputs.get("reference_asset_ids"), p.get("speaker_ids")): if not isinstance(values, list) or not 1 <= len(values) <= 2: raise _invalid("需要一至两个角色和对应参考图。") for value in values: _id(value) if len(set(values)) != len(values): raise _invalid("角色或参考图不能重复。") if len(inputs["reference_asset_ids"]) != len(p["speaker_ids"]): raise _invalid("角色与参考图数量不一致。") else: fields.add("face_tracks_asset_id") controls.update({"seed", "speech_silence_policy"}) if p.get("speech_silence_policy", SILENCE_POLICY) not in SILENCE_POLICIES: raise _invalid("对白静音策略不受支持。") if task == SYNC: controls.add("audio_context_shift_frames") _int(p.get("audio_context_shift_frames", 0), -6, 6) if preview: _int(p.get("num_frames"), 1, 144) tracks = inputs.get("speech_tracks") if isinstance(inputs, dict) else None if ( p.get("speech_silence_policy") != SOURCE_REST_POLICY or p.get("audio_context_shift_frames", 0) != 0 or not isinstance(tracks, list) or len(tracks) != 1 ): raise _invalid("试验口型仅支持单发言人、源画面静音策略和零偏移。") if "speech_tracks" in inputs: fields.add("speech_tracks") rows = inputs["speech_tracks"] if not isinstance(rows, list) or not 1 <= len(rows) <= 2: raise _invalid("每镜需要一至两个独立干声。") for row in rows: names = {"speaker_id", "target_track_id", "audio_asset_id"} _keys(row, names) for name in names: _id(row.get(name)) for name in ("speaker_id", "target_track_id", "audio_asset_id"): if len({row[name] for row in rows}) != len(rows): raise _invalid("双人干声或人物绑定重复。") else: fields.add("audio_asset_id") controls.update({"speaker_id", "target_track_id"}) _id(p.get("speaker_id")) _id(p.get("target_track_id")) _int(p.get("seed", 0), 0, 2**32 - 1) if task == INSPECT: fields.add("base_video_asset_id") _keys(inputs, fields) _keys(p, controls) for field in fields - {"reference_asset_ids", "speech_tracks"}: _id(inputs.get(field)) _int(p.get("fps"), 24, 24) _int(p.get("num_frames"), 1, 345) def approved_sample(settings, task, inputs, p, context=None): import hashlib, json, time root = getattr(settings, "state_root", None) if not isinstance(context, dict) or any( not re.fullmatch("[0-9a-f]{32}", str(context.get(k, ""))) for k in ("owner_id", "job_id") ): return False if not root or p.get("num_frames", 1) > 144 or len(inputs.get("prompt", "")) > 240: return False key = hashlib.sha256( json.dumps( [task, inputs, p], sort_keys=True, separators=(",", ":"), ensure_ascii=False ).encode() ).hexdigest() try: receipt = json.loads((Path(root) / "dialogue-calibration" / (key + ".json")).read_bytes()) now = time.time() if ( receipt.get("sha256") != key or receipt.get("owner_id") != context["owner_id"] or not now < receipt["expires_at"] <= now + 86400 ): return False # 同一请求只允许一个业务任务消费。硬链接的发布原子;重试保留原job绑定。 import os, tempfile folder = Path(root) / "dialogue-calibration" claim = folder / (key + ".used") with tempfile.NamedTemporaryFile(dir=folder, delete=False) as tmp: tmp.write(context["job_id"].encode()) try: try: os.link(tmp.name, claim) except FileExistsError: pass return claim.read_text() == context["job_id"] finally: Path(tmp.name).unlink(missing_ok=True) except (OSError, ValueError, TypeError, KeyError): return False async def approved_cpu_review(provider, inputs, p, assets): import asyncio, hashlib, json from app.services.normalized_cache import active_cache from app.services.artifacts import digest_file job = active_cache.get() bounds = inputs.get("expected", {}) if ( job is None or not 1 <= bounds.get("source_end_frame", 0) - bounds.get("source_start_frame", 0) <= 144 ): return False key = hashlib.sha256( json.dumps( ["video.dialogue.review", inputs, p], sort_keys=True, separators=(",", ":"), ensure_ascii=False, ).encode() ).hexdigest() try: receipt = json.loads( ( Path(provider.settings.state_root) / "dialogue-calibration" / (key + ".json") ).read_bytes() ) expected = receipt["asset_sha256"] ids = {inputs["video_asset_id"], *inputs.get("reference_asset_ids", [])} if set(expected) != ids: return False for aid in ids: path = provider._asset(aid, assets) if await asyncio.to_thread(digest_file, path) != expected[aid]: return False except (OSError, ValueError, TypeError, KeyError): return False return approved_sample( provider.settings, "video.dialogue.review", inputs, p, {"owner_id": job.owner, "job_id": job.job_id}, ) def visible_faces(path): import json try: with Path(path).open("rb") as stream: raw = stream.read(2 * 1024 * 1024 + 1) if len(raw) > 2 * 1024 * 1024: raise ValueError doc = json.loads(raw) tracks = doc["tracks"] if doc["decision"] == "pass" and isinstance(tracks, list) and 1 <= len(tracks) <= 2: return len(tracks) except (OSError, ValueError, KeyError, TypeError): pass raise _invalid("人脸轨迹记录无效。") async def prepare(provider, task, inputs, parameters, assets, context=None): if task == SPEECH_INSPECT and parameters.get("native_av_policy") == "native_av_v1": from .native_av import alignment_available, ALIGNMENT_REASON validate(task,inputs,parameters) if not await alignment_available(provider): raise MediaError("capability_unavailable",ALIGNMENT_REASON) out={key:value for key,value in inputs.items() if key in {"speaker_id","expected_text"}} for key in ("audio_asset_id","reference_asset_id"): if key in inputs: path=Path(provider._asset(inputs[key],assets)) out[key.removesuffix("_asset_id")+"_path"]=await provider._upload_input(path) if provider.settings.inference_remote_files else str(path) return dict(task_type=task,input=out,parameters=dict(parameters),timeout_seconds=1800) preview = parameters.get("profile") == LATENTSYNC_PREVIEW_PROFILE if preview: validate(task, inputs, parameters) sample = approved_sample(provider.settings, task, inputs, parameters, context) if preview and not sample: raise MediaError("capability_unavailable", "试验口型需要与所有者和本次任务绑定的校准票据。") if not sample and not enabled(provider.settings, task): raise MediaError("capability_unavailable", "本地尚未启用此对白能力。") people = max(len(inputs.get("speech_tracks", [])), len(parameters.get("speaker_ids", []))) if task in (SYNC, INSPECT): import asyncio path = provider._asset(inputs["face_tracks_asset_id"], assets) people = max(people, await asyncio.to_thread(visible_faces, path)) if preview and people != 1: raise _invalid("试验口型要求画面只出现一个人。") if ( people > 1 and not sample and not getattr(provider.settings, "dialogue_two_faces_enabled", False) ): raise MediaError("capability_unavailable", "尚未启用双人对白。") snap = {} if preview else await provider.upstream_capabilities() silence_policy = parameters.get("speech_silence_policy", SILENCE_POLICY) evidence = select_evidence(snap.get("dialogue"), task, silence_policy) if not sample and not certified(task, evidence, silence_policy): raise MediaError("capability_unavailable", "对白模型尚未完成此项实测认证。") if task == SYNC and parameters.get("audio_context_shift_frames", 0) and not sample and evidence.get("audio_context_shift_policy") != AUDIO_CONTEXT_SHIFT_POLICY: raise MediaError("capability_unavailable", "音频驱动时间补偿尚未通过实测。") if not sample and people > evidence.get("max_people", 1): raise MediaError("capability_unavailable", "同时在场人数超过已认证范围。") async def transfer(asset_id): path = Path(provider._asset(asset_id, assets)) return ( await provider._upload_input(path) if provider.settings.inference_remote_files else str(path) ) out = {} for key, value in inputs.items(): if key == "speech_tracks": out[key] = [ { "speaker_id": row["speaker_id"], "target_track_id": row["target_track_id"], "audio_path": await transfer(row["audio_asset_id"]), } for row in value ] elif key in {"prompt", "speaker_id", "expected_text"}: out[key] = value elif key == "reference_asset_ids": out["reference_paths"] = [await transfer(asset_id) for asset_id in value] else: out[key.removesuffix("_asset_id") + "_path"] = await transfer(value) upstream_parameters = dict(parameters) if task in (SYNC, INSPECT): # 旧图省略的参数仅在派发边界展开,保留其已冻结的输入摘要。 upstream_parameters["speech_silence_policy"] = silence_policy return { "task_type": task, "input": out, "parameters": upstream_parameters, "timeout_seconds": 1800, }