978 lines
38 KiB
Python
978 lines
38 KiB
Python
"""H3 原生音视频 DAG;复用持久父任务调度,所有媒体工作均由普通 Job 完成。"""
|
||
|
||
from copy import deepcopy
|
||
import json
|
||
import wave
|
||
|
||
from sqlalchemy import select
|
||
|
||
from app.adapters.provider import native_av
|
||
from app.adapters.provider.continuity_media import (
|
||
DIALOGUE_REVIEW_SAMPLING_POLICY,
|
||
dialogue_review_frame_indices,
|
||
)
|
||
from app.adapters.storage import safe_file, confined
|
||
from app.core.errors import fail
|
||
from app.domain.native_dialogue import compile_native_shots
|
||
from app.domain.native_av import align_native_utterances, normalize_native_text
|
||
from app.domain.native_silence import POLICY as SILENCE_POLICY, verified_silence
|
||
from app.domain.stories import compile_story, ordered_reference_ids
|
||
from app.models import Asset, WorkflowStep
|
||
from app.services.workflows import digest, verified_output
|
||
|
||
POLICY = "native_av_v1"
|
||
CONTENT_POLICY = "whisper-sensevoice-consensus-v1"
|
||
|
||
|
||
def _issue(code, unit, message):
|
||
return dict(code=code, unit_id=unit, message=message)
|
||
|
||
|
||
def _capability(kind, parameters, settings):
|
||
snapshot = getattr(settings, "_native_av_upstream", {})
|
||
if kind == "video.generate":
|
||
profile = parameters.get("profile")
|
||
return native_av.enabled(settings, profile) and native_av.canvas_certified(
|
||
native_av.select_evidence(snapshot, profile),
|
||
profile,
|
||
parameters.get("width"),
|
||
parameters.get("height"),
|
||
)
|
||
if kind == "audio.dialogue.inspect":
|
||
return native_av.alignment_enabled(settings, snapshot)
|
||
if kind == "video.dialogue.review":
|
||
return (
|
||
getattr(settings, "dialogue_quality_certified", False) is True
|
||
and bool(getattr(settings, "qwen_base_url", ""))
|
||
and bool(getattr(settings, "qwen_model", ""))
|
||
)
|
||
return True
|
||
|
||
|
||
def _video_context(context, frame_sha):
|
||
return digest(dict(native_context=context, frame_sha256=frame_sha, policy=POLICY))
|
||
|
||
|
||
def _review_context(video_sha, reference_shas, expected):
|
||
# 采样变化只使视觉审核证据失效,不改变昂贵的原生视频生成上下文。
|
||
return digest(dict(
|
||
video_sha=video_sha, refs=reference_shas, expected=expected, policy=POLICY,
|
||
review_sampling_policy=DIALOGUE_REVIEW_SAMPLING_POLICY,
|
||
))
|
||
|
||
|
||
def _valid_review_sampling(report, start, end):
|
||
"""升级前的边界采样报告不能因重新collect而冒充当前策略的证据。"""
|
||
if (
|
||
not isinstance(report, dict)
|
||
or type(start) is not int
|
||
or type(end) is not int
|
||
or not 0 <= start < end
|
||
or report.get("review_sampling_policy") != DIALOGUE_REVIEW_SAMPLING_POLICY
|
||
or type(report.get("source_start_frame")) is not int
|
||
or type(report.get("source_end_frame")) is not int
|
||
or report["source_start_frame"] != start
|
||
or report["source_end_frame"] != end
|
||
):
|
||
return False
|
||
evidence = report.get("frame_evidence")
|
||
indices = evidence.get("current_indices") if isinstance(evidence, dict) else None
|
||
return (
|
||
isinstance(indices, list)
|
||
and all(type(i) is int for i in indices)
|
||
and indices == dialogue_review_frame_indices(start, end)
|
||
)
|
||
|
||
|
||
def _audio_review_context(audio_sha, expected_text, speaker_id):
|
||
return digest(
|
||
dict(
|
||
audio_sha=audio_sha,
|
||
expected_text=expected_text,
|
||
speaker_id=speaker_id,
|
||
policy=POLICY,
|
||
content_verification_policy=CONTENT_POLICY if expected_text.strip() else SILENCE_POLICY,
|
||
)
|
||
)
|
||
|
||
|
||
def _content_consensus(report, expected):
|
||
if not isinstance(expected, str):
|
||
return False
|
||
if not expected.strip():
|
||
return verified_silence(report, expected)
|
||
normalized = normalize_native_text(expected)
|
||
if not normalized:
|
||
return False
|
||
fields = dict(
|
||
content_verification_policy=CONTENT_POLICY,
|
||
content_decision_source="whisper_sensevoice_consensus",
|
||
secondary_status="completed",
|
||
secondary_asr_revision="90c1c61912018b70ada0fcc024ea24aca62f2e63",
|
||
secondary_runtime_revision="6991744856587fa44379e8b5dcc432debffeb1be",
|
||
normalized_expected_text=normalized,
|
||
normalized_transcript=normalized,
|
||
normalized_secondary_transcript=normalized,
|
||
)
|
||
if any(report.get(k) != v for k, v in fields.items()):
|
||
return False
|
||
for name in ("content_error_rate", "secondary_content_error_rate"):
|
||
if type(report.get(name)) not in (int, float) or report[name] != 0:
|
||
return False
|
||
for name in ("transcript", "secondary_transcript"):
|
||
if (
|
||
not isinstance(report.get(name), str)
|
||
or normalize_native_text(report[name]) != normalized
|
||
):
|
||
return False
|
||
return True
|
||
|
||
|
||
def _read_report(asset, settings):
|
||
with safe_file(settings.asset_root, asset.storage_key) as source:
|
||
report = json.load(source)
|
||
if not isinstance(report, dict):
|
||
fail(409, "invalid_native_alignment", "原生报告必须是完整对象")
|
||
return report
|
||
|
||
|
||
def _wav_info(asset, settings):
|
||
try:
|
||
with safe_file(settings.asset_root, asset.storage_key) as source:
|
||
with wave.open(source, "rb") as audio:
|
||
return (
|
||
audio.getnframes(),
|
||
audio.getframerate(),
|
||
audio.getnchannels(),
|
||
audio.getsampwidth(),
|
||
)
|
||
except (OSError, EOFError, wave.Error):
|
||
fail(409, "invalid_output", "音频产物不是可解码的完整 PCM WAV")
|
||
|
||
|
||
async def plan_editor(session, draft, manifest, body, settings):
|
||
from .dialogue_engine import _recipe
|
||
from .editor_engine import _asset
|
||
from app.domain.editors import collect_manifest_asset_ids
|
||
from app.services.stories.common import spec_assets
|
||
|
||
body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body
|
||
allowed = {
|
||
f"{role}:{sid}"
|
||
for sid in manifest["shot_ids"]
|
||
for role in ("frame", "video", "native_alignment")
|
||
} | {"captions"}
|
||
if any(key not in allowed for key in [*body.get("targets", []), *body.get("force", [])]):
|
||
fail(422, "invalid_target", "原生对白仅支持首帧、原生视频或逐词验收目标")
|
||
projection = compile_native_shots(manifest)
|
||
m = projection["manifest"]
|
||
m["spec"]["render"]["total_frames"] = projection["timing"]["total_frames"]
|
||
model, references = await spec_assets(session, draft.owner_id, m["spec"], settings)
|
||
compiled = compile_story(model, references)
|
||
compiled_shots = {s["shot_id"]: s for s in compiled["shots"]}
|
||
assets, reusable = {}, {}
|
||
for aid in collect_manifest_asset_ids(manifest):
|
||
a = await session.get(Asset, aid)
|
||
if (
|
||
not a
|
||
or a.owner_id != draft.owner_id
|
||
or a.deleted_at
|
||
or not a.ready
|
||
or a.library_scope != "private"
|
||
):
|
||
fail(404, "asset_not_found", "原生对白来源素材不存在或不可访问")
|
||
assets[aid] = a
|
||
for key, binding in manifest.get("bindings", {}).items():
|
||
if await _asset(session, draft.owner_id, binding, settings, binding.get("kind")):
|
||
reusable[key] = deepcopy(binding)
|
||
force = set(body.get("force", []))
|
||
force.update(
|
||
"native_report:" + key.partition(":")[2]
|
||
for key in tuple(force)
|
||
if key.startswith("native_alignment:")
|
||
)
|
||
recipes, lookup = [], {}
|
||
shots = {s["id"]: s for s in m["spec"]["shots"]}
|
||
utterances = {u["id"]: u for u in m["spec"]["dialogue"]["utterances"]}
|
||
all_gates = []
|
||
|
||
def add(
|
||
key,
|
||
kind,
|
||
unit,
|
||
binding=None,
|
||
*,
|
||
deps=(),
|
||
inputs=None,
|
||
parameters=None,
|
||
context=None,
|
||
reuse=None,
|
||
changed=False,
|
||
):
|
||
if binding in force or changed:
|
||
reuse = None
|
||
r = _recipe(
|
||
key,
|
||
kind,
|
||
unit,
|
||
binding,
|
||
dependencies=deps,
|
||
inputs=inputs,
|
||
parameters=parameters,
|
||
context=context,
|
||
reuse=reuse,
|
||
forced=binding in force,
|
||
)
|
||
previous = manifest.get("bindings", {}).get(binding, {})
|
||
if previous.get("locked") and reuse is None and binding not in force:
|
||
r["issue"] = _issue(
|
||
"locked_dependency_changed",
|
||
unit,
|
||
"锁定的原生素材与当前依赖不符,请明确强制重生成或解锁",
|
||
)
|
||
recipes.append(r)
|
||
lookup[key] = key
|
||
if binding:
|
||
lookup[binding] = key
|
||
return r
|
||
|
||
for i, native in enumerate(projection["shots"], 1):
|
||
sid, shot = native["shot_id"], shots[native["shot_id"]]
|
||
c = compiled_shots[sid]
|
||
refs = ordered_reference_ids(c.get("references", []))
|
||
portrait = m["spec"].get("profile") == "portrait_1080_v1"
|
||
fp = dict(
|
||
width=704 if portrait else 1280,
|
||
height=1280 if portrait else 704,
|
||
seed=shot.get("frame_parameters", {}).get("seed", 42),
|
||
num_inference_steps=40 if refs else 50,
|
||
guidance_scale=1.0 if refs else 4.0,
|
||
)
|
||
if refs:
|
||
fp.update(
|
||
profile=getattr(
|
||
settings, "reference_generation_profile", "qwen-image-edit-2511-v1"
|
||
),
|
||
true_cfg_scale=4.0,
|
||
)
|
||
fi = dict(
|
||
prompt=c["frame_prompt"],
|
||
negative_prompt=c.get("effective_settings", {}).get("negative_prompt", ""),
|
||
)
|
||
if refs:
|
||
fi["reference_asset_ids"] = refs
|
||
fc = digest(
|
||
dict(prompt=fi, parameters=fp, reference_shas={aid: assets[aid].sha256 for aid in refs})
|
||
)
|
||
frame = reusable.get("frame:" + sid)
|
||
if frame and frame.get("source") != "manual" and frame.get("context_hash") != fc:
|
||
frame = None
|
||
fr = add(
|
||
f"frame_{i:04d}",
|
||
"image.reference.generate" if refs else "image.generate",
|
||
sid,
|
||
"frame:" + sid,
|
||
inputs=fi,
|
||
parameters=fp,
|
||
context=fc,
|
||
reuse=frame,
|
||
)
|
||
vc = _video_context(native["context_hash"], (fr["reuse"] or {}).get("sha256"))
|
||
video = reusable.get("video:" + sid)
|
||
provenance = (video or {}).get("provenance") or {}
|
||
sidecar = assets.get(provenance.get("native_source_audio_asset_id"))
|
||
if not sidecar and provenance.get("native_source_audio_asset_id"):
|
||
sidecar = await session.get(Asset, provenance["native_source_audio_asset_id"])
|
||
valid_sidecar = sidecar and await _asset(
|
||
session,
|
||
draft.owner_id,
|
||
dict(asset_id=sidecar.id, sha256=provenance.get("native_source_audio_sha256")),
|
||
settings,
|
||
"audio",
|
||
)
|
||
if (
|
||
not video
|
||
or not fr["reuse"]
|
||
or video.get("context_hash") != vc
|
||
or provenance.get("native_av_policy") != POLICY
|
||
or not valid_sidecar
|
||
):
|
||
video = None
|
||
vr = add(
|
||
f"nv_{i:04d}",
|
||
"video.generate",
|
||
sid,
|
||
"video:" + sid,
|
||
deps=[fr["key"]],
|
||
inputs=dict(prompt=native["prompt"]),
|
||
parameters=native["parameters"],
|
||
context=vc,
|
||
reuse=video,
|
||
changed=fr["reuse"] is None,
|
||
)
|
||
vr["native_context"] = native["context_hash"]
|
||
vr["native_utterance_ids"] = native["utterance_ids"]
|
||
original_video = manifest.get("bindings", {}).get("video:" + sid, {})
|
||
if original_video.get("source") == "manual" and not {
|
||
"frame:" + sid,
|
||
"video:" + sid,
|
||
}.intersection(force):
|
||
vr["issue"] = _issue(
|
||
"native_import_unsupported",
|
||
sid,
|
||
"当前原生对白不直接采用导入视频;请保留原片,并明确强制生成此镜头",
|
||
)
|
||
source_sha = (vr["reuse"] or {}).get("sha256")
|
||
nc = digest(dict(video_sha=source_sha, policy=POLICY))
|
||
audio = reusable.get("native_audio:" + sid)
|
||
if audio and audio.get("context_hash") != nc:
|
||
audio = None
|
||
ar = add(
|
||
f"na_{i:04d}",
|
||
"audio.dialogue.extract",
|
||
sid,
|
||
"native_audio:" + sid,
|
||
deps=[vr["key"]],
|
||
parameters=dict(
|
||
audio_policy=POLICY,
|
||
start_frame=0,
|
||
duration_frames=native["parameters"]["num_frames"],
|
||
),
|
||
context=nc,
|
||
reuse=audio,
|
||
changed=vr["reuse"] is None,
|
||
)
|
||
expected_text = "".join(
|
||
utterances[u].get("spoken_text") or utterances[u]["text"]
|
||
for u in native["utterance_ids"]
|
||
)
|
||
speaker = native["speaker_id"] or sid
|
||
qc = _audio_review_context((ar["reuse"] or {}).get("sha256"), expected_text, speaker)
|
||
report = reusable.get("native_report:" + sid)
|
||
if report and report.get("context_hash") != qc:
|
||
report = None
|
||
qr = add(
|
||
f"nq_{i:04d}",
|
||
"audio.dialogue.inspect",
|
||
sid,
|
||
"native_report:" + sid,
|
||
deps=[ar["key"]],
|
||
inputs=dict(expected_text=expected_text, speaker_id=speaker),
|
||
parameters=dict(
|
||
profile="dialogue-audio-v1", sample_rate=48000, native_av_policy=POLICY
|
||
),
|
||
context=qc,
|
||
reuse=report,
|
||
changed=ar["reuse"] is None,
|
||
)
|
||
visible_speech = (
|
||
native["speaker_id"] is not None
|
||
and native["speaker_id"] in shot["performance"]["visible_speaker_ids"]
|
||
and shot["performance"].get("lip_sync") != "off"
|
||
)
|
||
expected = dict(
|
||
source_start_frame=0,
|
||
source_end_frame=native["parameters"]["num_frames"],
|
||
fps=24,
|
||
transition="cut",
|
||
dedup_frames=0,
|
||
expected_motion=shot["continuity"].get("expected_motion", True),
|
||
visual=shot["visual_prompt"],
|
||
motion=shot["motion_prompt"],
|
||
characters=[
|
||
sp["name"]
|
||
for sp in m["spec"]["dialogue"]["speakers"]
|
||
if sp["id"] in shot["performance"]["visible_speaker_ids"]
|
||
],
|
||
native_dialogue=expected_text,
|
||
mouth_expectation=(
|
||
"说话人自然发音,其他人物保持嘴部放松"
|
||
if visible_speech
|
||
else "画面中所有人物自然放松闭唇,使用眼神和肢体动作表演,不做发音口型"
|
||
),
|
||
)
|
||
rc = _review_context(source_sha, {aid: assets[aid].sha256 for aid in refs[:3]}, expected)
|
||
review = reusable.get("dialogue_report:" + sid)
|
||
if review and review.get("context_hash") != rc:
|
||
review = None
|
||
rr = add(
|
||
f"nr_{i:04d}",
|
||
"video.dialogue.review",
|
||
sid,
|
||
"dialogue_report:" + sid,
|
||
deps=[vr["key"]],
|
||
inputs=dict(
|
||
reference_asset_ids=refs[:3],
|
||
expected=expected,
|
||
),
|
||
context=rc,
|
||
reuse=review,
|
||
changed=vr["reuse"] is None,
|
||
)
|
||
gr = add(
|
||
f"ng_{i:04d}",
|
||
"dialogue.accepted",
|
||
sid,
|
||
"native_alignment:" + sid,
|
||
deps=[vr["key"], ar["key"], qr["key"], rr["key"]],
|
||
context=vc,
|
||
)
|
||
gr.update(
|
||
native_utterance_ids=native["utterance_ids"],
|
||
audio_key=ar["key"],
|
||
report_key=qr["key"],
|
||
review_key=rr["key"],
|
||
video_key=vr["key"],
|
||
)
|
||
previous_alignment = manifest.get("bindings", {}).get("native_alignment:" + sid, {})
|
||
if previous_alignment.get("context_hash") == vc and all(
|
||
row["reuse"] for row in (vr, ar, qr, rr)
|
||
):
|
||
# 仍重新读取证据并物化全局字幕;稳定锁定不应阻止字幕或配乐编辑。
|
||
gr.pop("issue", None)
|
||
# video 目标意味着经过完整验收;首帧目标仍只包含首帧闭包。
|
||
lookup["video:" + sid] = gr["key"]
|
||
all_gates.append(gr["key"])
|
||
|
||
norms = []
|
||
for i, aid in enumerate(
|
||
dict.fromkeys(layer["asset_id"] for layer in m.get("audio", {}).get("layers", []))
|
||
):
|
||
r = add(f"native_bgm_{i:04d}", "audio.normalize", aid, inputs=dict(asset_id=aid))
|
||
norms.append(r["key"])
|
||
add(
|
||
"dialogue_mix",
|
||
"audio.mix",
|
||
"audio",
|
||
deps=[*all_gates, *norms],
|
||
parameters=dict(ducking=m["audio"].get("ducking", True)),
|
||
)
|
||
add("dialogue_captions", "captions.compile", "captions", deps=all_gates)
|
||
lookup["captions"] = "dialogue_captions"
|
||
add("compose", "video.compose", "film", deps=["dialogue_mix", "dialogue_captions", *all_gates])
|
||
bykey = {r["key"]: r for r in recipes}
|
||
selected = set()
|
||
|
||
def include(key):
|
||
if key in selected:
|
||
return
|
||
selected.add(key)
|
||
for dependency in bykey[key]["dependencies"]:
|
||
include(dependency)
|
||
|
||
targets = (
|
||
["compose"]
|
||
if body.get("output_goal", "film") == "film"
|
||
else body.get("targets") or ["video:" + sid for sid in manifest["shot_ids"]]
|
||
)
|
||
for target in [*targets, *force]:
|
||
include(lookup[target])
|
||
rows = [r for r in recipes if r["key"] in selected]
|
||
selected_units = {
|
||
r["unit_id"]
|
||
for r in rows
|
||
if r["kind"] != "image.generate" and r["kind"] != "image.reference.generate"
|
||
}
|
||
selected_utterances = {
|
||
uid
|
||
for sequence in m["spec"]["dialogue"]["sequences"]
|
||
if selected_units.intersection(sequence["shot_ids"])
|
||
for uid in sequence["utterance_ids"]
|
||
}
|
||
issues = [
|
||
i
|
||
for i in projection["issues"]
|
||
if i["unit_id"] in selected_units | selected_utterances
|
||
or selected_units
|
||
and i["unit_id"] == "dialogue"
|
||
or body.get("output_goal", "film") == "film"
|
||
]
|
||
if selected_units and m["spec"]["dialogue"].get("language", "Chinese") != "Chinese":
|
||
issues.append(
|
||
_issue("native_language_uncertified", "dialogue", "当前原生对白仅完成中文独立认证")
|
||
)
|
||
for r in rows:
|
||
if r.get("issue"):
|
||
issues.append(r["issue"])
|
||
if not r["reuse"] and not _capability(r["kind"], r["parameters"], settings):
|
||
issues.append(
|
||
_issue(
|
||
"capability_unavailable",
|
||
r["unit_id"],
|
||
"原生音视频、逐词识别或画面评审尚未完成独立认证",
|
||
)
|
||
)
|
||
if body.get("output_goal", "film") == "film":
|
||
if len(m["shot_ids"]) > 60 or projection["timing"]["total_frames"] > min(
|
||
7200, m["production"]["max_total_frames"]
|
||
):
|
||
issues.append(
|
||
_issue(
|
||
"dialogue_budget_exceeded", "production", "原生对白镜头或整片帧数超过制作预算"
|
||
)
|
||
)
|
||
if (
|
||
m["audio"].get("mode") in {"generated_narration", "manual_track"}
|
||
or m["audio"].get("mix_mode") == "manual_mix"
|
||
):
|
||
issues.append(
|
||
_issue(
|
||
"dialogue_audio_conflict",
|
||
"audio",
|
||
"原生对白使用原声音轨,请将配乐放入独立背景音乐层",
|
||
)
|
||
)
|
||
caps = dict(
|
||
reference_shas={aid: a.sha256 for aid, a in assets.items()},
|
||
native_av=deepcopy(getattr(settings, "_native_av_upstream", {})),
|
||
)
|
||
prepared = dict(
|
||
production_materialized=True,
|
||
effective_manifest=m if selected_units else deepcopy(manifest),
|
||
timing=projection["timing"],
|
||
utterances=[],
|
||
issues=[],
|
||
steps=[],
|
||
native_av_policy=POLICY,
|
||
)
|
||
return dict(
|
||
output_goal=body.get("output_goal", "film"),
|
||
source_version=draft.version,
|
||
steps=[
|
||
dict(
|
||
key=r["key"],
|
||
kind=r["kind"],
|
||
unit_id=r["unit_id"],
|
||
status="reuse" if r["reuse"] else "generate",
|
||
)
|
||
for r in rows
|
||
],
|
||
issues=issues,
|
||
plan_hash=digest(
|
||
dict(
|
||
manifest=manifest,
|
||
body={k: v for k, v in body.items() if k != "expected_plan_hash"},
|
||
recipes=rows,
|
||
capabilities=caps,
|
||
issues=issues,
|
||
)
|
||
),
|
||
_recipes=rows,
|
||
_capabilities=caps,
|
||
_prepared=prepared,
|
||
)
|
||
|
||
|
||
async def _verified_inputs(session, run, inputs, settings):
|
||
from app.domain.editors import collect_manifest_asset_ids
|
||
from .editor_engine import _asset
|
||
|
||
hashes = {}
|
||
for aid in collect_manifest_asset_ids(inputs):
|
||
asset = await session.get(Asset, aid)
|
||
frozen = run.plan_snapshot.get("asset_sha256", {}).get(aid)
|
||
if not asset or not await _asset(
|
||
session, run.owner_id, dict(asset_id=aid, sha256=frozen or asset.sha256), settings
|
||
):
|
||
fail(409, "dependency_changed", "冻结的原生素材已变化或不可访问")
|
||
hashes[aid] = asset.sha256
|
||
return hashes
|
||
|
||
|
||
async def resolve(session, run, step, settings):
|
||
from .dialogue_engine import _compose_inputs
|
||
|
||
recipe, m = step.recipe_json, run.result_manifest
|
||
inputs, parameters = deepcopy(recipe["input"]), deepcopy(recipe["parameters"])
|
||
sid, b = recipe["unit_id"], m["bindings"]
|
||
if step.kind == "video.generate":
|
||
inputs["first_frame_asset_id"] = b["frame:" + sid]["asset_id"]
|
||
elif step.kind == "audio.dialogue.extract":
|
||
source = b["video:" + sid]
|
||
inputs = dict(
|
||
video_asset_id=source["asset_id"],
|
||
audio_asset_id=source["provenance"]["native_source_audio_asset_id"],
|
||
)
|
||
elif step.kind == "audio.dialogue.inspect":
|
||
inputs["audio_asset_id"] = b["native_audio:" + sid]["asset_id"]
|
||
elif step.kind == "video.dialogue.review":
|
||
inputs["video_asset_id"] = b["video:" + sid]["asset_id"]
|
||
elif step.kind == "audio.mix":
|
||
inputs = await mix_inputs(session, run)
|
||
elif step.kind == "captions.compile":
|
||
from app.services.editor_media import compile_captions, materialize_cues
|
||
|
||
return dict(
|
||
input={},
|
||
parameters={},
|
||
input_sha256={},
|
||
captions=compile_captions(m, b, prepared=run.prepared_plan),
|
||
editable_cues=materialize_cues(m, b, prepared=run.prepared_plan),
|
||
)
|
||
elif step.kind == "video.compose":
|
||
inputs, parameters = await _compose_inputs(session, run, settings)
|
||
return dict(
|
||
input=inputs,
|
||
parameters=parameters,
|
||
input_sha256=await _verified_inputs(session, run, inputs, settings),
|
||
)
|
||
|
||
|
||
async def before_child(session, run, step, settings):
|
||
if not _capability(step.kind, step.recipe_json["parameters"], settings):
|
||
fail(422, "capability_unavailable", "原生能力认证已失效,停止派发")
|
||
if step.kind != "dialogue.accepted":
|
||
return False
|
||
await accept_shot(session, run, step, settings)
|
||
return True
|
||
|
||
|
||
async def accept_shot(session, run, step, settings):
|
||
from .dialogue_engine import _step, _binding
|
||
from .editor_engine import _asset, _add_ref
|
||
|
||
r, m = step.recipe_json, deepcopy(run.result_manifest)
|
||
sid = r["unit_id"]
|
||
results = {
|
||
key: (await _step(session, run, r[key])).result_json
|
||
for key in ("video_key", "audio_key", "report_key", "review_key")
|
||
}
|
||
for result in results.values():
|
||
if not await _asset(session, run.owner_id, result, settings, result["kind"]):
|
||
fail(409, "invalid_native_alignment", "原生验收依赖已变化")
|
||
audio, video = results["audio_key"], results["video_key"]
|
||
report_asset = await session.get(Asset, results["report_key"]["asset_id"])
|
||
report = _read_report(report_asset, settings)
|
||
review = _read_report(await session.get(Asset, results["review_key"]["asset_id"]), settings)
|
||
utterances = [
|
||
next(u for u in m["spec"]["dialogue"]["utterances"] if u["id"] == uid)
|
||
for uid in r["native_utterance_ids"]
|
||
]
|
||
expected = "".join(u.get("spoken_text") or u["text"] for u in utterances)
|
||
speaker = utterances[0]["speaker_id"] if utterances else sid
|
||
matches = dict(
|
||
native_av_policy=POLICY,
|
||
audio_sha256=audio["sha256"],
|
||
expected_text=expected,
|
||
speaker_id=speaker,
|
||
source_start_sample=0,
|
||
source_end_sample=audio["sample_count"],
|
||
sample_rate=48000,
|
||
timestamp_source="whisper-word-timestamps",
|
||
timestamp_origin="audio_asset",
|
||
asr_revision="41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
|
||
)
|
||
if (
|
||
any(report.get(k) != v for k, v in matches.items())
|
||
or report.get("decision") != "pass"
|
||
or not _content_consensus(report, expected)
|
||
or report.get("reasons")
|
||
):
|
||
fail(409, "invalid_native_alignment", "原声词时间报告与本次音轨、整句台词或识别合同不匹配")
|
||
if (
|
||
review.get("decision", review.get("verdict")) != "pass"
|
||
or results["review_key"].get("provenance", {}).get("video_sha256") != video["sha256"]
|
||
or review.get("source_start_frame") != 0
|
||
or review.get("source_end_frame") != video["duration_frames"]
|
||
or not _valid_review_sampling(review, 0, video["duration_frames"])
|
||
):
|
||
fail(409, "native_visual_rejected", "原生视频画面评审未通过或来源摘要不匹配")
|
||
try:
|
||
if utterances:
|
||
aligned = align_native_utterances(
|
||
report,
|
||
utterances,
|
||
audio_offset_samples=audio.get("provenance", {}).get("audio_offset_samples", 0),
|
||
)
|
||
else:
|
||
# 静默已经由独立 VAD 与实际空的 SenseVoice 证实;保留 Whisper
|
||
# 原始幻觉及失败词时间,只不给不存在的台词制造字幕时间。
|
||
aligned = []
|
||
except ValueError as exc:
|
||
fail(409, "invalid_native_alignment", str(exc))
|
||
t = next(t for t in run.prepared_plan["timing"]["shots"] if t["shot_id"] == sid)
|
||
if any(u["end_sample"] > (t["contribution_frames"] - 1) * 2000 for u in aligned):
|
||
fail(409, "native_dialogue_overflow", "完整台词未在视频结束至少一帧前说完,禁止裁掉句尾")
|
||
binding = _binding(results["report_key"])
|
||
binding["provenance"] = dict(
|
||
native_av_policy=POLICY,
|
||
native_context=video["context_hash"],
|
||
video_sha256=video["sha256"],
|
||
audio_sha256=audio["sha256"],
|
||
review_sha256=results["review_key"]["sha256"],
|
||
shot_id=sid,
|
||
utterances=aligned,
|
||
audio_offset_samples=audio.get("provenance", {}).get("audio_offset_samples", 0),
|
||
)
|
||
binding["context_hash"] = video["context_hash"]
|
||
old = m["bindings"].get("native_alignment:" + sid, {})
|
||
if (
|
||
old.get("locked")
|
||
and old.get("context_hash") != binding["context_hash"]
|
||
and not r.get("forced")
|
||
):
|
||
fail(409, "locked_dependency_changed", "锁定的原生逐词验收已失效")
|
||
if old.get("locked") and not r.get("forced"):
|
||
binding["locked"] = True
|
||
m["bindings"]["native_alignment:" + sid] = binding
|
||
run.result_manifest = m
|
||
prepared = deepcopy(run.prepared_plan)
|
||
keep = {u["id"] for u in utterances}
|
||
prepared["utterances"] = [
|
||
u for u in prepared["utterances"] if u["utterance_id"] not in keep
|
||
] + [
|
||
{
|
||
**u,
|
||
"start_sample": u["start_sample"] + t["start_frame"] * 2000,
|
||
"end_sample": u["end_sample"] + t["start_frame"] * 2000,
|
||
}
|
||
for u in aligned
|
||
]
|
||
prepared["effective_manifest"] = deepcopy(m)
|
||
run.prepared_plan = prepared
|
||
step.result_json, step.state = deepcopy(binding), "succeeded"
|
||
step.version += 1
|
||
await _add_ref(session, run, report_asset)
|
||
|
||
|
||
async def mix_inputs(session, run):
|
||
from app.domain.audio_timeline import compile_audio_timeline
|
||
|
||
m, rows = deepcopy(run.result_manifest), []
|
||
timing = {t["shot_id"]: t for t in run.prepared_plan["timing"]["shots"]}
|
||
for sid, t in timing.items():
|
||
audio = m["bindings"]["native_audio:" + sid]
|
||
evidence = m["bindings"]["native_alignment:" + sid]["provenance"]
|
||
offset = audio.get("provenance", {}).get("audio_offset_samples", 0)
|
||
maximum = t["contribution_frames"] * 2000 - offset
|
||
count = audio["sample_count"]
|
||
if count > maximum:
|
||
# 完整 WAV 永久保留;只有经逐词验收证明为非语音的尾部半格可不参与整片混音。
|
||
if count - maximum > 600 or any(
|
||
u["end_sample"] > maximum for u in evidence["utterances"]
|
||
):
|
||
fail(409, "native_audio_overflow", "原声尾部超出视频且没有安全的非语音边界")
|
||
count = maximum
|
||
audio.setdefault("provenance", {}).update(
|
||
mix_source_end_sample=count, mix_tail_omitted_samples=audio["sample_count"] - count
|
||
)
|
||
rows.append(
|
||
dict(
|
||
asset_id=audio["asset_id"],
|
||
source_start_sample=0,
|
||
source_end_sample=count,
|
||
offset_sample=t["start_frame"] * 2000 + offset,
|
||
role="narration",
|
||
segment_id=sid,
|
||
)
|
||
)
|
||
norms = (
|
||
await session.scalars(
|
||
select(WorkflowStep).where(
|
||
WorkflowStep.run_id == run.id, WorkflowStep.kind == "audio.normalize"
|
||
)
|
||
)
|
||
).all()
|
||
samples, remap = {}, {}
|
||
for n in norms:
|
||
source = n.resolved_input_json["input"]["asset_id"]
|
||
samples[source], remap[source] = n.result_json["sample_count"], n.result_json["asset_id"]
|
||
projection = deepcopy(m)
|
||
projection["audio"].update(mode="silent", segments=[])
|
||
timeline = compile_audio_timeline(projection, m["bindings"], source_samples=samples)
|
||
rows.extend(
|
||
{**row, "asset_id": remap.get(row["asset_id"], row["asset_id"])}
|
||
for row in timeline["segments"]
|
||
)
|
||
if not 1 <= len(rows) <= 128:
|
||
fail(422, "production_limit", "原声与背景音乐总片段数超过上限")
|
||
run.result_manifest = m
|
||
return dict(segments=rows, total_frames=run.prepared_plan["timing"]["total_frames"])
|
||
|
||
|
||
async def collect(session, run, step, job, settings):
|
||
from .editor_engine import _collect as collect_frame, _add_ref
|
||
from .dialogue_engine import _binding
|
||
from app.adapters.media import inspect_video_track
|
||
|
||
if step.kind in {"image.generate", "image.reference.generate", "image.prepare_frame"}:
|
||
return await collect_frame(session, run, step, job, settings)
|
||
if (
|
||
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
|
||
or step.selected_job_id != job.id
|
||
):
|
||
fail(409, "invalid_output", "原生产物不属于当前选中的任务尝试")
|
||
kind = (
|
||
"json"
|
||
if step.kind in {"audio.dialogue.inspect", "video.dialogue.review"}
|
||
else "video"
|
||
if step.kind in {"video.generate", "video.compose"}
|
||
else "audio"
|
||
)
|
||
candidates = (
|
||
await session.scalars(
|
||
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),
|
||
)
|
||
)
|
||
).all()
|
||
selected = [a for a in candidates if a.kind == kind]
|
||
if len(selected) != 1 or not await verified_output(selected[0], settings):
|
||
fail(409, "invalid_output", "原生任务必须返回唯一可校验的主产物")
|
||
asset = selected[0]
|
||
r, resolved = step.recipe_json, step.resolved_input_json
|
||
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=r.get("context_hash"),
|
||
generation_parameters=deepcopy(resolved["parameters"]),
|
||
)
|
||
if kind == "video":
|
||
track = await inspect_video_track(
|
||
confined(settings.asset_root, asset.storage_key, exists=True), settings
|
||
)
|
||
expected = resolved["parameters"].get(
|
||
"num_frames", run.prepared_plan["timing"]["total_frames"]
|
||
)
|
||
if track["frames"] != expected or track["fps"] != 24:
|
||
fail(409, "invalid_output", "原生视频未保持完整24fps实测帧数")
|
||
result.update(duration_frames=track["frames"], duration_seconds=track["frames"] / 24)
|
||
if step.kind == "video.generate":
|
||
from app.adapters.provider.native_av_media import _timing
|
||
from types import SimpleNamespace
|
||
|
||
_, _, embedded_channels = await _timing(
|
||
SimpleNamespace(settings=settings),
|
||
confined(settings.asset_root, asset.storage_key, exists=True),
|
||
)
|
||
if embedded_channels != 2:
|
||
fail(409, "invalid_native_audio", "H3原生视频必须含有立体声音轨")
|
||
if (
|
||
track["width"] != resolved["parameters"]["width"]
|
||
or track["height"] != resolved["parameters"]["height"]
|
||
):
|
||
fail(409, "invalid_output", "原生视频实际尺寸与冻结配置不匹配")
|
||
audios = [a for a in candidates if a.kind == "audio"]
|
||
if len(audios) != 1 or not await verified_output(audios[0], settings):
|
||
fail(409, "missing_native_audio", "H3原生视频必须同时归档完整PCM WAV")
|
||
audio = audios[0]
|
||
count, rate, channels, width = _wav_info(audio, settings)
|
||
if (rate, channels, width) != (32000, 2, 2) or abs(
|
||
count / 32000 - expected / 24
|
||
) > 0.01251:
|
||
fail(409, "invalid_native_audio", "H3原生侧车必须是完整且等长的32k立体声PCM WAV")
|
||
frame = run.result_manifest["bindings"]["frame:" + r["unit_id"]]
|
||
result["context_hash"] = _video_context(r["native_context"], frame["sha256"])
|
||
result["native_source_audio_asset_id"] = audio.id
|
||
result["provenance"] = dict(
|
||
native_av_policy=POLICY,
|
||
native_source_audio_asset_id=audio.id,
|
||
native_source_audio_sha256=audio.sha256,
|
||
)
|
||
await _add_ref(session, run, audio)
|
||
elif kind == "audio":
|
||
count, rate, channels, width = _wav_info(asset, settings)
|
||
meta = job.result_json or {}
|
||
if (
|
||
rate != 48000
|
||
or width != 2
|
||
or channels != 2
|
||
or count < 1
|
||
or type(meta.get("sample_count")) is not int
|
||
or meta["sample_count"] != count
|
||
or meta.get("sample_rate") != 48000
|
||
or "channels" in meta
|
||
and meta["channels"] != channels
|
||
):
|
||
fail(409, "invalid_output", "原声48k音频实测样本数与回执不符")
|
||
result.update(
|
||
sample_count=count,
|
||
sample_rate=rate,
|
||
duration_seconds=count / rate,
|
||
duration_frames=(count + 1999) // 2000,
|
||
)
|
||
if step.kind == "audio.dialogue.extract":
|
||
if (
|
||
meta.get("audio_policy") != POLICY
|
||
or type(meta.get("audio_offset_samples")) is not int
|
||
or meta["audio_offset_samples"] < 0
|
||
):
|
||
fail(409, "invalid_output", "缺少原声音轨时间原点回执")
|
||
if (
|
||
abs(
|
||
count
|
||
+ meta["audio_offset_samples"]
|
||
- resolved["parameters"]["duration_frames"] * 2000
|
||
)
|
||
> 600
|
||
):
|
||
fail(409, "invalid_output", "原声音轨未完整覆盖原生镜头")
|
||
result["provenance"] = dict(
|
||
native_av_policy=POLICY,
|
||
audio_offset_samples=meta["audio_offset_samples"],
|
||
source_audio_asset_id=resolved["input"]["audio_asset_id"],
|
||
)
|
||
result["context_hash"] = digest(
|
||
dict(
|
||
video_sha=run.result_manifest["bindings"]["video:" + r["unit_id"]]["sha256"],
|
||
policy=POLICY,
|
||
)
|
||
)
|
||
if step.kind == "audio.mix":
|
||
if count != resolved["input"]["total_frames"] * 2000:
|
||
fail(409, "invalid_output", "整片混音没有保持精确样本数")
|
||
result["track"] = dict(
|
||
asset_id=asset.id,
|
||
source_start_sample=0,
|
||
source_end_sample=count,
|
||
offset_sample=0,
|
||
sample_rate=48000,
|
||
short_policy="silence",
|
||
)
|
||
elif kind == "json":
|
||
result["report"] = _read_report(asset, settings)
|
||
if step.kind == "audio.dialogue.inspect":
|
||
result["context_hash"] = _audio_review_context(
|
||
resolved["input_sha256"][resolved["input"]["audio_asset_id"]],
|
||
resolved["input"]["expected_text"],
|
||
resolved["input"]["speaker_id"],
|
||
)
|
||
else:
|
||
expected = resolved["input"]["expected"]
|
||
if not _valid_review_sampling(
|
||
result["report"], expected["source_start_frame"], expected["source_end_frame"]
|
||
):
|
||
fail(409, "invalid_output", "原生画面审核缺少当前采样策略及完整帧序列证据,必须重新审核")
|
||
result["provenance"] = dict(
|
||
video_sha256=resolved["input_sha256"][resolved["input"]["video_asset_id"]]
|
||
)
|
||
result["context_hash"] = _review_context(
|
||
resolved["input_sha256"][resolved["input"]["video_asset_id"]],
|
||
{
|
||
aid: resolved["input_sha256"][aid]
|
||
for aid in resolved["input"].get("reference_asset_ids", [])
|
||
},
|
||
resolved["input"]["expected"],
|
||
)
|
||
m = deepcopy(run.result_manifest)
|
||
if r.get("binding_key"):
|
||
m["bindings"][r["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 == "video.compose":
|
||
run.current_output_asset_id = asset.id
|