"""V5对白的两阶段持久编排。此模块不加载模型或直接处理媒体。""" from copy import deepcopy from math import isfinite from types import SimpleNamespace from fastapi import HTTPException from sqlalchemy import select from app.core.errors import fail from app.domain.video_generation import H3_PROFILES, H3_TP2_PROFILE, H3_V2_PROFILE, recipe_parameters from app.adapters.provider.dialogue_gpu import SILENCE_POLICY, SOURCE_REST_POLICY from app.adapters.provider.dialogue_media import SOURCE_VISUAL_POLICY from app.domain.dialogue import ( prepare_dialogue, speech_content_hash, speech_stem_id, has_continuity, ) from app.domain.errors import MediaError from app.domain.stories import compile_story, canvas from app.domain.tasks import TERMINAL from app.models import ( Asset, AssetReference, Job, WorkflowRun, WorkflowStep, Execution, User, utcnow, ) from app.services.workflows import digest, verified_output, emit_run def enabled(value): return value.get("schema_version") == 3 and value.get("spec", {}).get("schema_version") == 5 def execution_recipes(run): return [ *(run.plan_snapshot or {}).get("steps", []), *(run.prepared_plan or {}).get("steps", []), ] def _recipe( key, kind, unit, binding=None, *, dependencies=(), inputs=None, parameters=None, context=None, reuse=None, forced=False, ): return dict( key=key, kind=kind, unit_id=unit, binding_key=binding, dependencies=[] if reuse else list(dependencies), input=inputs or {}, parameters=parameters or {}, context_hash=context, reuse=deepcopy(reuse), forced=forced, ) def _voice_preview(body): targets = body.get("targets", []) return ( body.get("output_goal") == "media" and bool(targets) and all(t.startswith(("speech:", "normalized_speech:", "audio:")) for t in targets) ) def _targets(manifest, body, children=None): if body.get("output_goal", "film") == "film" or not body.get("targets") or _voice_preview(body): return {} selected = {} for target in [*body["targets"], *body.get("force", [])]: role, _, sid = target.partition(":") if role in {"speech", "normalized_speech", "audio"}: collection = ( manifest["audio"]["segments"] if role == "audio" else manifest["spec"]["dialogue"]["utterances"] ) if sid not in {item["id"] for item in collection}: fail(422, "invalid_target", "配音目标不存在") continue if role not in { "frame", "video", "base_video", "selected_video", "synced_video", "face_tracks", } or sid not in (children or manifest["shot_ids"]): fail(422, "invalid_target", "对白媒体目标不存在") for child in (children or {}).get(sid, [sid]): selected.setdefault(child, set()).add(role) return selected def preparation_recipes(manifest, reusable, body, settings, capabilities): dialogue = manifest["spec"]["dialogue"] speakers = {s["id"]: s for s in dialogue["speakers"]} selected = ( {t.partition(":")[2] for t in body.get("targets", [])} if _voice_preview(body) else None ) forced = set(body.get("force", [])) rows = [] targets = _targets(manifest, body) shots = {s["id"]: s for s in manifest["spec"]["shots"]} def needs_geometry(sid, seq): roles = targets.get(sid, set()) return bool( roles.intersection({"video", "synced_video"}) or roles - {"frame"} and seq["timing_mode"] == "auto" and shots[sid]["performance"]["duration_mode"] == "auto" ) seq_ids = { seq["id"] for seq in dialogue["sequences"] if any(needs_geometry(sid, seq) for sid in seq["shot_ids"]) } if targets: capabilities["sequence_ids"] = sorted(seq_ids) units = { uid for seq in dialogue["sequences"] if seq["id"] in seq_ids for uid in seq["utterance_ids"] } for index, utterance in enumerate(dialogue["utterances"] if dialogue["enabled"] else [], 1): uid = utterance["id"] if ( targets and uid not in units and not any( f"{role}:{uid}" in body.get("targets", []) for role in ("speech", "normalized_speech") ) ): continue if selected is not None and not any( f"{role}:{uid}" in body["targets"] for role in ("speech", "normalized_speech") ): continue voice = speakers[utterance["speaker_id"]]["voice"] context = speech_content_hash(utterance, voice, capabilities) raw_key, normalized_key = "speech:" + uid, "normalized_speech:" + uid force_raw = raw_key in forced raw = reusable.get(raw_key) if force_raw or raw and raw.get("context_hash") != context: raw = None inputs = {"prompt": utterance.get("spoken_text") or utterance["text"]} if utterance.get("source", "tts") == "asset": raw = reusable.get(raw_key) if raw and raw["asset_id"] != utterance["asset_id"]: raw = None kind = "dialogue.asset" inputs = {"asset_id": utterance["asset_id"]} parameters = {} elif voice["provider"] == "kokoro": kind = "audio.speech" parameters = { "model": getattr(settings, "tts_model", "kokoro-82m"), "voice": voice["voice"], "speed": voice.get("speed", 1), } else: kind = "audio.dialogue.speech" if voice.get("reference_asset_id"): inputs["reference_asset_id"] = voice["reference_asset_id"] parameters = dict( profile="voxcpm2-v1", voice=voice.get("voice", ""), style=",".join( s for s in (voice.get("style", ""), utterance.get("delivery", "")) if s ), speed=voice.get("speed", 1), seed=voice.get("seed", 42), reference_text=voice.get("reference_text", ""), ) item = _recipe( f"sp_{index:04d}", kind, uid, raw_key, inputs=inputs, parameters=parameters, context=context, reuse=raw, forced=force_raw, ) old = manifest.get("bindings", {}).get(raw_key, {}) if not raw and old.get("locked") and not force_raw: item["issue"] = { "code": "locked_dependency_changed", "unit_id": uid, "message": "已锁定配音与台词或声音设定不匹配", } if ( utterance.get("locked") and not raw and utterance.get("source", "tts") == "tts" and not force_raw ): item["issue"] = { "code": "locked_dependency_changed", "unit_id": uid, "message": "已锁定台词缺少有效配音,请明确重配或解除锁定", } actual_model = ( getattr(settings, "tts_model", "kokoro-82m") if voice["provider"] == "kokoro" else "voxcpm2" ) if utterance.get("source", "tts") == "tts" and ( voice["model"] != actual_model or voice["provider"] == "kokoro" and voice.get("seed", 42) != 42 ): item["issue"] = dict( code="unsupported_voice_parameter", unit_id=uid, message="音色模型或随机种子与当前适配器不符", ) rows.append(item) normalized = reusable.get(normalized_key) norm_context = ( digest({"speech_sha": raw["sha256"], "normalizer": "pcm48k-v1"}) if raw else None ) if ( force_raw or normalized_key in forced or not normalized or normalized.get("context_hash") != norm_context ): normalized = None rows.append( _recipe( f"sn_{index:04d}", "audio.normalize", uid, normalized_key, dependencies=[item["key"]], context=norm_context, reuse=normalized, ) ) if not _voice_preview(body): reference = voice.get("reference_asset_id") inputs = dict( expected_text=utterance.get("spoken_text") or utterance["text"], speaker_id=utterance["speaker_id"], ) if reference: inputs["reference_asset_id"] = reference params = dict( profile="dialogue-audio-v1", sample_rate=48000, source_start_sample=utterance.get("source_start_sample", 0), source_end_sample=utterance.get("source_end_sample"), ) qa_key = "speech_report:" + uid candidate = rows[-1] qa_context = ( _audio_qa_hash(inputs, normalized["sha256"], capabilities, params) if normalized else None ) previous_qa = reusable.get(qa_key) verified = ( previous_qa if qa_context and previous_qa and previous_qa.get("context_hash") == qa_context and qa_key not in forced else None ) qa = _recipe( f"sq_{index:04d}", "audio.dialogue.inspect", uid, qa_key, dependencies=[candidate["key"]], inputs=inputs, parameters=params, context=qa_context, reuse=verified, ) qa.update( candidate_key=candidate["key"], repair_root=item["key"], can_repair=utterance.get("source", "tts") == "tts" and not utterance.get("locked"), ) if not reference or reference == utterance.get("asset_id"): qa["issue"] = dict( code="missing_voice_reference", unit_id=uid, message="请为角色提供独立的音色核验参考音频", ) rows.append(qa) narration = ( manifest.get("audio", {}).get("segments", []) if manifest.get("audio", {}).get("mode") == "generated_narration" else [] ) if targets: narration = [s for s in narration if "audio:" + s["id"] in body.get("targets", [])] if selected is not None: narration = [s for s in narration if "audio:" + s["id"] in body["targets"]] missing = [ s for s in narration if not s["text"].strip() and (selected is None or s["id"] in selected) ] if missing: shots = {s["id"]: s for s in manifest["spec"]["shots"]} requests = [] for segment in missing: source = shots.get(segment.get("shot_id")) or manifest["spec"]["shots"][0] requests.append( dict( shot_id=segment["id"], name=source["name"], visual_prompt=source["visual_prompt"], motion_prompt=source["motion_prompt"], duration_frames=min(360, source["edit"]["duration_frames"]), ) ) rows.append( _recipe( "narration_script", "text.script.generate", "script", inputs={"shots": requests, "context": manifest["spec"].get("context", {})}, parameters={"model": getattr(settings, "qwen_model", "Qwen3.8-27B")}, ) ) for i, segment in enumerate(narration, 1): sid = segment["id"] if selected is not None and sid not in selected: continue params = dict( model=getattr(settings, "tts_model", "kokoro-82m"), voice=segment.get("voice") or manifest["audio"]["voice"], speed=segment.get("speed") or manifest["audio"].get("speed", 1), ) context = ( digest({"text": segment["text"], "parameters": params}) if segment["text"].strip() else None ) raw = reusable.get("audio:" + sid) if ( "audio:" + sid in forced or raw and raw.get("source") != "manual" and raw.get("context_hash") != context ): raw = None row = _recipe( f"np_{i:04d}", "audio.speech", sid, "audio:" + sid, dependencies=["narration_script"] if not segment["text"].strip() else [], inputs={"prompt": segment["text"]}, parameters=params, context=context, reuse=raw, forced="audio:" + sid in forced, ) row["narration"] = True rows.append(row) norm = _recipe(f"nn_{i:04d}", "audio.normalize", sid, dependencies=[row["key"]]) norm["narration"] = True rows.append(norm) speech_ids = {u["id"] for u in dialogue["utterances"]} if dialogue["enabled"] else set() available = {"audio:" + s["id"] for s in narration} | { role + ":" + uid for uid in speech_ids for role in ("speech", "normalized_speech") } if selected is not None and set(body["targets"]) - available: fail(422, "invalid_target", "试听台词已删除或不存在") # BGM/音效在准备阶段只归一化,最终混音不参与时长冻结屏障。 if body.get("output_goal", "film") == "film": layers = manifest.get("audio", {}).get("layers", []) aids = [l["asset_id"] for l in layers] if manifest["audio"]["mode"] == "manual_track" and manifest["audio"].get("track"): aids.append(manifest["audio"]["track"]["asset_id"]) for i, aid in enumerate(dict.fromkeys(aids), 1): rows.append(_recipe(f"ln_{i:04d}", "audio.normalize", aid, inputs={"asset_id": aid})) return rows async def _reusable(session, owner_id, manifest, settings): from .editor_engine import _asset result = {} for key, binding in manifest.get("bindings", {}).items(): role, _, sid = key.partition(":") shot = next((s for s in manifest["spec"]["shots"] if s["id"] == sid), None) minimum = ( shot["edit"]["start_frame"] + shot["edit"]["duration_frames"] if shot and role in {"video", "base_video"} and not (binding.get("provenance") or {}).get("dialogue_signature") else None ) if await _asset(session, owner_id, binding, settings, binding.get("kind"), minimum): result[key] = deepcopy(binding) return result def _audio_qa_hash(inputs, sha, capabilities, params): return digest( dict( selection=params, text=inputs["expected_text"], speaker=inputs["speaker_id"], source_sha=sha, reference_sha=capabilities.get("reference_shas", {}).get( inputs.get("reference_asset_id") ), adapter=capabilities.get("audio_qa_revision"), **( {"audio_qa_contract": capabilities["audio_qa_contract"]} if "audio_qa_contract" in capabilities else {} ), ) ) def _audio_qa_contract(): from app.adapters.provider import dialogue_gpu return { "content_review_policy": dialogue_gpu.CONTENT_REVIEW_POLICY, "secondary_asr_revision": dialogue_gpu.SENSEVOICE_REVISION, "secondary_runtime_revision": dialogue_gpu.SENSEVOICE_RUNTIME, } def _matches_audio_qa_contract(report, contract, verdict): source = report.get("content_decision_source") if contract is None: # Only the historical, single-decoder format can attest the old policy. return ( report.get("content_review_policy") is None and source is None and (verdict != "pass" or report.get("content_error_rate") == 0) ) if report.get("content_review_policy") != contract["content_review_policy"]: return False status = report.get("secondary_status") if status in {"completed", "unavailable"} and any( report.get(key) != contract[key] for key in ("secondary_asr_revision", "secondary_runtime_revision") ): return False if verdict != "pass": return True primary = report.get("primary_content_error_rate") if ( report.get("content_error_rate") != 0 or report.get("reasons") or type(primary) not in (int, float) ): return False if source == "whisper": return primary == 0 and status == "not_requested" secondary = report.get("secondary_transcript") return ( source == "sensevoice" and 0 < primary < 0.20 and status == "completed" and isinstance(secondary, str) and bool(secondary.strip()) and report.get("secondary_content_error_rate") == 0 ) def _capabilities(settings, assets=None): assets = assets or {} upstream = getattr(settings, "_dialogue_upstream", {}) speech = upstream.get("speech", {}) if isinstance(upstream, dict) else {} return dict( final_render_contract=_final_render_contract(), audio_qa_contract=_audio_qa_contract(), reference_shas={aid: a.sha256 for aid, a in assets.items()}, audio_qa_revision={ k: (upstream or {}).get("speech_inspect", {}).get(k) for k in ("revision", "adapter_contract_version", "report_sha256") }, adapter_versions={ "kokoro": { "adapter": "kokoro-wav-v1", "model": getattr(settings, "tts_model", "kokoro-82m"), }, "voxcpm2": { "revision": speech.get("revision"), "report_sha256": speech.get("report_sha256"), }, }, max_shots=60, max_total_frames=7200, ) def _minimum_contribution(manifest, caps): dialogue = manifest["spec"]["dialogue"] scoped = caps.get("sequence_ids") adjustable = { sid for seq in dialogue["sequences"] if dialogue["enabled"] and seq["utterance_ids"] and seq["timing_mode"] == "auto" and (scoped is None or seq["id"] in scoped) for sid in seq["shot_ids"] } total = 0 for shot in manifest["spec"]["shots"]: sid, edit = shot["id"], shot["edit"] frames = edit["duration_frames"] if ( sid in adjustable and shot["performance"]["duration_mode"] == "auto" and not any( manifest["bindings"].get(f"{role}:{sid}", {}).get("locked") for role in ("video", "base_video", "selected_video", "synced_video") ) ): frames = 24 total += frames - edit["dedup_frames"] return total async def _plan_editor(session, draft, manifest, body, settings, *, tp2_capability=None): from app.domain.editors import collect_manifest_asset_ids from app.adapters.provider.dialogue_gpu import certified, KEYS, SPEECH, ANALYZE, SYNC, INSPECT, select_evidence body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body assets = {} for aid in collect_manifest_asset_ids(manifest): asset = await session.get(Asset, aid) if ( not asset or asset.owner_id != draft.owner_id or asset.deleted_at or not asset.ready or asset.library_scope != "private" ): fail(404, "asset_not_found", "对白来源素材不存在或不可访问") assets[aid] = asset reusable = await _reusable(session, draft.owner_id, manifest, settings) caps = _capabilities(settings, assets) rows = preparation_recipes(manifest, reusable, body, settings, caps) targets = _targets(manifest, body) selected_shots = [s for s in manifest["spec"]["shots"] if not targets or s["id"] in targets] final_shots = [ s for s in selected_shots if not targets or targets[s["id"]].intersection({"video", "synced_video", "face_tracks"}) ] issues = [r["issue"] for r in rows if r.get("issue")] upstream = getattr(settings, "_dialogue_upstream", {}) for row in rows: if row["reuse"]: continue if row["kind"] == "audio.dialogue.inspect" and not ( getattr(settings, "dialogue_speech_enabled", False) and certified(row["kind"], upstream.get("speech_inspect", {})) ): issues.append( dict( code="capability_unavailable", unit_id=row["unit_id"], message="逐句语音质量模型尚未认证", ) ) if row["kind"] == "audio.speech" and not getattr(settings, "tts_base_url", ""): issues.append( dict( code="speech_unavailable", unit_id=row["unit_id"], message="中文配音服务尚未配置", ) ) if row["kind"] == "audio.dialogue.speech" and not ( getattr(settings, "dialogue_speech_enabled", False) and certified(SPEECH, upstream.get(KEYS[SPEECH], {})) ): issues.append( dict( code="capability_unavailable", unit_id=row["unit_id"], message="多音色配音尚未完成部署认证", ) ) if not _voice_preview(body): maximum = min(manifest["production"]["max_total_frames"], caps["max_total_frames"]) minimum = _minimum_contribution(manifest, caps) if minimum > maximum: issues.append( dict( code="dialogue_budget_exceeded", unit_id="production", message=f"最低贡献帧数 {minimum} 超过总帧预算 {maximum}", ) ) if final_shots and not getattr(settings, "dialogue_quality_certified", False): issues.append( dict( code="capability_unavailable", unit_id="quality", message="对白画面质量判断尚未完成小样认证", ) ) if ( final_shots and manifest["spec"]["dialogue"]["enabled"] and not manifest["spec"]["dialogue"]["utterances"] ): issues.append( dict(code="dialogue_required", unit_id="dialogue", message="请先添加角色台词") ) from .editor_engine import build_recipes needs_video = [s for s in selected_shots if not targets or targets[s["id"]] != {"frame"}] if any(s["video_parameters"].get("profile") == H3_V2_PROFILE for s in needs_video): issues.append( dict( code="capability_unavailable", unit_id="video", message="原生首尾帧配置尚未认证用于对白,请选普通切镜配置", ) ) tp2 = [s for s in needs_video if s["video_parameters"].get("profile") == H3_TP2_PROFILE] if tp2: forced = [ key.replace("base_video:", "video:", 1) for key in body.get("force", []) if key.startswith(("base_video:", "video:", "frame:")) ] quiet_shots = set() if caps["final_render_contract"].get("speech_silence_policy") == SOURCE_REST_POLICY: dialogue = manifest["spec"]["dialogue"] speakers_by_line = {u["id"]: u["speaker_id"] for u in dialogue["utterances"]} speakers_by_sequence = { seq["id"]: {speakers_by_line[uid] for uid in seq["utterance_ids"]} for seq in dialogue["sequences"] } quiet_shots = { s["id"] for s in tp2 if dialogue["enabled"] and targets.get(s["id"]) != {"face_tracks"} and s["performance"]["lip_sync"] != "off" and speakers_by_sequence.get(s["performance"]["sequence_id"], set()) .intersection(s["performance"]["visible_speaker_ids"]) } legacy = _legacy_manifest(manifest, reusable, quiet_shots, forced) dry = build_recipes( legacy, legacy["bindings"], dict(output_goal="media", targets=["video:" + s["id"] for s in tp2], force=forced), settings, compile_story(manifest["spec"], assets), ) generation = [ r for r in dry if r["kind"] == "video.generate" and not r["reuse"] and r["parameters"].get("profile") == H3_TP2_PROFILE ] for row in generation: try: recipe_parameters(row["parameters"], H3_TP2_PROFILE) except ValueError as exc: issues.append( dict(code="invalid_video_profile", unit_id=row["unit_id"], message=str(exc)) ) uncertain = any( s["performance"]["duration_mode"] == "auto" and any( seq["timing_mode"] == "auto" and s["id"] in seq["shot_ids"] for seq in manifest["spec"]["dialogue"]["sequences"] ) for s in tp2 ) and any( (r.get("binding_key") or "").startswith("normalized_speech:") and not r["reuse"] for r in rows ) repairable = any( s["id"] in quiet_shots and "frame:" + s["id"] in reusable and not any( manifest["bindings"].get(f"{role}:{s['id']}", {}).get("locked") for role in ("video", "synced_video", "base_video") ) for s in final_shots ) if generation or uncertain or (repairable and tp2_capability): caps["tp2_authorized"] = bool(tp2_capability and await tp2_capability()) if generation and not caps["tp2_authorized"]: issues.append( dict( code="capability_unavailable", unit_id="video", message="双卡生成尚未认证", ) ) if has_continuity(manifest): issues.append( dict( code="capability_unavailable", unit_id="dialogue", message="对白连续衔接需独立完成最终口型与首尾帧认证,请先使用正常切镜", ) ) visible = [ s for s in final_shots if manifest["spec"]["dialogue"]["enabled"] and s["performance"]["visible_speaker_ids"] and (s["performance"]["lip_sync"] != "off" or targets.get(s["id"]) == {"face_tracks"}) ] lip_shots = {s["id"] for s in visible if targets.get(s["id"]) != {"face_tracks"}} silence_policy = caps["final_render_contract"].get("speech_silence_policy", SILENCE_POLICY) face_ready = getattr(settings, "dialogue_lipsync_enabled", False) and certified( ANALYZE, upstream.get(KEYS[ANALYZE], {}) ) lip_certificates = {task: select_evidence(upstream, task, silence_policy) for task in (SYNC, INSPECT)} lip_ready = face_ready and all(certified(task, cert, silence_policy) for task, cert in lip_certificates.items()) speakers = {s["id"]: s for s in manifest["spec"]["dialogue"]["speakers"]} entities = {e["id"]: e for e in manifest["spec"]["entities"]} for shot in visible: refs = [ _identity_refs(entities.get(speakers[sid]["entity_id"], {}), shot) for sid in shot["performance"]["visible_speaker_ids"] ] if any(not r for r in refs) or len({r[0] for r in refs if r}) != len(refs): issues.append( dict( code="missing_face_reference", unit_id=shot["id"], message="每名可见人物需要独立的身份参考图", ) ) for s in selected_shots: perf = s["performance"] seq = next( ( q for q in manifest["spec"]["dialogue"]["sequences"] if q["id"] == perf["sequence_id"] ), {}, ) if ( perf["original_audio"] == "preserve" and manifest["spec"]["dialogue"]["enabled"] and len(seq.get("shot_ids", [])) == 1 and seq.get("utterance_ids") ): issues.append( dict( code="original_audio_conflict", unit_id=s["id"], message="保留的原片人声可能与新对白重叠,请选择丢弃原声或移至无对白段落", ) ) signed_locks = [ s for s in final_shots if (not targets or targets[s["id"]].intersection({"video", "synced_video"})) and (manifest["bindings"].get("video:" + s["id"], {}).get("provenance") or {}).get( "dialogue_signature" ) and manifest["bindings"]["video:" + s["id"]].get("locked") and "video:" + s["id"] not in body.get("force", []) ] if signed_locks: projected = prepare_dialogue(manifest, reusable, caps) projected["final_render_contract"] = caps["final_render_contract"] projections = {s["id"]: s for s in projected["effective_manifest"]["spec"]["shots"]} visuals = {s["shot_id"]: s for s in compile_story(manifest["spec"], assets)["shots"]} seqs = {q["id"]: q for q in manifest["spec"]["dialogue"]["sequences"]} unknown = { r["unit_id"] for r in rows if r["kind"] == "audio.normalize" and not r["reuse"] } for shot in signed_locks: sid = shot["id"] signature = _shot_signature( projected, projections[sid], visuals[sid], projected["effective_manifest"] ) if signature != manifest["bindings"]["video:" + sid]["provenance"][ "dialogue_signature" ] or unknown.intersection( seqs.get(shot["performance"]["sequence_id"], {}).get("utterance_ids", []) ): issues.append( dict( code="locked_dependency_changed", unit_id=sid, message="已锁定成片镜头,请明确重做该镜头后继续", ) ) if lip_shots and not lip_ready: issues.append( dict( code="capability_unavailable", unit_id="lipsync", message=f"口型模型的静音策略 {silence_policy} 尚未完成部署认证", ) ) elif visible and not face_ready: issues.append( dict(code="capability_unavailable", unit_id="face_tracks", message="人脸轨迹分析尚未完成部署认证") ) face_two_ready = ( face_ready and getattr(settings, "dialogue_two_faces_enabled", False) and upstream[KEYS[ANALYZE]].get("max_people", 1) >= 2 ) lip_two_ready = face_two_ready and lip_ready and all( cert.get("max_people", 1) >= 2 for cert in lip_certificates.values() ) if any( len(s["performance"]["visible_speaker_ids"]) > 1 and not (lip_two_ready if s["id"] in lip_shots else face_two_ready) for s in visible ): issues.append( dict( code="capability_unavailable", unit_id="lipsync", message="双人同框尚未通过独立认证,可先使用说话人切镜", ) ) if ( len(manifest["shot_ids"]) > 60 or len(manifest["spec"]["dialogue"]["utterances"]) + len(manifest["audio"].get("layers", [])) > 128 ): issues.append( dict( code="production_limit", unit_id="dialogue", message="镜头或混音片段超过单次制作上限", ) ) if manifest["spec"]["dialogue"]["enabled"] and ( manifest["audio"].get("mix_mode") == "manual_mix" or manifest["audio"].get("mode") == "manual_track" ): issues.append( dict( code="dialogue_audio_conflict", unit_id="audio", message="完整人工混音与自动对白不能重复叠加,请选择分轨对白模式", ) ) public = [ { "key": r["key"], "kind": r["kind"], "unit_id": r["unit_id"], "status": "reuse" if r["reuse"] else "generate", } for r in rows ] if not _voice_preview(body): public.append( dict( key="timing", kind="dialogue.timing.prepare", unit_id="dialogue", status="pending_dependency", ) ) for sid, roles in targets.items(): for role in sorted(roles): public.append( dict(key=role + ":" + sid, kind=role, unit_id=sid, status="pending_dependency") ) plan = dict( output_goal=body.get("output_goal", "film"), source_version=draft.version, steps=public, issues=issues, ) plan["plan_hash"] = digest( { "manifest": manifest, "body": {k: v for k, v in body.items() if k != "expected_plan_hash"}, "assets": caps["reference_shas"], "final_render_contract": caps["final_render_contract"], "audio_qa_contract": caps["audio_qa_contract"], "audio_qa_revision": caps["audio_qa_revision"], "steps": rows, "issues": issues, } ) plan["_recipes"], plan["_capabilities"] = rows, caps return plan async def plan_editor(session, draft, manifest, body, settings, *, tp2_capability=None): from app.domain.native_dialogue import enabled as native_enabled if native_enabled(manifest): from .native_dialogue_engine import plan_editor as native_plan plan = await native_plan(session, draft, manifest, body, settings) return {key: value for key, value in plan.items() if not key.startswith("_")} plan = await _plan_editor( session, draft, manifest, body, settings, tp2_capability=tp2_capability ) return {key: value for key, value in plan.items() if not key.startswith("_")} async def start_editor_run(session, draft, manifest, body, settings, *, tp2_capability=None): from app.domain.native_dialogue import enabled as native_enabled if not native_enabled(manifest): fail( 409, "native_dialogue_upgrade_required", "历史对白可读取和恢复;新制作请先启用 H3 原生对白", ) from .native_dialogue_engine import plan_editor as native_plan plan = await native_plan(session, draft, manifest, body, settings) return await _start_legacy_editor_run( session, draft, manifest, body, settings, _frozen_plan=plan ) async def _start_legacy_editor_run( session, draft, manifest, body, settings, *, tp2_capability=None, _frozen_plan=None ): body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body plan = _frozen_plan or await _plan_editor( session, draft, manifest, body, settings, tp2_capability=tp2_capability ) if body.get("expected_version") != draft.version: fail(409, "draft_version_conflict", "草稿已更新") if body.get("expected_plan_hash") != plan["plan_hash"]: fail(409, "plan_changed", "对白执行计划已改变") if plan["issues"]: fail(422, "editor_issues", {"message": "请先处理对白制作问题", "issues": plan["issues"]}) from app.services.quotas import check_parent_capacity from app.services.folders import owned_folder await check_parent_capacity(session, settings, draft.owner_id, "run") folder = body.get("output_folder_id", draft.folder_id) if folder: await owned_folder(session, folder, draft.owner_id, lock=True) run = WorkflowRun( owner_id=draft.owner_id, draft_id=draft.id, draft_revision=draft.revision, source_draft_version=draft.version, folder_id=draft.folder_id, output_folder_id=folder, run_kind="story_auto", output_goal=plan["output_goal"], base_run_id=manifest.get("base_run_id"), spec_snapshot=deepcopy(manifest["spec"]), spec_hash=digest(manifest["spec"]), phase="dialogue_preparation", plan_snapshot={ "manifest": deepcopy(manifest), "steps": plan["_recipes"], "plan_hash": plan["plan_hash"], "body": deepcopy(body), "capabilities": plan["_capabilities"], "asset_sha256": plan["_capabilities"]["reference_shas"], }, result_manifest=deepcopy(manifest), execution_mode=body.get("execution_mode", "interactive"), apply_state="pending", ) session.add(run) if plan.get("_prepared") is not None: run.prepared_plan = deepcopy(plan["_prepared"]) run.result_manifest = deepcopy(plan["_prepared"]["effective_manifest"]) run.phase = "native_production" await session.flush() for recipe in plan["_recipes"]: result = recipe["reuse"] session.add( WorkflowStep( run_id=run.id, step_key=recipe["key"], kind=recipe["kind"], dependencies=recipe["dependencies"], semantic_input_hash=digest(recipe), recipe_json=deepcopy(recipe), state="succeeded" if result else "waiting", result_json=deepcopy(result), ) ) from app.domain.editors import collect_manifest_asset_ids for aid in collect_manifest_asset_ids(manifest): session.add( AssetReference(owner_id=run.owner_id, asset_id=aid, ref_kind="run", ref_id=run.id) ) await session.flush() await emit_run(session, run, False) return run _QUIET_BASE_PROMPT = ( "生成安静的配音底片。只表演头肩、眼神与手势,嘴唇自然闭合并保持放松。" "动作描述中的说话或开合嘴唇属于后续配音要求,底片全程不说话、不做口型。\n" "动作描述:" ) def _quiet_base_motion(shot): return _QUIET_BASE_PROMPT + shot["motion_prompt"] def _legacy_manifest(manifest, reusable, quiet_shots=(), force=()): """仅复用已验证的基础画面规划器,不把对白数据投影回作者草稿。""" m = deepcopy(manifest) m["schema_version"] = 1 m["spec"]["schema_version"] = 3 m["spec"].pop("dialogue", None) m["spec"]["render"].update(audio=None, subtitles=[], total_frames=None) for shot in m["spec"]["shots"]: shot.pop("performance", None) if "source_frames" not in shot["video_parameters"]: shot.pop("continuity", None) shot["edit"].pop("dedup_frames", None) if shot["id"] in quiet_shots: shot["motion_prompt"] = _quiet_base_motion(shot) m["audio"] = {"mode": "silent", "voice": "", "speed": 1, "track": None, "segments": []} m["captions"] = {"mode": "none", "cues": []} bindings = {} for sid in m["shot_ids"]: for role in ("frame", "video"): value = reusable.get(("base_video:" if role == "video" else "frame:") + sid) if ( value is None and role == "video" and not (reusable.get("video:" + sid, {}).get("provenance") or {}).get( "dialogue_signature" ) ): value = reusable.get("video:" + sid) if value: key = f"{role}:{sid}" bindings[key] = deepcopy(value) if role == "video" and sid in quiet_shots and value.get("locked") and key not in force: # 已核实的锁定底片仍进入源画面质检。这里只投影复用资格。 bindings[key].update(source="manual", context_hash=None) m["bindings"] = bindings return m def _identity_refs(entity, shot): cast = next((c for c in shot["cast"] if c["entity_id"] == entity.get("id")), {}) for field, selected in (("appearances", "appearance_id"), ("forms", "form_id")): for variant in entity.get(field, []): if variant["id"] == cast.get(selected) and variant.get("reference_asset_ids"): return variant["reference_asset_ids"] return entity.get("reference_asset_ids", []) def _stem_segments(prepared, shot_id, speaker_id, manifest): result = [] for p in prepared["placements"]: if p["shot_id"] != shot_id or p["speaker_id"] != speaker_id: continue binding = manifest["bindings"]["normalized_speech:" + p["utterance_id"]] result.append( dict( asset_id=binding["asset_id"], source_start_sample=p["source_start_sample"], source_end_sample=p["source_end_sample"], offset_sample=p["shot_start_sample"], role="narration", segment_id=p["utterance_id"], ) ) return result DIALOGUE_FINAL_RECIPE = "dialogue-final-v5-bounded-sync" def _final_render_contract(): from app.adapters.provider import dialogue_gpu return dict( recipe=DIALOGUE_FINAL_RECIPE, speech_silence_policy=SOURCE_REST_POLICY, mouth_blend_policy=dialogue_gpu.MOUTH_BLEND_POLICY, audio_context_shift_policy=dialogue_gpu.AUDIO_CONTEXT_SHIFT_POLICY, adapter_contract_version=dialogue_gpu.ADAPTER_CONTRACT_VERSION, adapters={ task: {"profile": dialogue_gpu.profile(task), "revision": dialogue_gpu.REVISIONS[task]} for task in (dialogue_gpu.SYNC, dialogue_gpu.INSPECT) }, ) def _shot_signature(prepared, shot, compiled, manifest): spans = [] for item in prepared["placements"]: if item["shot_id"] == shot["id"]: spans.append( { k: item[k] for k in ( "utterance_id", "speaker_id", "source_start_sample", "source_end_sample", "visible", ) } ) spans[-1].update( start=item["shot_start_sample"], end=item["shot_end_sample"], sha=manifest["bindings"]["normalized_speech:" + item["utterance_id"]]["sha256"], ) sources = { role: manifest["bindings"].get(f"{role}:{shot['id']}", {}).get("sha256") for role in ("frame", "base_video") } contract = prepared.get("final_render_contract", {"recipe": "dialogue-final-v2"}) if ( contract.get("speech_silence_policy") == SOURCE_REST_POLICY and (shot["performance"]["lip_sync"] == "off" or not any(s["visible"] for s in spans)) ): # 无画内发言的镜头不经过口型,沿用其既有验收签名。 contract = {**contract, "speech_silence_policy": SILENCE_POLICY} return digest( dict( shot=shot, context=compiled["context_hash"], speech=spans, sources=sources, **contract, ) ) def production_recipes(prepared, reusable, body, settings, compiled): from .editor_engine import build_recipes manifest = prepared["effective_manifest"] children = prepared["provenance"]["shot_children"] targets = _targets(manifest, body, children) force = set() for key in body.get("force", []): role, _, uid = key.partition(":") shot_targets = ( children.get(uid, [uid]) if role in {"frame", "base_video", "video", "synced_video", "selected_video", "face_tracks"} else [uid] ) force.update(role + ":" + child for child in shot_targets) legacy_targets = [ ("frame:" if targets.get(sid) == {"frame"} else "video:") + sid for sid in manifest["shot_ids"] if not targets or sid in targets ] legacy_body = dict( output_goal="media", targets=legacy_targets, force=[ key.replace("base_video:", "video:", 1) for key in sorted(force) if key.startswith(("frame:", "base_video:", "video:")) ], ) for sid, roles in targets.items(): if "frame" in roles and "frame:" + sid not in legacy_body["targets"]: legacy_body["targets"].append("frame:" + sid) source_rest = ( prepared.get("final_render_contract", {}).get("speech_silence_policy") == SOURCE_REST_POLICY ) visible_dialogue = {p["shot_id"] for p in prepared["placements"] if p["visible"]} quiet_shots = { shot["id"] for shot in manifest["spec"]["shots"] if source_rest and shot["id"] in visible_dialogue and targets.get(shot["id"]) != {"face_tracks"} and shot["performance"]["lip_sync"] != "off" and shot["video_parameters"].get("profile") in H3_PROFILES } legacy = _legacy_manifest(manifest, reusable, quiet_shots, legacy_body["force"]) rows = build_recipes(legacy, legacy["bindings"], legacy_body, settings, compiled) for row in rows: if row["kind"] == "video.generate": sid = row["unit_id"] row["binding_key"] = "base_video:" + sid if sid in quiet_shots and (row["reuse"] or {}).get("locked"): row["reuse"] = deepcopy(reusable.get("base_video:" + sid) or reusable["video:" + sid]) if sid in quiet_shots and not row["reuse"] and len(row["input"]["prompt"]) > 8000: row["issue"] = dict( code="prompt_too_long", unit_id=sid, binding_key=row["binding_key"], message="静音底片规则与动作描述合计超出提示词上限,请缩短动作描述", ) by_binding = {row["binding_key"]: row["key"] for row in rows if row["binding_key"]} generated_keys = { row["key"] for row in rows if row["kind"] == "video.generate" and not row["reuse"] } final_dependencies = [] timing = {row["shot_id"]: row for row in prepared["timing"]["shots"]} speakers = {s["id"]: s for s in manifest["spec"]["dialogue"]["speakers"]} for i, shot in enumerate(manifest["spec"]["shots"], 1): sid, t = shot["id"], timing[shot["id"]] if not targets or targets.get(sid, set()) - {"frame"}: base = ( manifest["bindings"].get("base_video:" + sid) or manifest["bindings"].get("video:" + sid) or {} ) if ( base.get("locked") and not (base.get("provenance") or {}).get("dialogue_signature") and "base_video:" + sid not in reusable and "video:" + sid not in reusable and not {"base_video:" + sid, "video:" + sid}.intersection(force) ): fail(409, "locked_dependency_changed", "已锁定的原始底片不满足实际选段时长或校验") if targets and (sid not in targets or targets[sid] <= {"base_video", "frame"}): continue signature = _shot_signature(prepared, shot, compiled["shots"][i - 1], manifest) current = reusable.get("video:" + sid) related_force = {"frame:" + sid, "base_video:" + sid, "synced_video:" + sid, "video:" + sid} if ( (not targets or targets[sid] <= {"synced_video", "video"}) and current and (current.get("provenance") or {}).get("dialogue_signature") == signature and not related_force.intersection(force) ): rows = [r for r in rows if r["unit_id"] != sid] final_key = f"accepted_{i:04d}" rows.append(_recipe(final_key, "dialogue.accepted", sid, "video:" + sid, reuse=current)) final_dependencies.append(final_key) continue lock = manifest["bindings"].get("video:" + sid, {}) publish_final = not targets or bool(targets[sid].intersection({"video", "synced_video"})) if ( publish_final and lock.get("locked") and (lock.get("provenance") or {}).get("dialogue_signature") and "video:" + sid not in force ): fail(409, "locked_dependency_changed", "已锁定的最终镜头需要明确重做") base = ( manifest["bindings"].get("base_video:" + sid) or manifest["bindings"].get("video:" + sid) or {} ) if ( base.get("locked") and base.get("duration_frames") is not None and base["duration_frames"] < t["source_end_frame"] and not {"base_video:" + sid, "video:" + sid}.intersection(force) ): fail(409, "locked_dependency_changed", "已锁定底片的帧数不足") select_key = f"sel_{i:04d}" rows.append( _recipe( select_key, "video.dialogue.select", sid, "selected_video:" + sid, dependencies=[by_binding["base_video:" + sid]], parameters={ "start_frame": t["source_start_frame"] + t["dedup_frames"], "duration_frames": t["contribution_frames"], }, ) ) if targets.get(sid) == {"selected_video"}: continue references = list( dict.fromkeys(r["asset_id"] for r in compiled["shots"][i - 1].get("references", [])) ) expected = dict( source_start_frame=0, source_end_frame=t["contribution_frames"], fps=24, expected_motion=shot["continuity"].get("expected_motion", True), transition="cut", dedup_frames=0, visual=shot["visual_prompt"], motion=( _quiet_base_motion(shot) if sid in quiet_shots and (by_binding["base_video:" + sid] in generated_keys) else shot["motion_prompt"] ), characters=[speakers[s]["name"] for s in shot["performance"]["visible_speaker_ids"]], ) review_key = f"review_{i:04d}" review = _recipe( review_key, "video.dialogue.review", sid, dependencies=[select_key], inputs={"expected": expected, "reference_asset_ids": references[:3]}, ) review.update( repair_root=by_binding.get( "frame:" + sid, None if sid in quiet_shots else by_binding["base_video:" + sid] ), candidate_key=select_key, visual_context=compiled["shots"][i - 1]["context_hash"], final_signature=signature, ) rows.append(review) visible = shot["performance"]["visible_speaker_ids"] talking = [ speaker_id for speaker_id in visible if _stem_segments(prepared, sid, speaker_id, manifest) ] active = ( bool(talking) and shot["performance"]["lip_sync"] != "off" or "face_tracks" in targets.get(sid, set()) ) if active: face_key = f"face_{i:04d}" # 参考顺序必须与角色顺序一致,不能夹带场景图作为身份参考。 entity_map = {e["id"]: e for e in manifest["spec"]["entities"]} face_refs = [] for speaker_id in visible: entity = entity_map.get(speakers[speaker_id].get("entity_id"), {}) refs = _identity_refs(entity, shot) if refs: face_refs.append(refs[0]) rows.append( _recipe( face_key, "video.dialogue.analyze", sid, "face_tracks:" + sid, dependencies=[review_key], inputs={"reference_asset_ids": face_refs}, parameters=dict( profile="musetalk-v15-v1", fps=24, speaker_ids=visible, num_frames=t["contribution_frames"], ), ) ) if targets.get(sid) == {"face_tracks"}: continue stems = [] for j, speaker_id in enumerate(talking, 1): stem_key = f"stem_{i:04d}_{j}" stem_id = speech_stem_id(sid, speaker_id) rows.append( _recipe( stem_key, "audio.mix", stem_id, "speech_stem:" + stem_id, inputs={ "segments": _stem_segments(prepared, sid, speaker_id, manifest), "total_frames": t["contribution_frames"], }, parameters={"ducking": False}, ) ) stems.append(dict(speaker_id=speaker_id, stem_key=stem_key)) lip_key = f"lip_{i:04d}" lip = _recipe( lip_key, "video.lipsync", sid, dependencies=[face_key, *[s["stem_key"] for s in stems]], parameters=dict( profile="musetalk-v15-v1", fps=24, num_frames=t["contribution_frames"], seed=shot["frame_parameters"]["seed"], ), ) if prepared.get("final_render_contract", {}).get("audio_context_shift_policy"): lip["parameters"]["audio_context_shift_frames"] = shot["performance"].get( "audio_context_shift_frames", 0 ) if source_rest: lip["parameters"]["speech_silence_policy"] = SOURCE_REST_POLICY lip.update(stems=stems, forced="synced_video:" + sid in force) rows.append(lip) qc_key = f"syncqa_{i:04d}" qc = _recipe( qc_key, "video.dialogue.inspect", sid, dependencies=[lip_key], parameters=dict( profile="musetalk-v15-v1", fps=24, num_frames=t["contribution_frames"] ), ) qc.update( stems=stems, repair_root=lip_key, candidate_key=lip_key, visual_context=compiled["shots"][i - 1]["context_hash"], final_signature=signature, ) if source_rest: qc["parameters"]["speech_silence_policy"] = SOURCE_REST_POLICY if shot["performance"]["lip_sync"] == "required": review["input"]["expected"]["source_visual_policy"] = SOURCE_VISUAL_POLICY review["repair_root"] = by_binding["base_video:" + sid] if sid in quiet_shots and len(_quiet_base_motion(shot)) <= 8000: qc["source_repair_root"] = by_binding["base_video:" + sid] rows.append(qc) final_dependencies.append(qc_key) else: final_dependencies.append(review_key) if body.get("output_goal", "film") == "film": extract_keys = [] for i, shot in enumerate(manifest["spec"]["shots"], 1): if shot["performance"]["original_audio"] == "preserve": sid = shot["id"] t = timing[sid] key = f"orig_{i:04d}" extract_keys.append(key) base = by_binding["base_video:" + sid] deps = [base] if any(row["key"] == base for row in rows) else [] rows.append( _recipe( key, "audio.dialogue.extract", sid, "original_audio:" + sid, dependencies=deps, parameters={ "start_frame": t["source_start_frame"] + t["dedup_frames"], "duration_frames": t["contribution_frames"], }, ) ) has_mix = bool( extract_keys or prepared["utterances"] or manifest["audio"]["layers"] or manifest["audio"]["mode"] != "silent" ) if has_mix: rows.append( _recipe( "dialogue_mix", "audio.mix", "dialogue", dependencies=extract_keys, parameters={"ducking": manifest["audio"].get("ducking", True)}, ) ) rows.append(_recipe("dialogue_captions", "captions.compile", "captions")) rows.append( _recipe( "compose", "video.compose", "film", dependencies=[ *final_dependencies, *(["dialogue_mix"] if has_mix else []), "dialogue_captions", ], ) ) # 输入字节在派发时确定,只有精确resolved_input哈希相同才复用派生成果。 for row in rows: if row["kind"] in {"video.dialogue.review", "video.dialogue.inspect"}: sid = row["unit_id"] row["publish_final"] = not targets or bool( targets[sid].intersection({"video", "synced_video"}) ) row["force_final"] = "video:" + sid in force row.setdefault("requested_parameters", deepcopy(row["parameters"])) if targets: lookup = {r["binding_key"]: r["key"] for r in rows if r.get("binding_key")} for sid in targets: gates = [ r for r in rows if r["unit_id"] == sid and r["kind"] in {"dialogue.accepted", "video.dialogue.inspect", "video.dialogue.review"} ] if gates: lookup["video:" + sid] = lookup["synced_video:" + sid] = gates[-1]["key"] by_key = {r["key"]: r for r in rows} keep = set() def include(key): if key in keep: return keep.add(key) for dep in by_key[key]["dependencies"]: include(dep) for sid, roles in targets.items(): for role in roles: key = lookup.get(role + ":" + sid) if not key: fail(422, "invalid_target", "目标镜头缺少对应制作步骤") include(key) rows = [r for r in rows if r["key"] in keep] return rows async def _materialize(session, run, steps, settings): from .editor_engine import _add_ref manifest = deepcopy(run.result_manifest) body = run.plan_snapshot["body"] if _voice_preview(body): prepared = dict( effective_manifest=manifest, steps=[], production_materialized=True, source_plan_hash=run.plan_snapshot["plan_hash"], ) else: prepared = prepare_dialogue( manifest, manifest["bindings"], run.plan_snapshot["capabilities"] ) contract = run.plan_snapshot["capabilities"].get("final_render_contract") prepared["final_render_contract"] = deepcopy(contract or {"recipe": "dialogue-final-v2"}) if prepared["issues"]: run.state, run.error_json = ( "blocked", {"code": "dialogue_timing_conflict", "issues": prepared["issues"]}, ) return manifest = prepared["effective_manifest"] voiced = {p["shot_id"] for p in prepared["placements"]} conflicting = [ s["id"] for s in manifest["spec"]["shots"] if s["id"] in voiced and s["performance"]["original_audio"] == "preserve" ] if conflicting: run.state, run.error_json = ( "blocked", dict( code="original_audio_conflict", shot_ids=conflicting, message="保留原片音轨与实测新对白重叠", ), ) return from app.services.stories.common import spec_assets model, assets = await spec_assets(session, run.owner_id, manifest["spec"], settings) compiled = compile_story(model, assets) scoped = _targets(manifest, body, prepared["provenance"]["shot_children"]) if any( row["errors"] for row in compiled["shots"] if not scoped or row["shot_id"] in scoped ): run.state, run.error_json = "blocked", {"code": "invalid_story_references"} return reusable = await _reusable(session, run.owner_id, manifest, settings) try: rows = production_recipes(prepared, reusable, body, settings, compiled) except HTTPException as exc: run.state, run.error_json = "blocked", exc.detail return for row in rows: if ( row["kind"] == "video.generate" and not row.get("reuse") and row["parameters"].get("profile") == H3_TP2_PROFILE ): try: recipe_parameters(row["parameters"], H3_TP2_PROFILE) except ValueError as exc: run.state, run.error_json = ( "blocked", dict( code="invalid_video_profile", unit_id=row["unit_id"], message=str(exc) ), ) return if row.get("issue"): run.state, run.error_json = "blocked", row["issue"] return if ( row["kind"] == "video.generate" and not row.get("reuse") and row["parameters"].get("profile") == H3_TP2_PROFILE and not run.plan_snapshot["capabilities"].get("tp2_authorized") ): run.state, run.error_json = ( "blocked", dict( code="capability_unavailable", message="有效时长需要新双卡视频,请重新规划并认证", ), ) return prepared.update( steps=rows, production_materialized=True, source_plan_hash=run.plan_snapshot["plan_hash"], ) if "audio_qa_contract" in run.plan_snapshot["capabilities"]: prepared["audio_qa_contract"] = deepcopy( run.plan_snapshot["capabilities"]["audio_qa_contract"] ) prepared["prepared_hash"] = digest(prepared) # prepared_plan 与生产步骤在持Run锁的同一事务物化,崩溃后只会整体重放。 for row in prepared["steps"]: session.add( WorkflowStep( run_id=run.id, step_key=row["key"], kind=row["kind"], dependencies=row["dependencies"], recipe_json=deepcopy(row), semantic_input_hash=digest(row), state="succeeded" if row["reuse"] else "waiting", result_json=deepcopy(row["reuse"]), ) ) if row["reuse"] and row.get("binding_key"): manifest["bindings"][row["binding_key"]] = deepcopy(row["reuse"]) run.prepared_plan = prepared run.result_manifest = manifest run.phase = "dialogue_production" from app.domain.editors import collect_manifest_asset_ids for aid in collect_manifest_asset_ids(manifest): asset = await session.get(Asset, aid) if asset: await _add_ref(session, run, asset) await session.flush() async def _step(session, run, key): item = await session.scalar( select(WorkflowStep).where(WorkflowStep.run_id == run.id, WorkflowStep.step_key == key) ) if not item or item.state != "succeeded" or not item.result_json: fail(409, "dependency_changed", "对白依赖尚未完成") return item async def _resolve(session, run, step, settings): from app.domain.native_dialogue import enabled as native_enabled if native_enabled(run.result_manifest): from .native_dialogue_engine import resolve return await resolve(session, run, step, settings) from .editor_engine import _resolve as resolve_legacy, _asset from app.domain.editors import collect_manifest_asset_ids m, recipe = run.result_manifest, step.recipe_json inputs, params = deepcopy(recipe["input"]), deepcopy(recipe["parameters"]) uid = recipe["unit_id"] bindings = m["bindings"] if step.kind in { "image.generate", "image.reference.generate", "image.prepare_frame", "video.generate", }: return await resolve_legacy(session, run, step, settings) if recipe.get("narration"): if step.kind == "audio.speech": segment = next(s for s in m["audio"]["segments"] if s["id"] == uid) inputs["prompt"] = segment["text"] elif step.kind == "audio.normalize": inputs = {"asset_id": bindings["audio:" + uid]["asset_id"]} if step.kind == "audio.normalize" and (recipe.get("binding_key") or "").startswith( "normalized_speech:" ): inputs = {"asset_id": bindings["speech:" + uid]["asset_id"]} if step.kind == "audio.dialogue.inspect": inputs["audio_asset_id"] = bindings["normalized_speech:" + uid]["asset_id"] if step.kind in {"video.dialogue.select", "audio.dialogue.extract"}: inputs = {"video_asset_id": bindings["base_video:" + uid]["asset_id"]} if step.kind in {"video.dialogue.review", "video.dialogue.analyze"}: inputs["video_asset_id"] = bindings["selected_video:" + uid]["asset_id"] if step.kind in {"video.lipsync", "video.dialogue.inspect"}: face = bindings["face_tracks:" + uid] face_step = await _step(session, run, "face_" + step.step_key.rsplit("_", 1)[-1]) report = face_step.result_json.get("report", {}) if report.get("decision") not in {"pass", None}: fail(409, "ambiguous_target", "画面说话人尚未可靠绑定") tracks = {track["speaker_id"]: track["track_id"] for track in report.get("tracks", [])} speech_tracks = [] for stem in recipe["stems"]: source = await _step(session, run, stem["stem_key"]) if stem["speaker_id"] not in tracks: fail(409, "ambiguous_target", "无法确定角色对应的人脸") speech_tracks.append( dict( speaker_id=stem["speaker_id"], audio_asset_id=source.result_json["asset_id"], target_track_id=tracks[stem["speaker_id"]], ) ) inputs.update( video_asset_id=bindings["selected_video:" + uid]["asset_id"], face_tracks_asset_id=face["asset_id"], speech_tracks=speech_tracks, ) if step.kind == "video.dialogue.inspect": lip = await _step(session, run, recipe["candidate_key"]) inputs.update( video_asset_id=lip.result_json["asset_id"], base_video_asset_id=bindings["selected_video:" + uid]["asset_id"], ) if step.step_key == "dialogue_mix": inputs = await _mix_inputs(session, run) if step.kind == "captions.compile": from app.services.editor_media import compile_captions, materialize_cues return dict( input={}, parameters={}, input_sha256={}, captions=compile_captions(m, bindings, prepared=run.prepared_plan), editable_cues=materialize_cues(m, bindings, prepared=run.prepared_plan), ) if step.kind == "video.compose": inputs, params = await _compose_inputs(session, run, settings) ids = set(collect_manifest_asset_ids(inputs)) hashes = {} for aid in ids: asset = await session.get(Asset, aid) frozen_sha = (run.plan_snapshot or {}).get("asset_sha256", {}).get(aid) if not asset or not await _asset( session, run.owner_id, {"asset_id": aid, "sha256": frozen_sha or asset.sha256}, settings ): fail(409, "dependency_changed", "对白来源素材已变化或不可访问") hashes[aid] = asset.sha256 return dict(input=inputs, parameters=params, input_sha256=hashes) async def _mix_inputs(session, run): from app.domain.audio_timeline import compile_audio_timeline m = run.result_manifest rows = [] for utterance in run.prepared_plan["utterances"]: b = m["bindings"]["normalized_speech:" + utterance["utterance_id"]] rows.append( dict( asset_id=b["asset_id"], source_start_sample=utterance["source_start_sample"], source_end_sample=utterance["source_end_sample"], offset_sample=utterance["start_sample"], role="narration", segment_id=utterance["utterance_id"], ) ) norms = ( await session.scalars( select(WorkflowStep).where( WorkflowStep.run_id == run.id, WorkflowStep.kind == "audio.normalize" ) ) ).all() samples, remap = {}, {} for n in norms: if n.resolved_input_json and n.result_json: source = n.resolved_input_json["input"]["asset_id"] samples[source] = n.result_json["sample_count"] remap[source] = n.result_json["asset_id"] timing = {r["shot_id"]: r for r in run.prepared_plan["timing"]["shots"]} for recipe in run.prepared_plan["steps"]: if recipe["kind"] == "audio.dialogue.extract": result = (await _step(session, run, recipe["key"])).result_json sid = recipe["unit_id"] rows.append( dict( asset_id=result["asset_id"], source_start_sample=0, source_end_sample=result["sample_count"], offset_sample=timing[sid]["start_frame"] * 2000, role="sfx", segment_id=sid, ) ) track = m["audio"].get("track") if m["audio"]["mode"] == "manual_track" and track and "source_end_ms" in track: m = deepcopy(m) m["audio"]["track"] = dict( asset_id=track["asset_id"], source_start_sample=track["source_start_ms"] * 48, source_end_sample=track["source_end_ms"] * 48, offset_sample=track["offset_frame"] * 2000, ) timeline = compile_audio_timeline(m, m["bindings"], source_samples=samples) for row in timeline["segments"]: row["asset_id"] = remap.get(row["asset_id"], row["asset_id"]) rows.append(row) if not rows or len(rows) > 128: fail(422, "production_limit", "混音需1–128段,不能截掉对白") return {"segments": rows, "total_frames": run.prepared_plan["timing"]["total_frames"]} async def _compose_inputs(session, run, settings): from app.adapters.media import inspect_video_track from app.adapters.storage import confined m = run.result_manifest spec = deepcopy(m["spec"]) # 这是只读渲染投影,作者原始trim与对白结构仍保存在result_manifest。 spec["schema_version"] = 4 spec.pop("dialogue", None) clips = [] for shot, t in zip(spec["shots"], run.prepared_plan["timing"]["shots"], strict=True): shot.pop("performance", None) from app.domain.video_generation import H3_NATIVE_AV_PROFILES if shot["video_parameters"].get("profile") in H3_NATIVE_AV_PROFILES: shot["video_parameters"] = dict( profile=H3_V2_PROFILE, source_frames=t["contribution_frames"], seed=shot["video_parameters"].get("seed", 42), num_inference_steps=shot["video_parameters"].get("num_inference_steps", 50), upscale=False, ) shot["continuity"].update(transition="cut", endpoint_mode="first_frame") count = t["contribution_frames"] shot["edit"].update(start_frame=0, duration_frames=count, dedup_frames=0) b = m["bindings"]["video:" + shot["id"]] asset = await session.get(Asset, b["asset_id"]) track = await inspect_video_track( confined(settings.asset_root, asset.storage_key, exists=True), settings ) if track["frames"] != count: fail(409, "invalid_output", "最终镜头帧数不匹配,不能重复裁剪或补长") clips.append( dict( shot_id=shot["id"], asset_id=asset.id, sha256=asset.sha256, width=track["width"], height=track["height"], fps=24, source_frames=count, start_frame=0, duration_frames=count, ) ) mix = ( await _step(session, run, "dialogue_mix") if any(r["key"] == "dialogue_mix" for r in execution_recipes(run)) else None ) subtitles = await _step(session, run, "dialogue_captions") spec["render"].update( audio=mix.result_json["track"] if mix else None, subtitles=subtitles.result_json["cues"], total_frames=run.prepared_plan["timing"]["total_frames"], ) audio = await session.get(Asset, mix.result_json["asset_id"]) if mix else None render_inputs = dict( clips=clips, fps=24, canvas=list(canvas(spec["profile"])), **({"audio": {**mix.result_json["track"], "sha256": audio.sha256}} if audio else {}), ) return ( { "asset_ids": [c["asset_id"] for c in clips], **({"audio_asset_id": audio.id} if audio else {}), }, { "clips": [{"asset_id": c["asset_id"]} for c in clips], "story_spec": spec, "render_inputs": render_inputs, }, ) def _semantic_hash(kind, resolved): hashes = resolved.get("input_sha256", {}) def content(value): if isinstance(value, dict): return {k: content(v) for k, v in value.items()} if isinstance(value, list): return [content(v) for v in value] return hashes.get(value, value) if isinstance(value, str) else value return digest( { "kind": kind, "input": content(resolved["input"]), "parameters": content(resolved["parameters"]), } ) def _binding(result): from app.schemas.editors import BindingV2 return {key: deepcopy(value) for key, value in result.items() if key in BindingV2.model_fields} def _required_source_video(run, review): """从冻结的镜头与真实后继步骤识别已经编排的 source-v2 底片。""" plan = run.prepared_plan or {} if plan.get("final_render_contract", {}).get("speech_silence_policy") != SOURCE_REST_POLICY: return None sid = review["unit_id"] shots = run.result_manifest["spec"]["shots"] if not any(s["id"] == sid and s["performance"]["lip_sync"] == "required" for s in shots): return None rows = [r for r in plan.get("steps", []) if r["unit_id"] == sid] if not any( r["kind"] == "video.dialogue.inspect" and r["parameters"].get("speech_silence_policy") == SOURCE_REST_POLICY for r in rows ): return None return next( ( r["key"] for r in rows if r["kind"] == "video.generate" and r["binding_key"] == "base_video:" + sid ), None, ) async def create_editor_child(session, run, step, settings): from .editor_engine import _asset, _add_ref from app.services.jobs import create_jobs from app.services.events import emit_job from app.schemas.jobs import Submit recipe = step.recipe_json from app.domain.native_dialogue import enabled as native_enabled if native_enabled(run.result_manifest): from .native_dialogue_engine import before_child if await before_child(session, run, step, settings): return if step.kind == "video.dialogue.review": root = _required_source_video(run, recipe) if root and recipe["input"]["expected"].get("source_visual_policy") != SOURCE_VISUAL_POLICY: recipe = deepcopy(recipe) recipe["input"]["expected"]["source_visual_policy"] = SOURCE_VISUAL_POLICY recipe["repair_root"] = root step.recipe_json, step.resolved_input_json = recipe, None if step.kind == "dialogue.asset": asset = await session.get(Asset, recipe["input"]["asset_id"]) if not asset or not await _asset( session, run.owner_id, {"asset_id": asset.id, "sha256": asset.sha256}, settings, "audio" ): fail(409, "dependency_changed", "导入配音素材不可用") result = dict( asset_id=asset.id, sha256=asset.sha256, kind="audio", source="manual", context_hash=recipe["context_hash"], duration_seconds=asset.duration_seconds, ) m = deepcopy(run.result_manifest) m["bindings"][recipe["binding_key"]] = result run.result_manifest = m step.result_json, step.state = result, "succeeded" await _add_ref(session, run, asset) return if step.resolved_input_json is None: step.resolved_input_json = await _resolve(session, run, step, settings) step.semantic_input_hash = _semantic_hash(step.kind, step.resolved_input_json) resolved = step.resolved_input_json if step.kind == "captions.compile": step.result_json, step.state = {"cues": resolved["captions"]}, "succeeded" m = deepcopy(run.result_manifest) m["captions"]["cues"] = resolved["editable_cues"] run.result_manifest = m return prior = run.result_manifest.get("bindings", {}).get(recipe.get("binding_key"), {}) context_matches = ( not recipe.get("context_hash") or prior.get("context_hash") == recipe["context_hash"] ) if ( prior and not native_enabled(run.result_manifest) and not recipe.get("forced") and prior.get("input_hash") == step.semantic_input_hash and context_matches and step.kind != "audio.dialogue.inspect" ): if await _asset(session, run.owner_id, prior, settings, prior["kind"]): cached = deepcopy(prior) if step.kind == "video.dialogue.analyze": import json from app.adapters.storage import safe_file asset = await session.get(Asset, prior["asset_id"]) with safe_file(settings.asset_root, asset.storage_key) as source: evidence = json.load(source) cached["report"] = dict( decision=evidence.get("decision"), tracks=[ {"speaker_id": t["speaker_id"], "track_id": t["track_id"]} for t in evidence.get("tracks", []) ], ) step.result_json, step.state = cached, "succeeded" return if prior.get("locked") and not recipe.get("forced"): fail(409, "locked_dependency_changed", "已锁定素材失效,自动生成不会覆盖") for aid, sha in resolved["input_sha256"].items(): if not await _asset(session, run.owner_id, {"asset_id": aid, "sha256": sha}, settings): fail(409, "dependency_changed", "冻结依赖已变化") step.explicit_attempt += 1 jobs = await create_jobs( session, Submit( task_type=step.kind, input=resolved["input"], parameters=resolved["parameters"], execution_mode=run.execution_mode, folder_id=run.folder_id, output_folder_id=run.output_folder_id, ), SimpleNamespace(id=run.owner_id, auth_kind="session", scopes=[]), settings, key=f"run:{run.id}:{step.step_key}:{step.explicit_attempt}", internal=True, frozen_workflow=True, ) job = jobs[0] job.run_id, job.step_key, job.explicit_attempt = run.id, step.step_key, step.explicit_attempt job.desired_state, job.hold_reasons = run.desired_state, list(run.hold_reasons or []) step.selected_job_id, step.state = job.id, "ready" step.version += 1 await emit_job(session, job) return job _LIP_QUALITY_REASONS = { "protected_region_changed": "嘴部以外的受保护画面发生变化", "listener_changed": "未发言人物的面部发生变化", "identity_changed": "人物身份一致性未通过", "listener_sync": "未发言人物的口型跟随了对白", "sync_offset": "口型与声音时间错位", "low_sync_confidence": "口型同步置信度不足", "silence_mouth_motion": "静音段仍有明显嘴部运动", "silent_mouth_source_changed": "静音段的嘴部画面与底片不符", "insufficient_silent_mouth_source_evidence": "静音嘴区可比较的像素块不足", "insufficient_silence_evidence": "静音段嘴部证据不足", "source_speaking_during_silence": "底片在对白静音时仍在说话,请更换安静的底片", "insufficient_source_rest_evidence": "底片静音时的嘴部证据不足,请人工检查", "insufficient_sync_evidence": "口型同步证据不足", "short_sample": "样本过短,无法判断口型同步", "insufficient_voiced_evidence": "有效发声证据不足", } # bounded-feature-shift-v1 补偿资格沿用已认证盲测的保护上限。 _SYNC_REPAIR_VISUAL_LIMITS = { "max_protected_pixel_error": 6, "max_protected_block_mae": 18, "max_protected_block_severe_fraction": 0.15, "max_silent_speaker_error": 8, } def _next_sync_shift(report, stems, current): """仅对完整的单发言人高置信残差尝试校正。验收仍由独立盲测执行。""" def measured(value): return type(value) in (int, float) and isfinite(value) scores = report.get("scores") rests = report.get("rest_checks") identities = report.get("identity_samples") listeners = report.get("listener_sync_checks") if ( report.get("decision") != "reject" or report.get("reasons") != ["sync_offset"] or type(current) is not int or abs(current) > 6 or len(stems) != 1 or not isinstance(scores, list) or len(scores) != 1 or not isinstance(rests, list) or len(rests) != 1 or not isinstance(identities, list) or not identities or not isinstance(listeners, list) ): return None speaker = stems[0]["speaker_id"] score, rest = scores[0], rests[0] # 认证报告的 reasons 汇总所有失败项;缺少相应实测记录时不能据此修复。 if ( not all( isinstance(row, dict) and row.get("speaker_id") == speaker for row in (score, rest, *identities) ) or not all( measured(row.get("similarity")) and row["similarity"] >= 0.65 for row in identities ) or not measured(report.get("min_identity_similarity")) or report["min_identity_similarity"] < 0.65 or not all( measured(report.get(key)) and 0 <= report[key] <= upper for key, upper in _SYNC_REPAIR_VISUAL_LIMITS.items() ) or any(not isinstance(row, dict) or row.get("decision") != "reject" for row in listeners) or rest.get("decision") != "pass" or score.get("decision") != "reject" or score.get("working_fps") != 25 or not measured(score.get("confidence")) or score["confidence"] < 4 or type(score.get("voiced_windows")) is not int or score["voiced_windows"] < 15 ): return None silent_frames, windows = rest.get("silent_frames"), rest.get("windows") if ( type(silent_frames) is not int or silent_frames < 0 or not isinstance(windows, list) or bool(windows) != bool(silent_frames) or any( not isinstance(window, dict) or window.get("decision") != "pass" for window in windows ) ): return None offset = score.get("offset_ms") if not measured(offset) or not 80 < abs(offset) <= 240: return None corrected = current + round(offset * 24 / 1000) return corrected if abs(corrected) <= 6 else None def _source_rest_evidence(report, speakers, frames, *, key="source_rest_checks"): rows = report.get(key) if not isinstance(rows, list) or len(rows) != len(speakers): return None checks = {} for row in rows: if not isinstance(row, dict): return None speaker = row.get("speaker_id") if not isinstance(speaker, str) or speaker not in speakers: return None windows = row.get("windows") decision = row.get("decision") count = row.get("silent_frames") if ( type(count) is not int or not 0 <= count <= frames or not isinstance(windows, list) or decision not in ("pass", "reject", "indeterminate") ): return None total, previous = 0, 0 decisions = set() for window in windows: if not isinstance(window, dict): return None a, b = window.get("start_frame"), window.get("end_frame") result = window.get("decision") if ( type(a) is not int or type(b) is not int or not previous <= a < b <= frames or result not in ("pass", "reject", "indeterminate") ): return None total += b - a previous = b decisions.add(result) expected = next((d for d in ("reject", "indeterminate") if d in decisions), "pass") if total != count or expected != decision: return None checks[speaker] = (decision, [(w["start_frame"], w["end_frame"]) for w in windows]) return checks if set(checks) == speakers else None def _silent_mouth_evidence(report, source_checks, verdict): rows = report.get("silent_mouth_source_checks") if not isinstance(rows, list) or len(rows) != len(source_checks): return False seen = set() for row in rows: if not isinstance(row, dict): return False speaker = row.get("speaker_id") if not isinstance(speaker, str) or speaker not in source_checks or speaker in seen: return False seen.add(speaker) silent = sum(b-a for a, b in source_checks[speaker][1]) mae, severe = row.get("max_block_mae"), row.get("max_block_severe_fraction") if not ( silent > 0 and type(row.get("silent_frames")) is int and type(row.get("measured_frames")) is int and row["silent_frames"] == row["measured_frames"] == silent and type(row.get("block_count")) is int and row["block_count"] >= silent and type(mae) in (float, int) and 0 <= mae <= 255 and type(severe) in (float, int) and 0 <= severe <= 1 ): return False changed = mae > 18 or severe > 0.15 if row.get("decision") != ("reject" if changed else "pass"): return False if changed and (verdict != "reject" or "silent_mouth_source_changed" not in report.get("reasons", [])): return False return True async def _quality_result(session, run, step, job, result, settings): from app.models.workflows import WorkflowVariant, QualityAssessment from .editor_engine import _add_ref recipe = step.recipe_json candidate_step = await _step(session, run, recipe["candidate_key"]) candidate = deepcopy(candidate_step.result_json) candidate["shot_id"] = recipe["unit_id"] prior = ( await session.scalars(select(WorkflowVariant).where(WorkflowVariant.run_id == run.id)) ).all() ordinal = sum(v.step_key == step.step_key for v in prior) policy_error = None source_rest = False source_checks = None verdict = result["report"].get("decision", result["report"].get("verdict", "indeterminate")) if (step.kind == "video.dialogue.review" and (job.input_json or {}).get("expected", {}).get("source_visual_policy") == SOURCE_VISUAL_POLICY and result["report"].get("source_visual_policy") != SOURCE_VISUAL_POLICY): verdict = "indeterminate" policy_error = "底片画面评审未返回本次请求的评审策略" if step.kind == "video.dialogue.inspect": contract = run.prepared_plan.get("final_render_contract") or {} policy = contract.get("speech_silence_policy") source_rest = policy == SOURCE_REST_POLICY blend = contract.get("mouth_blend_policy") report = result["report"] if ( report.get("mouth_blend_policy") != blend or candidate.get("mouth_blend_policy") != blend or blend and report.get("synced_sha256") != candidate["sha256"] ): verdict = "indeterminate" policy_error = "口型候选或质检报告与冻结的嘴部渲染策略、候选视频摘要不匹配" elif policy and report.get("speech_silence_policy") != policy: verdict = "indeterminate" policy_error = f"口型质检报告未证明已冻结的静音策略 {policy}" elif source_rest: resolved = step.resolved_input_json base_asset_id = resolved["input"]["base_video_asset_id"] speakers = {row["speaker_id"] for row in recipe["stems"]} frames = resolved["parameters"]["num_frames"] source_checks = _source_rest_evidence(report, speakers, frames) final_checks = _source_rest_evidence(report, speakers, frames, key="rest_checks") if ( (candidate.get("provenance") or {}).get("speech_silence_policy") != policy or resolved["input_sha256"][base_asset_id] != report.get("base_sha256") or source_checks is None or final_checks is None or not _silent_mouth_evidence(report, source_checks, verdict) or any(source_checks[s][1] != final_checks[s][1] for s in speakers) or verdict == "pass" and any(checks[s][0] != "pass" for checks in (source_checks, final_checks) for s in speakers) ): verdict = "indeterminate" policy_error = "口型质检报告缺少与冻结底片、说话人及静音区间匹配的源画面和最终画面证据" if step.kind == "audio.dialogue.inspect": inputs = step.resolved_input_json["input"] report = result["report"] contract = run.plan_snapshot["capabilities"].get("audio_qa_contract") if not _matches_audio_qa_contract(report, contract, verdict): verdict = "indeterminate" policy_error = "语音质检回执与本次运行冻结的内容复核策略或模型修订不符" expected_ref = step.resolved_input_json["input_sha256"].get(inputs["reference_asset_id"]) selection = step.resolved_input_json["parameters"] if any( report.get(k) != v for k, v in { "audio_sha256": candidate["sha256"], "reference_sha256": expected_ref, "source_start_sample": selection.get("source_start_sample", 0), "source_end_sample": selection.get("source_end_sample") or candidate["sample_count"], "speaker_id": inputs["speaker_id"], "expected_text": inputs["expected_text"], }.items() ): verdict = "indeterminate" if verdict not in {"pass", "reject", "indeterminate"}: verdict = "indeterminate" variant = WorkflowVariant( run_id=run.id, step_key=step.step_key, ordinal=ordinal, generation_job_id=candidate_step.selected_job_id, model_input_hash=step.semantic_input_hash, provenance_hash=digest(candidate), resolved_input=deepcopy(step.resolved_input_json), candidate=candidate, state="accepted" if verdict == "pass" else "rejected", ) session.add(variant) await session.flush() session.add( QualityAssessment( variant_id=variant.id, job_id=job.id, verdict=verdict, evidence=deepcopy(result["report"]), ) ) if step.kind == "audio.dialogue.inspect" and verdict == "pass": m = deepcopy(run.result_manifest) result["context_hash"] = _audio_qa_hash( step.resolved_input_json["input"], candidate["sha256"], run.plan_snapshot["capabilities"], step.resolved_input_json["parameters"], ) m["bindings"][recipe["binding_key"]] = _binding(result) run.result_manifest = m return if verdict == "pass": sid = recipe["unit_id"] shot = next(s for s in run.result_manifest["spec"]["shots"] if s["id"] == sid) active = any(p["shot_id"] == sid and p["visible"] for p in run.prepared_plan["placements"]) final = recipe.get("publish_final", True) and ( step.kind == "video.dialogue.inspect" or not active or shot["performance"]["lip_sync"] == "off" ) if final: m = deepcopy(run.result_manifest) candidate.pop("shot_id", None) old = m["bindings"].get("video:" + sid, {}) if ( old.get("locked") and (old.get("provenance") or {}).get("dialogue_signature") and not recipe.get( "force_final", "video:" + sid in run.plan_snapshot["body"].get("force", []) ) ): fail(409, "locked_dependency_changed", "无法覆盖已锁定的最终镜头") candidate["locked"] = bool( old.get("locked") and (old.get("provenance") or {}).get("dialogue_signature") ) final_signature = _shot_signature( run.prepared_plan, shot, {"context_hash": recipe["visual_context"]}, m ) candidate["provenance"] = { **(candidate.get("provenance") or {}), "dialogue_signature": final_signature, "quality_asset_id": result["asset_id"], } m["bindings"]["video:" + sid] = _binding(candidate) if step.kind == "video.dialogue.inspect": m["bindings"]["synced_video:" + sid] = _binding(candidate) m["bindings"]["dialogue_report:" + sid] = _binding(result) run.result_manifest = m asset = await session.get(Asset, candidate["asset_id"]) await _add_ref(session, run, asset) return repaired = [v for v in prior if v.state == "repair_requested"] local_count = sum((v.candidate or {}).get("shot_id") == recipe["unit_id"] for v in repaired) policy = run.result_manifest.get("production", {}) audio_qa = step.kind == "audio.dialogue.inspect" limit = ( (1 if recipe.get("can_repair") else 0) if audio_qa else min(2, policy.get("max_repairs_per_shot", 2)) ) if ( verdict == "reject" and local_count < limit and len(repaired) < min(12, policy.get("max_total_repairs", 12)) ): shift = None repair_root = recipe["repair_root"] if step.kind == "video.dialogue.review": repair_root = _required_source_video(run, recipe) or repair_root if step.kind == "video.dialogue.inspect": reasons = report.get("reasons") if contract.get("audio_context_shift_policy") and reasons == ["sync_offset"]: if not source_rest or all(check[0] == "pass" for check in source_checks.values()): shift = _next_sync_shift( report, recipe["stems"], candidate["generation_parameters"].get("audio_context_shift_frames"), ) if shift is None: repair_root = None elif source_rest: repair_root = None if ( isinstance(reasons, list) and "source_speaking_during_silence" in reasons and "insufficient_source_rest_evidence" not in reasons and source_checks is not None and any(check[0] == "reject" for check in source_checks.values()) and all(check[0] != "indeterminate" for check in source_checks.values()) ): repair_root = recipe.get("source_repair_root") if repair_root and await _reset_quality_branch( session, run, repair_root, settings, shift ): variant.state = "repair_requested" return step.state, run.state = "blocked", "blocked" diagnosis = { "message": policy_error or result["report"].get("reason") or "对白镜头质量需要人工处理" } reasons = result["report"].get("reasons") if not policy_error and step.kind == "video.dialogue.inspect" and isinstance(reasons, list): codes = list(dict.fromkeys(code for code in reasons if isinstance(code, str) and code)) if codes: diagnosis["reasons"] = codes details = [_LIP_QUALITY_REASONS[code] for code in codes if code in _LIP_QUALITY_REASONS] ordinal = run.result_manifest["shot_ids"].index(recipe["unit_id"]) + 1 detail = ";".join(details) or diagnosis["message"] diagnosis["message"] = f"第{ordinal}镜口型质检:{detail}" run.error_json = dict( code="dialogue_quality_" + verdict, step_key=step.step_key, shot_id=recipe["unit_id"], report_asset_id=result["asset_id"], **diagnosis, ) async def recover_frame_repair(session, run, key, body, settings): from app.models.workflows import WorkflowVariant, QualityAssessment from .editor_engine import _asset, _add_ref def invalid(): fail(409, "frame_recovery_unavailable", "运行、人工首帧或原评审修复记录与请求不符") if run.desired_state != "run" or run.state not in {"running", "queued", "blocked"}: invalid() if run.state == "blocked" and (run.error_json or {}).get("step_key") != key: invalid() frozen = {r["key"]: r for r in (run.prepared_plan or {}).get("steps", [])} original = frozen.get(key, {}) manual = original.get("reuse") or {} sid = original.get("unit_id") if ( not sid or original.get("binding_key") != "frame:" + sid or manual.get("source") != "manual" or manual.get("asset_id") != body.frame_asset_id or manual.get("sha256") != body.frame_sha256 ): invalid() reviews = [ r for r in frozen.values() if r["kind"] == "video.dialogue.review" and r["unit_id"] == sid and r.get("repair_root") == key ] if len(reviews) != 1 or not (video_key := _required_source_video(run, reviews[0])): invalid() frame = await session.scalar( select(WorkflowStep).where(WorkflowStep.run_id == run.id, WorkflowStep.step_key == key) ) video = await session.scalar( select(WorkflowStep).where( WorkflowStep.run_id == run.id, WorkflowStep.step_key == video_key ) ) job = await session.get(Job, body.target_job_id, with_for_update=True) if ( not frame or not video or video.selected_job_id or video.state != "waiting" or frame.selected_job_id != body.target_job_id or not frame.recipe_json.get("forced") or not job or job.owner_id != run.owner_id or job.run_id != run.id or job.step_key != key or job.explicit_attempt != frame.explicit_attempt or job.deleted_at is not None ): invalid() active = await session.scalar( select(Execution.id).where(Execution.job_id == job.id, Execution.state != "exited").limit(1) ) if job.state != "cancelled" or not job.cancel_requested or active: fail(409, "cleanup_pending", "请先取消选中的首帧重画作业,并等待执行清理完成") review = ( await session.execute( select(WorkflowVariant, QualityAssessment) .join(QualityAssessment, QualityAssessment.variant_id == WorkflowVariant.id) .where(WorkflowVariant.run_id == run.id, WorkflowVariant.step_key == reviews[0]["key"]) .order_by(WorkflowVariant.ordinal.desc()) .limit(1) ) ).first() if ( not review or review[0].state != "repair_requested" or review[1].verdict != "reject" or (review[1].evidence or {}).get("source_visual_policy") == SOURCE_VISUAL_POLICY or review[1].job_id != body.rejected_review_job_id ): invalid() # 此分支只恢复被旧评审删掉的人工输入,其他已生成绑定及其锁不允许被撤销。 bindings = run.result_manifest["bindings"] if bindings.get(original["binding_key"]) or (frozen[video_key].get("reuse") or {}).get( "locked" ): invalid() asset = await _asset(session, run.owner_id, manual, settings, "image") if not asset: fail(409, "dependency_changed", "冻结的人工首帧文件或摘要已变化") if not await _reset_quality_branch(session, run, video_key, settings, waiting_only=True): fail(409, "quality_repair_locked", "底片、下游素材锁定或执行条件已变化") manifest = deepcopy(run.result_manifest) manifest["bindings"][original["binding_key"]] = deepcopy(manual) run.result_manifest = manifest frame.recipe_json = { **deepcopy(original), "manual_frame_recovery": { "cancelled_job_id": job.id, "rejected_review_job_id": body.rejected_review_job_id, "restored_sha256": asset.sha256, "video_step_key": video_key, }, } frame.state, frame.result_json = "succeeded", deepcopy(manual) frame.selected_job_id, frame.resolved_input_json = None, None frame.semantic_input_hash = digest(original) frame.version += 1 await _add_ref(session, run, asset) run.state, run.error_json = "running", None async def _reset_quality_branch(session, run, root, settings, shift=None, *, waiting_only=False): import secrets steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == run.id))).all() selected = {root} root_step = next(s for s in steps if s.step_key == root) frame_dependency = None if root_step.kind == "video.generate": sid = root_step.recipe_json["unit_id"] bindings = run.result_manifest["bindings"] if any( bindings.get(f"{role}:{sid}", {}).get("locked") for role in ("video", "synced_video", "base_video") ): return False if root_step.recipe_json["parameters"].get( "profile" ) == H3_TP2_PROFILE and not run.plan_snapshot["capabilities"].get("tp2_authorized"): return False frame_step = next((s for s in steps if s.recipe_json.get("binding_key") == "frame:" + sid), None) if frame_step: frame_dependency = frame_step.step_key else: from .editor_engine import _asset if not await _asset(session, run.owner_id, bindings.get("frame:" + sid, {}), settings, "image"): return False if root_step.kind in {"audio.speech", "audio.dialogue.speech"}: same = [s for s in steps if s.recipe_json["unit_id"] == root_step.recipe_json["unit_id"]] norm = next(s for s in same if s.kind == "audio.normalize") qa = next(s for s in same if s.kind == "audio.dialogue.inspect") if any( m.get("locked") for key, m in run.result_manifest["bindings"].items() if key in {s.recipe_json.get("binding_key") for s in (root_step, norm, qa)} ): return False norm.dependencies = [root] qa.dependencies = [norm.step_key] while True: expanded = selected | {s.step_key for s in steps if selected.intersection(s.dependencies)} if expanded == selected: break selected = expanded m = deepcopy(run.result_manifest) for s in steps: if s.step_key not in selected: continue if waiting_only and (s.state != "waiting" or s.selected_job_id): return False key = s.recipe_json.get("binding_key") if key and m["bindings"].get(key, {}).get("locked"): return False for s in steps: if s.step_key not in selected: continue key = s.recipe_json.get("binding_key") if key: m["bindings"].pop(key, None) recipe = deepcopy(s.recipe_json) if root_step.kind == "video.generate" and s.kind == "video.dialogue.review": contract = run.prepared_plan.get("final_render_contract", {}) if contract.get("speech_silence_policy") == SOURCE_REST_POLICY: recipe["input"]["expected"]["motion"] = root_step.recipe_json["input"]["prompt"] if s.step_key == root: recipe["forced"] = True if frame_dependency and frame_dependency not in s.dependencies: s.dependencies = [*s.dependencies, frame_dependency] if shift is not None: recipe["parameters"]["audio_context_shift_frames"] = shift elif "seed" in recipe["parameters"]: recipe["parameters"]["seed"] = secrets.randbits(32) s.recipe_json = recipe s.selected_job_id, s.resolved_input_json, s.result_json = None, None, None s.state = "waiting" s.version += 1 run.result_manifest, run.error_json = m, None return True async def _collect(session, run, step, job, settings): from app.domain.native_dialogue import enabled as native_enabled if native_enabled(run.result_manifest): from .native_dialogue_engine import collect return await collect(session, run, step, job, settings) from .editor_engine import _collect as collect_legacy, _add_ref if step.kind in { "image.generate", "image.reference.generate", "image.prepare_frame", "video.generate", }: return await collect_legacy(session, run, step, job, settings) kind = ( "json" if step.kind in { "video.dialogue.review", "video.dialogue.analyze", "video.dialogue.inspect", "audio.dialogue.inspect", "text.script.generate", } else ( "video" if step.kind in {"video.dialogue.select", "video.lipsync", "video.compose"} else "audio" ) ) asset = await session.scalar( select(Asset) .where( Asset.source_job_id == job.id, Asset.owner_id == run.owner_id, Asset.library_scope == "private", Asset.ready.is_(True), Asset.deleted_at.is_(None), Asset.kind == kind, ) .order_by(Asset.source_output_index) ) if not asset or not await verified_output(asset, settings): fail(409, "invalid_output", "对白任务未返回可用产物") result = dict( asset_id=asset.id, sha256=asset.sha256, kind=kind, source="generated", source_job_id=job.id, source_run_id=run.id, input_hash=step.semantic_input_hash, context_hash=step.recipe_json.get("context_hash"), generation_parameters=deepcopy(step.resolved_input_json["parameters"]), ) if asset.duration_seconds is not None: result.update( duration_seconds=asset.duration_seconds, duration_frames=round(asset.duration_seconds * 24), ) if kind == "audio": meta = job.result_json or {} if step.kind in {"audio.normalize", "audio.mix", "audio.dialogue.extract"}: if ( type(meta.get("sample_count")) is not int or meta["sample_count"] <= 0 or meta.get("sample_rate", 48000) != 48000 ): fail(409, "invalid_output", "缺少真实48k音频样本数") if type(meta.get("sample_count")) is int: result.update( sample_count=meta["sample_count"], sample_rate=meta.get("sample_rate", 48000), duration_frames=(meta["sample_count"] + 1999) // 2000, ) if step.kind == "audio.mix": result["track"] = dict( asset_id=asset.id, source_start_sample=0, source_end_sample=result["sample_count"], offset_sample=0, sample_rate=48000, short_policy="silence", ) if step.kind == "audio.normalize" and ( step.recipe_json.get("binding_key") or "" ).startswith("normalized_speech:"): raw = run.result_manifest["bindings"]["speech:" + step.recipe_json["unit_id"]] result["context_hash"] = digest( {"speech_sha": raw["sha256"], "normalizer": "pcm48k-v1"} ) if step.kind == "video.lipsync": contract = run.prepared_plan.get("final_render_contract") or {} blend = contract.get("mouth_blend_policy") receipt = job.result_json or {} silence_policy = contract.get("speech_silence_policy", SILENCE_POLICY) if silence_policy == SOURCE_REST_POLICY: resolved = step.resolved_input_json base_sha = resolved["input_sha256"][resolved["input"]["video_asset_id"]] if receipt.get("speech_silence_policy") != silence_policy or receipt.get("base_sha256") != base_sha: fail(409, "dialogue_render_contract_mismatch", "口型生成回执与冻结的静音策略或底片摘要不匹配") elif receipt.get("speech_silence_policy", silence_policy) != silence_policy: fail(409, "dialogue_render_contract_mismatch", "口型生成回执与冻结的静音策略不匹配") shift_policy = contract.get("audio_context_shift_policy") shift = step.resolved_input_json["parameters"].get("audio_context_shift_frames") if ( receipt.get("audio_context_shift_policy") != shift_policy or shift_policy is None and "audio_context_shift_frames" in receipt or shift_policy is not None and ( type(shift) is not int or abs(shift) > 6 or type(receipt.get("audio_context_shift_frames")) is not int or receipt["audio_context_shift_frames"] != shift or receipt.get("synced_sha256") != asset.sha256 ) ): fail( 409, "dialogue_render_contract_mismatch", "口型生成回执与冻结的声学特征偏移策略、参数或视频摘要不匹配", ) if shift_policy is not None: result["provenance"] = dict( audio_context_shift_policy=shift_policy, audio_context_shift_frames=shift ) if silence_policy == SOURCE_REST_POLICY: result["provenance"] = { **(result.get("provenance") or {}), "speech_silence_policy": SOURCE_REST_POLICY, } if receipt.get("mouth_blend_policy") != blend or ( blend and receipt.get("synced_sha256") != asset.sha256 ): fail( 409, "dialogue_render_contract_mismatch", "生成视频的嘴部渲染策略或素材摘要与冻结合同不符", ) if blend is not None: result["mouth_blend_policy"] = blend if kind == "video" and step.kind != "video.compose": from app.adapters.media import inspect_video_track from app.adapters.storage import confined track = await inspect_video_track( confined(settings.asset_root, asset.storage_key, exists=True), settings ) expected = step.resolved_input_json["parameters"].get( "num_frames", step.resolved_input_json["parameters"].get("duration_frames") ) if track["fps"] != 24 or track["frames"] != expected: fail(409, "invalid_output", "对白派生视频未保持精确帧数") result["duration_frames"] = track["frames"] if step.kind in {"audio.mix", "audio.dialogue.extract"}: frames = ( step.resolved_input_json["input"].get("total_frames") if step.kind == "audio.mix" else step.resolved_input_json["parameters"]["duration_frames"] ) if result["sample_count"] != frames * 2000: fail(409, "invalid_output", "音频产物未覆盖确切的贡献帧") if step.kind in {"audio.dialogue.inspect", "video.dialogue.inspect"}: import json from app.adapters.storage import safe_file # The cached binding identifies this verified report asset, so evaluate its actual bytes. with safe_file(settings.asset_root, asset.storage_key) as source: report = json.load(source) if not isinstance(report, dict): fail(409, "invalid_output", "对白质检报告格式无效") result["report"] = report elif kind == "json": result["report"] = deepcopy(job.result_json or {}) m = deepcopy(run.result_manifest) if step.kind == "text.script.generate": texts = {s["shot_id"]: s["text"] for s in (job.result_json or {}).get("segments", [])} wanted = {s["shot_id"] for s in step.resolved_input_json["input"]["shots"]} if set(texts) != wanted: fail(409, "invalid_output", "旁白补全结果不完整") for segment in m["audio"]["segments"]: if not segment["text"].strip() and segment["id"] in texts: segment["text"] = texts[segment["id"]] if step.recipe_json.get("narration"): if step.kind == "audio.speech": segment = next( s for s in m["audio"]["segments"] if s["id"] == step.recipe_json["unit_id"] ) result["context_hash"] = digest( {"text": segment["text"], "parameters": step.recipe_json["parameters"]} ) elif step.kind == "audio.normalize": original = m["bindings"]["audio:" + step.recipe_json["unit_id"]] original.update( sample_count=result["sample_count"], sample_rate=48000, duration_frames=(result["sample_count"] + 1999) // 2000, ) if step.recipe_json.get("binding_key") and step.kind != "audio.dialogue.inspect": m["bindings"][step.recipe_json["binding_key"]] = _binding(result) run.result_manifest = m step.result_json, step.state = result, "succeeded" step.version += 1 await _add_ref(session, run, asset) if step.kind in {"video.dialogue.review", "video.dialogue.inspect", "audio.dialogue.inspect"}: await _quality_result(session, run, step, job, result, settings) if step.kind == "video.compose": run.current_output_asset_id = asset.id async def advance_editor_run(session, run, settings): from app.core.maintenance import maintenance_active from .workflow_engine import child_capacity if run.state in {"succeeded", "cancelled", "failed", "blocked"}: return owner = await session.get(User, run.owner_id) if not owner or owner.disabled: run.hold_reasons = sorted(set(run.hold_reasons or []) | {"admin_suspend"}) steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == run.id))).all() before = digest( { "state": run.state, "phase": run.phase, "steps": [(s.step_key, s.state, s.version) for s in steps], } ) run.hold_reasons = sorted(set(run.hold_reasons or []) - {"quota", "storage"}) if run.desired_state == "cancel": active = await session.scalar( select(Execution.id) .join(Job, Job.id == Execution.job_id) .where(Job.run_id == run.id, Execution.state.not_in({"exited", "results_ready"})) ) jobs = (await session.scalars(select(Job).where(Job.run_id == run.id))).all() if not active and all(j.state in TERMINAL for j in jobs): run.state, run.finished_at = "cancelled", utcnow() else: run.state = "cancelling" await emit_run(session, run) return if run.desired_state == "pause" or run.hold_reasons: run.state = "paused" await emit_run(session, run) return # 旧版恢复入口可能已把仍有阻断步骤的运行改为 queued/running。 blocked = next((s for s in steps if s.state == "blocked"), None) if blocked: run.state = "blocked" if not run.error_json: run.error_json = dict(code="workflow_step_blocked", step_key=blocked.step_key) await emit_run(session, run) return for step in steps: if not step.selected_job_id or step.state in {"succeeded", "blocked", "cancelled"}: continue job = await session.get(Job, step.selected_job_id) if ( not job or job.owner_id != run.owner_id or job.run_id != run.id or job.step_key != step.step_key or job.explicit_attempt != step.explicit_attempt ): continue if job.state == "succeeded": try: async with session.begin_nested(): await _collect(session, run, step, job, settings) except (HTTPException, ValueError, MediaError) as exc: await session.refresh(step) await session.refresh(run) detail = ( exc.detail if isinstance(exc, HTTPException) and isinstance(exc.detail, dict) else {} ) step.state, run.state = "blocked", "blocked" run.error_json = dict( code=detail.get("code", "invalid_output"), step_key=step.step_key ) elif job.state in {"failed", "timed_out", "needs_attention", "cancelled"}: step.state, run.state = "blocked", "blocked" run.error_json = { "code": "dialogue_step_failed", "step_key": step.step_key, "cause": deepcopy(job.error_json), } else: step.state = "running" if job.state in {"running", "collecting"} else "ready" if run.state == "blocked": await emit_run(session, run) return if run.prepared_plan is None and all(s.state == "succeeded" for s in steps): await _materialize(session, run, steps, settings) steps = ( await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == run.id)) ).all() if run.state == "blocked": await emit_run(session, run) return if ( run.prepared_plan and run.prepared_plan.get("production_materialized") and all(s.state == "succeeded" for s in steps) ): run.state, run.phase, run.finished_at = "succeeded", "complete", utcnow() run.error_json = None # 应用由advance_workflows提交后的独立事务完成,不反向获取用户/草稿锁。 run.apply_state = "pending" await emit_run(session, run) return run.state, run.started_at = "running", run.started_at or utcnow() bykey = {s.step_key: s for s in steps} admitted = 0 for recipe in execution_recipes(run): step = bykey[recipe["key"]] if ( step.state != "waiting" or step.selected_job_id or not all(bykey[k].state == "succeeded" for k in step.dependencies) ): continue if admitted >= 8 or maintenance_active(settings): break if not await child_capacity(session, run, step, settings): run.hold_reasons = ["quota"] break try: async with session.begin_nested(): await create_editor_child(session, run, step, settings) except (HTTPException, ValueError, MediaError) as exc: await session.refresh(step) await session.refresh(run) detail = ( exc.detail if isinstance(exc, HTTPException) and isinstance(exc.detail, dict) else {} ) code = detail.get("code", "invalid_dialogue_input") if code in {"quota_exceeded", "storage_insufficient"}: run.hold_reasons = ["quota" if code == "quota_exceeded" else "storage"] break step.state, run.state = "blocked", "blocked" run.error_json = dict( code=code, step_key=step.step_key, message=detail.get("message", "对白步骤无法执行") ) break admitted += 1 after = digest( { "state": run.state, "phase": run.phase, "steps": [(s.step_key, s.state, s.version) for s in steps], } ) if before != after: if ( run.state == "running" and (run.error_json or {}).get("code") == "workflow_orchestration_failed" and all(s.state != "blocked" for s in steps) ): run.error_json = None await emit_run(session, run)