2067 lines
89 KiB
Python
2067 lines
89 KiB
Python
|
|
"""通过真实数据库/媒体文件检查对白准备、物化、重启和独立 CAS。"""
|
|||
|
|
|
|||
|
|
from copy import deepcopy
|
|||
|
|
import hashlib
|
|||
|
|
import json
|
|||
|
|
import io
|
|||
|
|
import os
|
|||
|
|
from pathlib import Path
|
|||
|
|
import shutil
|
|||
|
|
import subprocess
|
|||
|
|
import wave
|
|||
|
|
from uuid import uuid4
|
|||
|
|
|
|||
|
|
from PIL import Image
|
|||
|
|
from sqlalchemy import select
|
|||
|
|
from test_audio_timeline_v2 import provider
|
|||
|
|
import pytest
|
|||
|
|
|
|||
|
|
from app.adapters.provider.dialogue_gpu import MOUTH_BLEND_POLICY
|
|||
|
|
from app.models import Asset, Job, User, WorkflowDraft, WorkflowRun, WorkflowStep
|
|||
|
|
from app.services.dialogue import apply_pending_result
|
|||
|
|
from app.services.snapshots import snapshot_run
|
|||
|
|
from app.services.orchestration.workflow_engine import advance_run
|
|||
|
|
from test_dialogue_engine import enable_historical as enable
|
|||
|
|
|
|||
|
|
U, V, B, CAST, TITLE = (f"{i:032x}" for i in range(20, 25))
|
|||
|
|
COUNTS = {U: 101000, V: 34000}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.fixture(autouse=True)
|
|||
|
|
def frozen_legacy_admission(monkeypatch):
|
|||
|
|
"""只在历史图回归中模拟旧接纳边界;公共新建仍由原生专用测试验证。"""
|
|||
|
|
from app.services.orchestration import dialogue_engine
|
|||
|
|
|
|||
|
|
async def admit_history(session, draft, manifest, body, settings, **kwargs):
|
|||
|
|
assert "generation" not in manifest["spec"]["dialogue"], "历史夹具不能替代原生生产入口"
|
|||
|
|
return await dialogue_engine._start_legacy_editor_run(
|
|||
|
|
session, draft, manifest, body, settings, **kwargs
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 保留真实 HTTP 鉴权、CAS、幂等和资源引用,仅冻结历史版本曾接纳的执行图。
|
|||
|
|
monkeypatch.setattr(dialogue_engine, "start_editor_run", admit_history)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def wav(count):
|
|||
|
|
buffer = io.BytesIO()
|
|||
|
|
with wave.open(buffer, "wb") as track:
|
|||
|
|
track.setparams((1, 2, 48000, count, "NONE", ""))
|
|||
|
|
track.writeframes(
|
|||
|
|
(b"\x10\x00" * 120 + b"\xf0\xff" * 120) * (count // 240) + b"\x10\x00" * (count % 240)
|
|||
|
|
)
|
|||
|
|
return buffer.getvalue()
|
|||
|
|
|
|||
|
|
|
|||
|
|
def configure_media_tools(settings):
|
|||
|
|
for key in ("ffmpeg", "ffprobe"):
|
|||
|
|
binary = os.getenv(key.upper() + "_BIN") or shutil.which(key)
|
|||
|
|
if not binary:
|
|||
|
|
pytest.skip(f"{key} unavailable")
|
|||
|
|
setattr(settings, key + "_bin", binary)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def motion(settings, tmp_path):
|
|||
|
|
configure_media_tools(settings)
|
|||
|
|
path = tmp_path / "testsrc.mp4"
|
|||
|
|
subprocess.run(
|
|||
|
|
[
|
|||
|
|
settings.ffmpeg_bin,
|
|||
|
|
"-v",
|
|||
|
|
"error",
|
|||
|
|
"-y",
|
|||
|
|
"-f",
|
|||
|
|
"lavfi",
|
|||
|
|
"-i",
|
|||
|
|
"testsrc2=size=128x128:rate=24:duration=2",
|
|||
|
|
"-an",
|
|||
|
|
"-c:v",
|
|||
|
|
"libx264",
|
|||
|
|
"-pix_fmt",
|
|||
|
|
"yuv420p",
|
|||
|
|
str(path),
|
|||
|
|
],
|
|||
|
|
check=True,
|
|||
|
|
)
|
|||
|
|
return path.read_bytes()
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def asset(session, system, owner, kind, data, duration=None, job=None):
|
|||
|
|
suffix, mime = {
|
|||
|
|
"audio": ("wav", "audio/wav"),
|
|||
|
|
"video": ("mp4", "video/mp4"),
|
|||
|
|
"json": ("json", "application/json"),
|
|||
|
|
"image": ("png", "image/png"),
|
|||
|
|
}[kind]
|
|||
|
|
key = f"fixtures/{uuid4().hex}.{suffix}"
|
|||
|
|
path = system.settings.asset_root / key
|
|||
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|||
|
|
path.write_bytes(data)
|
|||
|
|
if job:
|
|||
|
|
job.upstream_id = "simulated-" + job.id
|
|||
|
|
row = Asset(
|
|||
|
|
origin="generated" if job else "upload",
|
|||
|
|
source_upstream_id=job.upstream_id if job else None,
|
|||
|
|
owner_id=owner,
|
|||
|
|
name="验证素材." + suffix,
|
|||
|
|
kind=kind,
|
|||
|
|
mime_type=mime,
|
|||
|
|
storage_key=key,
|
|||
|
|
sha256=hashlib.sha256(data).hexdigest(),
|
|||
|
|
size_bytes=len(data),
|
|||
|
|
duration_seconds=duration,
|
|||
|
|
width=128 if kind == "video" else None,
|
|||
|
|
height=128 if kind == "video" else None,
|
|||
|
|
source_job_id=job.id if job else None,
|
|||
|
|
source_output_index=0 if job else None,
|
|||
|
|
ready=True,
|
|||
|
|
)
|
|||
|
|
session.add(row)
|
|||
|
|
await session.flush()
|
|||
|
|
return row
|
|||
|
|
|
|||
|
|
|
|||
|
|
def dialogue_capabilities(system, silence_policy):
|
|||
|
|
from app.adapters.provider.dialogue_gpu import KEYS, REVISIONS, profile
|
|||
|
|
|
|||
|
|
async def capabilities():
|
|||
|
|
return {
|
|||
|
|
"dialogue": {
|
|||
|
|
KEYS[task]: dict(
|
|||
|
|
available=True,
|
|||
|
|
profile=profile(task),
|
|||
|
|
adapter_contract_version="dialogue-v1",
|
|||
|
|
speech_silence_policy=silence_policy,
|
|||
|
|
mouth_blend_policy=MOUTH_BLEND_POLICY,
|
|||
|
|
audio_context_shift_policy="bounded-feature-shift-v1",
|
|||
|
|
content_review_policy="whisper-sensevoice-exact-v1",
|
|||
|
|
task_type=task,
|
|||
|
|
decision="pass",
|
|||
|
|
report_sha256="b" * 64,
|
|||
|
|
revision=revision,
|
|||
|
|
max_people=1,
|
|||
|
|
)
|
|||
|
|
for task, revision in REVISIONS.items()
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
system.provider.upstream_capabilities = capabilities
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def configure(system, *, video=None, repair_limits=None, silence_policy="source-rest-v2"):
|
|||
|
|
settings = system.settings
|
|||
|
|
settings.dialogue_speech_enabled = True
|
|||
|
|
settings.tts_base_url = "http://test-tts/v1"
|
|||
|
|
settings.dialogue_lipsync_enabled = True
|
|||
|
|
settings.dialogue_quality_certified = True
|
|||
|
|
dialogue_capabilities(system, silence_policy)
|
|||
|
|
draft_id, result = await enable(system)
|
|||
|
|
m = result["manifest"]
|
|||
|
|
if repair_limits:
|
|||
|
|
m["production"].update(repair_limits)
|
|||
|
|
(seq,) = m["spec"]["dialogue"]["sequences"]
|
|||
|
|
(speaker,) = m["spec"]["dialogue"]["speakers"]
|
|||
|
|
m["spec"]["dialogue"]["utterances"] = [
|
|||
|
|
dict(id=u, speaker_id=speaker["id"], text=t)
|
|||
|
|
for u, t in [(U, "我会留下。"), (V, "直到天亮。")]
|
|||
|
|
]
|
|||
|
|
(first,) = m["spec"]["shots"]
|
|||
|
|
second = deepcopy(first)
|
|||
|
|
second.update(id=B, visual_prompt="镜头转向候车厅")
|
|||
|
|
second["cast"][0]["id"] = CAST
|
|||
|
|
first["edit"]["duration_frames"] = second["edit"]["duration_frames"] = 48
|
|||
|
|
m["spec"]["shots"].append(second)
|
|||
|
|
m["shot_ids"].append(B)
|
|||
|
|
seq.update(shot_ids=m["shot_ids"].copy(), utterance_ids=[U, V], timing_mode="fixed")
|
|||
|
|
m["captions"] = dict(
|
|||
|
|
mode="script",
|
|||
|
|
cues=[
|
|||
|
|
dict(
|
|||
|
|
id=TITLE,
|
|||
|
|
anchor="absolute",
|
|||
|
|
start_frame=0,
|
|||
|
|
end_frame=4,
|
|||
|
|
text="夜半车站",
|
|||
|
|
timing_override=True,
|
|||
|
|
text_override=True,
|
|||
|
|
)
|
|||
|
|
],
|
|||
|
|
)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
owner = (await s.get(WorkflowDraft, draft_id)).owner_id
|
|||
|
|
ref = await asset(s, system, owner, "audio", wav(60000), 1.25)
|
|||
|
|
speaker["voice"]["reference_asset_id"] = ref.id
|
|||
|
|
await s.commit()
|
|||
|
|
if video is not None:
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
owner = (await s.get(WorkflowDraft, draft_id)).owner_id
|
|||
|
|
picture = io.BytesIO()
|
|||
|
|
Image.new("RGB", (128, 128), "blue").save(picture, format="PNG")
|
|||
|
|
reference = await asset(s, system, owner, "image", picture.getvalue())
|
|||
|
|
m["spec"]["entities"][0]["reference_asset_ids"] = [reference.id]
|
|||
|
|
src = await asset(s, system, owner, "video", video, 2)
|
|||
|
|
for sid in m["shot_ids"]:
|
|||
|
|
m["bindings"]["video:" + sid] = dict(
|
|||
|
|
asset_id=src.id, sha256=src.sha256, kind="video", source="manual", locked=True
|
|||
|
|
)
|
|||
|
|
await s.commit()
|
|||
|
|
saved = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/save",
|
|||
|
|
json=dict(manifest=m, expected_version=result["version"]),
|
|||
|
|
headers={"Idempotency-Key": "dialogue-test-save"},
|
|||
|
|
)
|
|||
|
|
assert saved.status_code == 200, saved.text
|
|||
|
|
return draft_id, saved.json()
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def start(system, draft_id, version, preview=False, key="run"):
|
|||
|
|
body = dict(
|
|||
|
|
expected_version=version,
|
|||
|
|
output_goal="media" if preview else "film",
|
|||
|
|
targets=["speech:" + U] if preview else [],
|
|||
|
|
execution_mode="batch",
|
|||
|
|
)
|
|||
|
|
url = f"/api/editors/{draft_id}"
|
|||
|
|
plan = await system.client.post(url + "/plan", json=body)
|
|||
|
|
assert plan.status_code == 200 and not plan.json()["issues"], plan.text
|
|||
|
|
body["expected_plan_hash"] = plan.json()["plan_hash"]
|
|||
|
|
launched = await system.client.post(url + "/runs", json=body, headers={"Idempotency-Key": key})
|
|||
|
|
assert launched.status_code == 202, launched.text
|
|||
|
|
return launched.json()["run"]["id"]
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def steps(s, rid):
|
|||
|
|
return (await s.scalars(select(WorkflowStep).where(WorkflowStep.run_id == rid))).all()
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def tick(system, rid):
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
await advance_run(s, rid, system.settings)
|
|||
|
|
await s.commit()
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def record_audio(system, rid, verdict="pass"):
|
|||
|
|
"""模拟供应商返回的音频任务,仅接受编排器本轮真实创建的选中 Job。"""
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
for step in await steps(s, rid):
|
|||
|
|
if (
|
|||
|
|
step.kind not in {"audio.speech", "audio.normalize", "audio.dialogue.inspect"}
|
|||
|
|
or not step.selected_job_id
|
|||
|
|
):
|
|||
|
|
continue
|
|||
|
|
job = await s.get(Job, step.selected_job_id)
|
|||
|
|
if job.state == "succeeded":
|
|||
|
|
continue
|
|||
|
|
if step.kind == "audio.dialogue.inspect":
|
|||
|
|
a = await s.get(Asset, job.input_json["audio_asset_id"])
|
|||
|
|
ref = await s.get(Asset, job.input_json["reference_asset_id"])
|
|||
|
|
report = dict(
|
|||
|
|
decision="pass"
|
|||
|
|
if verdict
|
|||
|
|
in {"wrong_range", "old_pass", "bad_revision", "primary_pass", "stale_asset"}
|
|||
|
|
else verdict,
|
|||
|
|
source_start_sample=1
|
|||
|
|
if verdict == "wrong_range"
|
|||
|
|
else step.resolved_input_json["parameters"].get("source_start_sample", 0),
|
|||
|
|
source_end_sample=step.resolved_input_json["parameters"].get(
|
|||
|
|
"source_end_sample"
|
|||
|
|
)
|
|||
|
|
or COUNTS[step.recipe_json["unit_id"]],
|
|||
|
|
speaker_id=job.input_json["speaker_id"],
|
|||
|
|
expected_text=job.input_json["expected_text"],
|
|||
|
|
reference_sha256=ref.sha256,
|
|||
|
|
audio_sha256=a.sha256,
|
|||
|
|
)
|
|||
|
|
if verdict == "old_reject":
|
|||
|
|
report["decision"] = "reject"
|
|||
|
|
report["content_error_rate"] = 0.0 if verdict != "old_reject" else 0.5
|
|||
|
|
if verdict not in {"old_pass", "old_reject"}:
|
|||
|
|
from app.adapters.provider import dialogue_gpu as gpu
|
|||
|
|
|
|||
|
|
primary = verdict == "primary_pass"
|
|||
|
|
report.update(
|
|||
|
|
content_review_policy=gpu.CONTENT_REVIEW_POLICY,
|
|||
|
|
content_error_rate=0.0,
|
|||
|
|
primary_content_error_rate=0.0 if primary else 0.1,
|
|||
|
|
content_decision_source="whisper" if primary else "sensevoice",
|
|||
|
|
secondary_status="not_requested" if primary else "completed",
|
|||
|
|
secondary_transcript=None if primary else job.input_json["expected_text"],
|
|||
|
|
secondary_content_error_rate=None if primary else 0.0,
|
|||
|
|
secondary_asr_revision=None if primary else gpu.SENSEVOICE_REVISION,
|
|||
|
|
secondary_runtime_revision=None if primary else gpu.SENSEVOICE_RUNTIME,
|
|||
|
|
)
|
|||
|
|
if verdict == "bad_revision":
|
|||
|
|
report["secondary_asr_revision"] = "a" * 40
|
|||
|
|
archived = dict(report)
|
|||
|
|
if verdict == "stale_asset":
|
|||
|
|
archived.pop("content_review_policy")
|
|||
|
|
await asset(s, system, job.owner_id, "json", json.dumps(archived).encode(), job=job)
|
|||
|
|
job.state, job.phase, job.result_json = "succeeded", "done", report
|
|||
|
|
continue
|
|||
|
|
n = COUNTS[step.recipe_json["unit_id"]]
|
|||
|
|
data = wav(n)
|
|||
|
|
if job.input_json.get("prompt") == "再等一刻。":
|
|||
|
|
data = data[:44] + bytes(b ^ 1 for b in data[44:])
|
|||
|
|
if step.kind == "audio.normalize":
|
|||
|
|
source = await s.get(Asset, job.input_json["asset_id"])
|
|||
|
|
data = (system.settings.asset_root / source.storage_key).read_bytes()
|
|||
|
|
output = await asset(s, system, job.owner_id, "audio", data, n / 48000, job)
|
|||
|
|
job.state, job.phase = "succeeded", "done"
|
|||
|
|
job.result_json = dict(
|
|||
|
|
sample_count=n, sample_rate=48000, duration_seconds=n / 48000, asset_id=output.id
|
|||
|
|
)
|
|||
|
|
await s.commit()
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def prepare_run(system, rid):
|
|||
|
|
for _ in range(12):
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
if r.prepared_plan:
|
|||
|
|
assert r.prepared_plan["production_materialized"]
|
|||
|
|
return
|
|||
|
|
assert r.state not in {"succeeded", "failed", "blocked"}, r.error_json
|
|||
|
|
assert {x.kind for x in await steps(s, rid)} <= {
|
|||
|
|
"audio.speech",
|
|||
|
|
"audio.normalize",
|
|||
|
|
"audio.dialogue.inspect",
|
|||
|
|
}
|
|||
|
|
await tick(system, rid)
|
|||
|
|
await record_audio(system, rid)
|
|||
|
|
pytest.fail("准备图没有在已完成语音和归一化后物化")
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("conflict", [False, True])
|
|||
|
|
async def test_preview_materializes_empty_production_and_applies_once(system, conflict):
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
rid = await start(system, draft_id, saved["version"], preview=True)
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
assert run.state == "succeeded" and run.apply_state == "pending"
|
|||
|
|
assert not run.prepared_plan["steps"]
|
|||
|
|
assert {x.kind for x in await steps(s, rid)} == {"audio.normalize", "audio.speech"}
|
|||
|
|
assert {"speech:" + U, "normalized_speech:" + U} <= run.result_manifest["bindings"].keys()
|
|||
|
|
assert "speech:" + V not in run.result_manifest["bindings"]
|
|||
|
|
assert run.result_manifest["spec"] == saved["manifest"]["spec"]
|
|||
|
|
if conflict:
|
|||
|
|
draft = await s.get(WorkflowDraft, draft_id)
|
|||
|
|
draft.version += 1
|
|||
|
|
await s.commit()
|
|||
|
|
assert (await apply_pending_result(db, rid, system.settings)) is (not conflict)
|
|||
|
|
assert not await apply_pending_result(db, rid, system.settings)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
assert (await s.get(WorkflowRun, rid)).apply_state == (
|
|||
|
|
"conflict" if conflict else "applied"
|
|||
|
|
)
|
|||
|
|
assert (await s.get(WorkflowDraft, draft_id)).version == saved["version"] + 1
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_cancel_fences_late_speech_and_never_applies(system):
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
rid = await start(system, draft_id, saved["version"], preview=True)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
assert any(st.selected_job_id for st in await steps(s, rid))
|
|||
|
|
r.desired_state = "cancel"
|
|||
|
|
await s.commit()
|
|||
|
|
await record_audio(system, rid)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
assert not await apply_pending_result(db, rid, system.settings)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
assert run.state == "cancelled" and not run.result_manifest["bindings"]
|
|||
|
|
assert (await s.get(WorkflowDraft, draft_id)).version == saved["version"]
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_cross_owner_dialogue_recording_rejected_before_planning(system, other_client):
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
owner = await s.scalar(select(User.id).where(User.username == "alice"))
|
|||
|
|
private = await asset(s, system, owner, "audio", wav(4000), 4000 / 48000)
|
|||
|
|
await s.commit()
|
|||
|
|
m = deepcopy(saved["manifest"])
|
|||
|
|
m["spec"]["dialogue"]["utterances"][0].update(source="asset", asset_id=private.id)
|
|||
|
|
denied = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/save",
|
|||
|
|
json=dict(expected_version=saved["version"], manifest=m),
|
|||
|
|
headers={"Idempotency-Key": "foreign-wav"},
|
|||
|
|
)
|
|||
|
|
assert denied.status_code == 404
|
|||
|
|
assert (await system.client.get(f"/api/editors/{draft_id}")).json()["version"] == saved[
|
|||
|
|
"version"
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def finish_media_jobs(
|
|||
|
|
system,
|
|||
|
|
rid,
|
|||
|
|
provider,
|
|||
|
|
tmp_path,
|
|||
|
|
verdict,
|
|||
|
|
*,
|
|||
|
|
lip_policy=MOUTH_BLEND_POLICY,
|
|||
|
|
qa_policy=MOUTH_BLEND_POLICY,
|
|||
|
|
wrong_sha=None,
|
|||
|
|
shift_receipt="match",
|
|||
|
|
silence_reason=None,
|
|||
|
|
wrong_silence_receipt=None,
|
|||
|
|
):
|
|||
|
|
"""执行本地选段/混音/合成;人脸与口型模型只在作业结果边界替换。"""
|
|||
|
|
from app.adapters.provider.audio_timeline import mix
|
|||
|
|
from app.adapters.provider.composition import _compose
|
|||
|
|
from app.adapters.provider.dialogue_media import run_cpu
|
|||
|
|
|
|||
|
|
provider.settings = system.settings
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
files = {
|
|||
|
|
a.id: system.settings.asset_root / a.storage_key
|
|||
|
|
for a in (await s.scalars(select(Asset).where(Asset.owner_id == r.owner_id))).all()
|
|||
|
|
}
|
|||
|
|
for st in await steps(s, rid):
|
|||
|
|
if not st.selected_job_id:
|
|||
|
|
continue
|
|||
|
|
j = await s.get(Job, st.selected_job_id)
|
|||
|
|
if j.state == "succeeded":
|
|||
|
|
continue
|
|||
|
|
work = tmp_path / j.id
|
|||
|
|
work.mkdir(exist_ok=True)
|
|||
|
|
inputs, params = j.input_json, j.parameters
|
|||
|
|
if j.task_type in {
|
|||
|
|
"audio.mix",
|
|||
|
|
"video.compose",
|
|||
|
|
"video.dialogue.select",
|
|||
|
|
"audio.dialogue.extract",
|
|||
|
|
}:
|
|||
|
|
if j.task_type == "audio.mix":
|
|||
|
|
output = await mix(provider, inputs, params, files, work)
|
|||
|
|
kind = "audio"
|
|||
|
|
elif j.task_type == "video.compose":
|
|||
|
|
output = await _compose(provider, inputs, params, files, work)
|
|||
|
|
kind = "video"
|
|||
|
|
else:
|
|||
|
|
output = await run_cpu(provider, j.task_type, inputs, params, files, work)
|
|||
|
|
kind = "audio" if j.task_type == "audio.dialogue.extract" else "video"
|
|||
|
|
data = output.outputs[0].read_bytes()
|
|||
|
|
result = output.result
|
|||
|
|
duration = (
|
|||
|
|
result.get("sample_count", 0) / 48000
|
|||
|
|
if kind == "audio"
|
|||
|
|
else (4 if j.task_type == "video.compose" else 2)
|
|||
|
|
)
|
|||
|
|
elif j.task_type == "video.lipsync":
|
|||
|
|
kind = "video"
|
|||
|
|
data = files[inputs["video_asset_id"]].read_bytes()
|
|||
|
|
duration = 2
|
|||
|
|
result = {"num_frames": 48, "fps": 24}
|
|||
|
|
if params.get("speech_silence_policy") == "source-rest-v2":
|
|||
|
|
result["speech_silence_policy"] = (
|
|||
|
|
"neutral-rest-v1" if wrong_silence_receipt == "render" else "source-rest-v2"
|
|||
|
|
)
|
|||
|
|
result["base_sha256"] = hashlib.sha256(data).hexdigest()
|
|||
|
|
if "audio_context_shift_frames" in params or shift_receipt == "unexpected":
|
|||
|
|
if shift_receipt != "missing":
|
|||
|
|
result["audio_context_shift_policy"] = "bounded-feature-shift-v1"
|
|||
|
|
result["audio_context_shift_frames"] = (
|
|||
|
|
1
|
|||
|
|
if shift_receipt == "wrong"
|
|||
|
|
else params.get("audio_context_shift_frames", 0)
|
|||
|
|
)
|
|||
|
|
if lip_policy is not None:
|
|||
|
|
result["mouth_blend_policy"] = lip_policy
|
|||
|
|
result["synced_sha256"] = (
|
|||
|
|
"0" * 64 if wrong_sha == "render" else hashlib.sha256(data).hexdigest()
|
|||
|
|
)
|
|||
|
|
elif j.task_type in {
|
|||
|
|
"video.dialogue.analyze",
|
|||
|
|
"video.dialogue.inspect",
|
|||
|
|
"video.dialogue.review",
|
|||
|
|
}:
|
|||
|
|
kind = "json"
|
|||
|
|
result = {
|
|||
|
|
"decision": verdict if j.task_type == "video.dialogue.inspect" else "pass"
|
|||
|
|
}
|
|||
|
|
if j.task_type == "video.dialogue.review" and "source_visual_policy" in inputs["expected"]:
|
|||
|
|
result["source_visual_policy"] = inputs["expected"]["source_visual_policy"]
|
|||
|
|
if j.task_type == "video.dialogue.inspect":
|
|||
|
|
if verdict == "correct_offset":
|
|||
|
|
result["decision"] = "pass"
|
|||
|
|
if st.explicit_attempt == 1:
|
|||
|
|
speaker = inputs["speech_tracks"][0]["speaker_id"]
|
|||
|
|
offset = 120 if st.step_key.endswith("1") else -120
|
|||
|
|
result.update(shift_evidence(speaker, offset))
|
|||
|
|
if qa_policy is not None:
|
|||
|
|
result["mouth_blend_policy"] = qa_policy
|
|||
|
|
result["synced_sha256"] = (
|
|||
|
|
"0" * 64
|
|||
|
|
if wrong_sha == "inspect"
|
|||
|
|
else hashlib.sha256(
|
|||
|
|
files[inputs["video_asset_id"]].read_bytes()
|
|||
|
|
).hexdigest()
|
|||
|
|
)
|
|||
|
|
if verdict == "indeterminate":
|
|||
|
|
result["reasons"] = ["low_sync_confidence", "insufficient_voiced_evidence"]
|
|||
|
|
elif verdict == "reject":
|
|||
|
|
result["reasons"] = ["identity_changed"]
|
|||
|
|
if verdict == "legacy_pass":
|
|||
|
|
result["decision"] = "pass"
|
|||
|
|
else:
|
|||
|
|
from app.adapters.provider.dialogue_gpu import SILENCE_POLICY
|
|||
|
|
|
|||
|
|
policy = params.get("speech_silence_policy", SILENCE_POLICY)
|
|||
|
|
result["speech_silence_policy"] = (
|
|||
|
|
"neutral-rest-v1" if wrong_silence_receipt == "inspect" else policy
|
|||
|
|
)
|
|||
|
|
if policy == "source-rest-v2":
|
|||
|
|
result["base_sha256"] = hashlib.sha256(
|
|||
|
|
files[inputs["base_video_asset_id"]].read_bytes()
|
|||
|
|
).hexdigest()
|
|||
|
|
source = "pass"
|
|||
|
|
if silence_reason and st.step_key == "syncqa_0001":
|
|||
|
|
source = (
|
|||
|
|
"reject" if silence_reason == "source_speaking_during_silence"
|
|||
|
|
else "indeterminate"
|
|||
|
|
)
|
|||
|
|
result.update(decision=source, reasons=[silence_reason])
|
|||
|
|
result["source_rest_checks"] = [
|
|||
|
|
dict(speaker_id=track["speaker_id"], decision=source, silent_frames=12,
|
|||
|
|
windows=[dict(start_frame=35, end_frame=47, decision=source)])
|
|||
|
|
for track in inputs["speech_tracks"]
|
|||
|
|
]
|
|||
|
|
result["rest_checks"] = [
|
|||
|
|
dict(speaker_id=track["speaker_id"], decision="pass", silent_frames=12,
|
|||
|
|
windows=[dict(start_frame=35, end_frame=47, decision="pass")])
|
|||
|
|
for track in inputs["speech_tracks"]
|
|||
|
|
]
|
|||
|
|
result["silent_mouth_source_checks"] = [
|
|||
|
|
dict(speaker_id=track["speaker_id"], decision="pass", silent_frames=12,
|
|||
|
|
measured_frames=12, block_count=42, max_block_mae=3.,
|
|||
|
|
max_block_severe_fraction=0.) for track in inputs["speech_tracks"]
|
|||
|
|
]
|
|||
|
|
if wrong_silence_receipt == "missing_mouth_checks":
|
|||
|
|
result.pop("silent_mouth_source_checks")
|
|||
|
|
if wrong_silence_receipt == "missing_source_checks":
|
|||
|
|
result.pop("source_rest_checks")
|
|||
|
|
if j.task_type == "video.dialogue.analyze":
|
|||
|
|
result["tracks"] = [
|
|||
|
|
dict(speaker_id=sid, track_id="a" * 32) for sid in params["speaker_ids"]
|
|||
|
|
]
|
|||
|
|
data = json.dumps(result).encode()
|
|||
|
|
duration = None
|
|||
|
|
else:
|
|||
|
|
pytest.fail(f"意外重生成底片或配音: {j.task_type}")
|
|||
|
|
await asset(s, system, r.owner_id, kind, data, duration, j)
|
|||
|
|
j.result_json = result
|
|||
|
|
j.state, j.phase = "succeeded", "done"
|
|||
|
|
await s.commit()
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
"verdict", ["pass", "indeterminate", "legacy_pass", "reject", "correct_offset"]
|
|||
|
|
)
|
|||
|
|
async def test_film_across_cuts_quality_gate_and_bgm_reuse(system, provider, tmp_path, verdict):
|
|||
|
|
clip = motion(system.settings, tmp_path)
|
|||
|
|
draft_id, saved = await configure(system, video=clip)
|
|||
|
|
rid = await start(system, draft_id, saved["version"])
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
assert r.state != "succeeded"
|
|||
|
|
keys = {x.step_key for x in await steps(s, rid)}
|
|||
|
|
assert len([p for p in r.prepared_plan["placements"] if p["utterance_id"] == U]) == 2
|
|||
|
|
frozen_hash = r.prepared_plan["prepared_hash"]
|
|||
|
|
for _ in range(23):
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, verdict)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
st = await steps(s, rid)
|
|||
|
|
assert {x.step_key for x in st} == keys and len(st) == len(keys)
|
|||
|
|
assert r.prepared_plan["prepared_hash"] == frozen_hash
|
|||
|
|
if verdict == "correct_offset":
|
|||
|
|
q = (await snapshot_run(s, r.owner_id, rid))["run"]["quality"]
|
|||
|
|
assert q["total_repairs"] == sum(
|
|||
|
|
v["state"] == "repair_requested" for v in q["variants"]
|
|||
|
|
)
|
|||
|
|
if r.state == "blocked":
|
|||
|
|
assert verdict not in {"pass", "correct_offset"}, r.error_json
|
|||
|
|
code = "reject" if verdict == "reject" else "indeterminate"
|
|||
|
|
assert r.error_json["code"] == "dialogue_quality_" + code, r.error_json
|
|||
|
|
if verdict != "legacy_pass":
|
|||
|
|
reasons = (
|
|||
|
|
["identity_changed"]
|
|||
|
|
if verdict == "reject"
|
|||
|
|
else ["low_sync_confidence", "insufficient_voiced_evidence"]
|
|||
|
|
)
|
|||
|
|
assert r.error_json["reasons"] == reasons
|
|||
|
|
ordinal = r.result_manifest["shot_ids"].index(r.error_json["shot_id"]) + 1
|
|||
|
|
detail = (
|
|||
|
|
"人物身份一致性未通过"
|
|||
|
|
if verdict == "reject"
|
|||
|
|
else "口型同步置信度不足;有效发声证据不足"
|
|||
|
|
)
|
|||
|
|
assert r.error_json["message"] == f"第{ordinal}镜口型质检:{detail}"
|
|||
|
|
else:
|
|||
|
|
assert "静音策略" in r.error_json["message"]
|
|||
|
|
summary = (await snapshot_run(s, r.owner_id, rid))["run"]["quality"]
|
|||
|
|
assert (summary["accepted_shots"], summary["total_shots"]) == (0, 2)
|
|||
|
|
assert not r.current_output_asset_id
|
|||
|
|
assert not any(k.startswith("synced_video:") for k in r.result_manifest["bindings"])
|
|||
|
|
assert (await s.get(WorkflowDraft, draft_id)).version == saved["version"]
|
|||
|
|
return
|
|||
|
|
if r.state == "succeeded":
|
|||
|
|
assert verdict in {"pass", "correct_offset"}
|
|||
|
|
break
|
|||
|
|
else:
|
|||
|
|
pytest.fail("生产图没有完成")
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
st = {x.step_key: x for x in await steps(s, rid)}
|
|||
|
|
rows = st["dialogue_mix"].resolved_input_json["input"]["segments"]
|
|||
|
|
assert [(x["segment_id"], x["offset_sample"], x["source_end_sample"]) for x in rows] == [
|
|||
|
|
(U, 9600, COUNTS[U]),
|
|||
|
|
(V, 9600 + COUNTS[U] + 9600, COUNTS[V]),
|
|||
|
|
]
|
|||
|
|
assert st["dialogue_mix"].result_json["sample_count"] == 192000
|
|||
|
|
cues = st["dialogue_captions"].result_json["cues"]
|
|||
|
|
assert [(c["text"], c["start_frame"], c["end_frame"]) for c in cues] == [
|
|||
|
|
("夜半车站", 0, 4),
|
|||
|
|
("我会留下。", 5, 55),
|
|||
|
|
("直到天亮。", 60, 77),
|
|||
|
|
]
|
|||
|
|
assert len([x for x in st.values() if x.kind == "video.lipsync"]) == 2
|
|||
|
|
if verdict == "correct_offset":
|
|||
|
|
for index, sid in enumerate(run.result_manifest["shot_ids"], 1):
|
|||
|
|
lip = st[f"lip_{index:04d}"]
|
|||
|
|
attempts = (
|
|||
|
|
await s.scalars(
|
|||
|
|
select(Job)
|
|||
|
|
.where(Job.run_id == rid, Job.step_key == lip.step_key)
|
|||
|
|
.order_by(Job.explicit_attempt)
|
|||
|
|
)
|
|||
|
|
).all()
|
|||
|
|
assert [j.parameters["audio_context_shift_frames"] for j in attempts] == [
|
|||
|
|
0,
|
|||
|
|
3 if index == 1 else -3,
|
|||
|
|
]
|
|||
|
|
assert attempts[0].parameters["seed"] == attempts[1].parameters["seed"]
|
|||
|
|
assert attempts[0].input_json == attempts[1].input_json
|
|||
|
|
qa = st[f"syncqa_{index:04d}"]
|
|||
|
|
assert "audio_context_shift_frames" not in qa.resolved_input_json["parameters"]
|
|||
|
|
accepted = run.result_manifest["bindings"]["video:" + sid]["provenance"]
|
|||
|
|
assert (
|
|||
|
|
accepted["audio_context_shift_frames"]
|
|||
|
|
== attempts[1].parameters["audio_context_shift_frames"]
|
|||
|
|
)
|
|||
|
|
assert (await snapshot_run(s, run.owner_id, rid))["run"]["quality"][
|
|||
|
|
"total_repairs"
|
|||
|
|
] == 2
|
|||
|
|
assert run.current_output_asset_id
|
|||
|
|
rendered = await s.get(Asset, run.current_output_asset_id)
|
|||
|
|
streams = json.loads(
|
|||
|
|
subprocess.check_output(
|
|||
|
|
[
|
|||
|
|
system.settings.ffprobe_bin,
|
|||
|
|
"-v",
|
|||
|
|
"error",
|
|||
|
|
"-show_streams",
|
|||
|
|
"-of",
|
|||
|
|
"json",
|
|||
|
|
str(system.settings.asset_root / rendered.storage_key),
|
|||
|
|
]
|
|||
|
|
)
|
|||
|
|
)["streams"]
|
|||
|
|
assert sorted(stream["codec_type"] for stream in streams) == ["audio", "video"]
|
|||
|
|
video = next(stream for stream in streams if stream["codec_type"] == "video")
|
|||
|
|
assert int(video["nb_frames"]) == 96 and video["avg_frame_rate"] == "24/1"
|
|||
|
|
audio = next(stream for stream in streams if stream["codec_type"] == "audio")
|
|||
|
|
assert abs(float(audio["duration"]) - 4) < 1 / 24
|
|||
|
|
assert await apply_pending_result(db, rid, system.settings)
|
|||
|
|
latest = (await system.client.get(f"/api/editors/{draft_id}")).json()
|
|||
|
|
async with db.session() as s:
|
|||
|
|
draft = await s.get(WorkflowDraft, draft_id)
|
|||
|
|
bgm = await asset(s, system, draft.owner_id, "audio", wav(48000), 1)
|
|||
|
|
await s.commit()
|
|||
|
|
m = latest["manifest"]
|
|||
|
|
m["captions"]["cues"][0].update(text="雨夜车站", text_override=True)
|
|||
|
|
m["audio"]["layers"] = [
|
|||
|
|
dict(
|
|||
|
|
id="f" * 32,
|
|||
|
|
role="bgm",
|
|||
|
|
anchor="absolute",
|
|||
|
|
asset_id=bgm.id,
|
|||
|
|
source_end_sample=48000,
|
|||
|
|
gain_db=-16,
|
|||
|
|
)
|
|||
|
|
]
|
|||
|
|
changed = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/save",
|
|||
|
|
json=dict(expected_version=latest["version"], manifest=m),
|
|||
|
|
headers={"Idempotency-Key": "change-bgm"},
|
|||
|
|
)
|
|||
|
|
assert changed.status_code == 200, changed.text
|
|||
|
|
second = await start(system, draft_id, changed.json()["version"], key="bgm-only")
|
|||
|
|
for _ in range(9):
|
|||
|
|
await tick(system, second)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, second)
|
|||
|
|
if r.prepared_plan:
|
|||
|
|
break
|
|||
|
|
for st in await steps(s, second):
|
|||
|
|
if st.kind == "audio.normalize" and st.selected_job_id:
|
|||
|
|
j = await s.get(Job, st.selected_job_id)
|
|||
|
|
if j.state != "succeeded":
|
|||
|
|
assert st.recipe_json["unit_id"] == bgm.id
|
|||
|
|
await asset(s, system, j.owner_id, "audio", wav(48000), 1, j)
|
|||
|
|
j.result_json = {"sample_count": 48000, "sample_rate": 48000}
|
|||
|
|
j.state, j.phase = "succeeded", "done"
|
|||
|
|
await s.commit()
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, second)
|
|||
|
|
assert r.prepared_plan, r.error_json
|
|||
|
|
production = r.prepared_plan["steps"]
|
|||
|
|
assert len([row for row in production if row["kind"] == "dialogue.accepted"]) == 2
|
|||
|
|
assert not any(row["kind"] in {"video.generate", "video.lipsync"} for row in production)
|
|||
|
|
for _ in range(8):
|
|||
|
|
await finish_media_jobs(system, second, provider, tmp_path, "pass")
|
|||
|
|
await tick(system, second)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, second)
|
|||
|
|
assert r.state not in {"failed", "blocked"}, r.error_json
|
|||
|
|
if r.state == "succeeded":
|
|||
|
|
break
|
|||
|
|
else:
|
|||
|
|
pytest.fail("仅更换配乐的运行未完成")
|
|||
|
|
async with db.session() as s:
|
|||
|
|
second_steps = {x.step_key: x for x in await steps(s, second)}
|
|||
|
|
rows = second_steps["dialogue_mix"].resolved_input_json["input"]["segments"]
|
|||
|
|
assert [row["role"] for row in rows] == ["narration", "narration", "bgm"]
|
|||
|
|
jobs = (await s.scalars(select(Job).where(Job.run_id == second))).all()
|
|||
|
|
assert {j.task_type for j in jobs} == {"audio.normalize", "audio.mix", "video.compose"}
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, second)
|
|||
|
|
summary = (await snapshot_run(s, r.owner_id, second))["run"]["quality"]
|
|||
|
|
assert (summary["accepted_shots"], summary["total_shots"]) == (2, 2)
|
|||
|
|
assert await apply_pending_result(db, second, system.settings)
|
|||
|
|
latest = (await system.client.get(f"/api/editors/{draft_id}")).json()
|
|||
|
|
changed = latest["manifest"]
|
|||
|
|
changed["audio"]["layers"] = []
|
|||
|
|
first_video = "video:" + changed["shot_ids"][0]
|
|||
|
|
changed["bindings"][first_video]["locked"] = True
|
|||
|
|
changed["spec"]["dialogue"]["utterances"][0]["text"] = "再等一刻。"
|
|||
|
|
body = dict(expected_version=latest["version"], manifest=changed)
|
|||
|
|
locked = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/save", json=body, headers={"Idempotency-Key": "lock-video"}
|
|||
|
|
)
|
|||
|
|
assert locked.status_code == 200, locked.text
|
|||
|
|
locked_plan = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/plan", json=dict(expected_version=locked.json()["version"])
|
|||
|
|
)
|
|||
|
|
assert any(i["code"] == "locked_dependency_changed" for i in locked_plan.json()["issues"])
|
|||
|
|
body["expected_version"] = locked.json()["version"]
|
|||
|
|
body["manifest"] = locked.json()["manifest"]
|
|||
|
|
body["manifest"]["bindings"][first_video]["locked"] = False
|
|||
|
|
unlocked = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/save", json=body, headers={"Idempotency-Key": "unlock-video"}
|
|||
|
|
)
|
|||
|
|
assert unlocked.status_code == 200, unlocked.text
|
|||
|
|
third = await start(system, draft_id, unlocked.json()["version"], key="new-line")
|
|||
|
|
await prepare_run(system, third)
|
|||
|
|
for _ in range(15):
|
|||
|
|
await finish_media_jobs(system, third, provider, tmp_path, "pass")
|
|||
|
|
await tick(system, third)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, third)
|
|||
|
|
assert r.state != "blocked", r.error_json
|
|||
|
|
if r.state == "succeeded":
|
|||
|
|
kinds = (await s.scalars(select(Job.task_type).where(Job.run_id == third))).all()
|
|||
|
|
assert "video.lipsync" in kinds and "video.dialogue.inspect" in kinds
|
|||
|
|
assert "video.dialogue.analyze" not in kinds and "video.generate" not in kinds
|
|||
|
|
break
|
|||
|
|
else:
|
|||
|
|
pytest.fail("重录台词后未通过质检")
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_direct_plan_refreshes_capabilities_and_fails_closed(system):
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
calls = []
|
|||
|
|
|
|||
|
|
async def uncertified():
|
|||
|
|
calls.append(True)
|
|||
|
|
return {"dialogue": {}}
|
|||
|
|
|
|||
|
|
system.provider.upstream_capabilities = uncertified
|
|||
|
|
response = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/plan",
|
|||
|
|
json=dict(expected_version=saved["version"], output_goal="film"),
|
|||
|
|
)
|
|||
|
|
assert response.status_code == 200
|
|||
|
|
assert calls and any(i["code"] == "capability_unavailable" for i in response.json()["issues"])
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_failed_preparation_never_materializes_or_publishes(system):
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
rid = await start(system, draft_id, saved["version"], preview=True)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
speech = next(st for st in await steps(s, rid) if st.kind == "audio.speech")
|
|||
|
|
job = await s.get(Job, speech.selected_job_id)
|
|||
|
|
job.state, job.phase = "failed", "done"
|
|||
|
|
job.error_json = {"code": "provider_failed"}
|
|||
|
|
await s.commit()
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
assert run.state in {"blocked", "failed"}
|
|||
|
|
assert not run.prepared_plan and not run.current_output_asset_id
|
|||
|
|
assert (await s.get(WorkflowDraft, draft_id)).version == saved["version"]
|
|||
|
|
assert not await apply_pending_result(db, rid, system.settings)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("mode_matches", [True, False])
|
|||
|
|
async def test_step_mode_applies_only_to_same_frozen_editing_mode(system, mode_matches):
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
switched = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/mode",
|
|||
|
|
json=dict(expected_version=saved["version"], mode="manual"),
|
|||
|
|
headers={"Idempotency-Key": "step-preview-mode"},
|
|||
|
|
)
|
|||
|
|
assert switched.status_code == 200, switched.text
|
|||
|
|
version = switched.json()["version"]
|
|||
|
|
rid = await start(system, draft_id, version, preview=True)
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
if not mode_matches:
|
|||
|
|
# 单独覆盖模式守卫,即使版本相同也不能跨执行方式误应用。
|
|||
|
|
async with db.session() as s:
|
|||
|
|
d = await s.get(WorkflowDraft, draft_id)
|
|||
|
|
d.editor_manifest = {**d.editor_manifest, "editing_mode": "auto"}
|
|||
|
|
await s.commit()
|
|||
|
|
assert (await apply_pending_result(db, rid, system.settings)) is mode_matches
|
|||
|
|
async with db.session() as s:
|
|||
|
|
d = await s.get(WorkflowDraft, draft_id)
|
|||
|
|
assert d.editor_manifest["editing_mode"] == ("manual" if mode_matches else "auto")
|
|||
|
|
assert ("normalized_speech:" + U in d.editor_manifest["bindings"]) is mode_matches
|
|||
|
|
assert (await s.get(WorkflowRun, rid)).apply_state == (
|
|||
|
|
"applied" if mode_matches else "conflict"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("verdict", "attempts"), [("reject", 2), ("indeterminate", 1), ("wrong_range", 1)]
|
|||
|
|
)
|
|||
|
|
async def test_speech_quality_limits_before_h3(system, tmp_path, verdict, attempts):
|
|||
|
|
draft_id, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
rid = await start(system, draft_id, saved["version"])
|
|||
|
|
db = system.app.state.db
|
|||
|
|
for _ in range(20):
|
|||
|
|
await tick(system, rid)
|
|||
|
|
await record_audio(system, rid, verdict)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
if run.state == "blocked":
|
|||
|
|
assert run.error_json["code"] == "dialogue_quality_" + (
|
|||
|
|
"indeterminate" if verdict == "wrong_range" else verdict
|
|||
|
|
)
|
|||
|
|
assert not run.prepared_plan
|
|||
|
|
jobs = (await s.scalars(select(Job).where(Job.run_id == rid))).all()
|
|||
|
|
assert not any(j.task_type.startswith("video.") for j in jobs)
|
|||
|
|
assert len([j for j in jobs if j.step_key == "sq_0001"]) == attempts
|
|||
|
|
assert not any(
|
|||
|
|
k.startswith("speech_report:") for k in run.result_manifest["bindings"]
|
|||
|
|
)
|
|||
|
|
return
|
|||
|
|
pytest.fail("音频质量不合格仍未阻塞")
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_frame_target_excludes_other_shots_and_speech(system, tmp_path):
|
|||
|
|
draft_id, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
sid = saved["manifest"]["shot_ids"][1]
|
|||
|
|
body = dict(expected_version=saved["version"], output_goal="media", targets=["frame:" + sid])
|
|||
|
|
plan = await system.client.post(f"/api/editors/{draft_id}/plan", json=body)
|
|||
|
|
assert not plan.json()["issues"], plan.text
|
|||
|
|
body["expected_plan_hash"] = plan.json()["plan_hash"]
|
|||
|
|
started = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/runs", json=body, headers={"Idempotency-Key": "one-frame"}
|
|||
|
|
)
|
|||
|
|
rid = started.json()["run"]["id"]
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
assert run.prepared_plan, run.error_json
|
|||
|
|
assert [(r["binding_key"], r["unit_id"]) for r in run.prepared_plan["steps"]] == [
|
|||
|
|
("frame:" + sid, sid)
|
|||
|
|
]
|
|||
|
|
assert run.plan_snapshot["steps"] == []
|
|||
|
|
summary = (await snapshot_run(s, run.owner_id, rid))["run"]["quality"]
|
|||
|
|
assert (summary["accepted_shots"], summary["total_shots"]) == (0, 0)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("manual", [False, True, "original"])
|
|||
|
|
async def test_disabled_dialogue_keeps_author_and_optional_manual_sound(
|
|||
|
|
system, provider, tmp_path, manual
|
|||
|
|
):
|
|||
|
|
source = motion(system.settings, tmp_path)
|
|||
|
|
if manual == "original":
|
|||
|
|
path = tmp_path / "original.mp4"
|
|||
|
|
subprocess.run(
|
|||
|
|
[
|
|||
|
|
system.settings.ffmpeg_bin,
|
|||
|
|
"-v",
|
|||
|
|
"error",
|
|||
|
|
"-y",
|
|||
|
|
"-i",
|
|||
|
|
str(tmp_path / "testsrc.mp4"),
|
|||
|
|
"-f",
|
|||
|
|
"lavfi",
|
|||
|
|
"-i",
|
|||
|
|
"sine=frequency=620:sample_rate=48000:duration=2",
|
|||
|
|
"-c:v",
|
|||
|
|
"copy",
|
|||
|
|
"-c:a",
|
|||
|
|
"aac",
|
|||
|
|
str(path),
|
|||
|
|
],
|
|||
|
|
check=True,
|
|||
|
|
)
|
|||
|
|
source = path.read_bytes()
|
|||
|
|
draft_id, saved = await configure(system, video=source)
|
|||
|
|
m = saved["manifest"]
|
|||
|
|
m["spec"]["dialogue"]["enabled"] = False
|
|||
|
|
if manual == "original":
|
|||
|
|
m["spec"]["shots"][0]["performance"]["original_audio"] = "preserve"
|
|||
|
|
if manual is True:
|
|||
|
|
tid = m["spec"]["dialogue"]["speakers"][0]["voice"]["reference_asset_id"]
|
|||
|
|
m["audio"].update(
|
|||
|
|
mode="manual_track",
|
|||
|
|
mix_mode="manual_mix",
|
|||
|
|
track=dict(
|
|||
|
|
asset_id=tid,
|
|||
|
|
source_start_sample=12000,
|
|||
|
|
source_end_sample=60000,
|
|||
|
|
offset_sample=12000,
|
|||
|
|
),
|
|||
|
|
)
|
|||
|
|
amended = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/save",
|
|||
|
|
json=dict(manifest=m, expected_version=saved["version"]),
|
|||
|
|
headers={"Idempotency-Key": "disable-dialogue"},
|
|||
|
|
)
|
|||
|
|
assert amended.status_code == 200, amended.text
|
|||
|
|
rid = await start(system, draft_id, amended.json()["version"])
|
|||
|
|
db = system.app.state.db
|
|||
|
|
for _ in range(15):
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
assert r.state != "blocked", r.error_json
|
|||
|
|
if r.state == "succeeded":
|
|||
|
|
summary = (await snapshot_run(s, r.owner_id, rid))["run"]["quality"]
|
|||
|
|
assert (summary["accepted_shots"], summary["total_shots"]) == (2, 2)
|
|||
|
|
assert len(r.result_manifest["spec"]["dialogue"]["utterances"]) == 2
|
|||
|
|
kinds = (await s.scalars(select(Job.task_type).where(Job.run_id == rid))).all()
|
|||
|
|
assert "audio.speech" not in kinds and "video.lipsync" not in kinds
|
|||
|
|
assert ("audio.mix" in kinds) == bool(manual)
|
|||
|
|
rendered = await s.get(Asset, r.current_output_asset_id)
|
|||
|
|
streams = json.loads(
|
|||
|
|
subprocess.check_output(
|
|||
|
|
[
|
|||
|
|
system.settings.ffprobe_bin,
|
|||
|
|
"-v",
|
|||
|
|
"error",
|
|||
|
|
"-show_streams",
|
|||
|
|
"-of",
|
|||
|
|
"json",
|
|||
|
|
str(system.settings.asset_root / rendered.storage_key),
|
|||
|
|
]
|
|||
|
|
)
|
|||
|
|
)["streams"]
|
|||
|
|
compose = next(st for st in await steps(s, rid) if st.kind == "video.compose")
|
|||
|
|
assert ("audio_asset_id" in compose.resolved_input_json["input"]) == bool(manual)
|
|||
|
|
pcm = subprocess.check_output(
|
|||
|
|
[
|
|||
|
|
system.settings.ffmpeg_bin,
|
|||
|
|
"-v",
|
|||
|
|
"error",
|
|||
|
|
"-i",
|
|||
|
|
str(system.settings.asset_root / rendered.storage_key),
|
|||
|
|
"-map",
|
|||
|
|
"0:a:0",
|
|||
|
|
"-f",
|
|||
|
|
"s16le",
|
|||
|
|
"pipe:1",
|
|||
|
|
]
|
|||
|
|
)
|
|||
|
|
assert any(pcm) == bool(manual)
|
|||
|
|
if manual == "original":
|
|||
|
|
assert kinds.count("audio.dialogue.extract") == 1
|
|||
|
|
assert "original_audio:" + m["shot_ids"][0] in r.result_manifest["bindings"]
|
|||
|
|
return
|
|||
|
|
for st in await steps(s, rid):
|
|||
|
|
if st.kind == "audio.normalize" and st.selected_job_id:
|
|||
|
|
j = await s.get(Job, st.selected_job_id)
|
|||
|
|
if j.state != "succeeded":
|
|||
|
|
await asset(s, system, j.owner_id, "audio", wav(60000), 1.25, j)
|
|||
|
|
j.result_json = {"sample_count": 60000, "sample_rate": 48000}
|
|||
|
|
j.state, j.phase = "succeeded", "done"
|
|||
|
|
await s.commit()
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, "pass")
|
|||
|
|
pytest.fail("关闭对白后的制作未完成")
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_tp2_real_generation_requires_callback_but_verified_base_does_not(system, tmp_path):
|
|||
|
|
from app.services.orchestration import dialogue_engine as e
|
|||
|
|
from app.domain.video_generation import H3_TP2_PROFILE
|
|||
|
|
|
|||
|
|
draft_id, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
m = deepcopy(saved["manifest"])
|
|||
|
|
sid = m["shot_ids"][0]
|
|||
|
|
m["spec"]["shots"][0]["video_parameters"].update(profile=H3_TP2_PROFILE, upscale=False)
|
|||
|
|
calls = []
|
|||
|
|
|
|||
|
|
async def denied():
|
|||
|
|
calls.append(1)
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
draft = await s.get(WorkflowDraft, draft_id)
|
|||
|
|
body = dict(output_goal="media", targets=["base_video:" + sid])
|
|||
|
|
plan = await e.plan_editor(s, draft, m, body, system.settings, tp2_capability=denied)
|
|||
|
|
assert not calls and not plan["issues"]
|
|||
|
|
forced = await e.plan_editor(
|
|||
|
|
s, draft, m, {**body, "force": ["video:" + sid]}, system.settings, tp2_capability=denied
|
|||
|
|
)
|
|||
|
|
assert calls and any(i["code"] == "capability_unavailable" for i in forced["issues"])
|
|||
|
|
del m["bindings"]["video:" + sid]
|
|||
|
|
plan = await e.plan_editor(s, draft, m, body, system.settings, tp2_capability=denied)
|
|||
|
|
assert len(calls) == 2 and any(
|
|||
|
|
i["code"] == "capability_unavailable" for i in plan["issues"]
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_too_short_derived_base_is_excluded(system, tmp_path):
|
|||
|
|
from app.services.orchestration.dialogue_engine import _reusable
|
|||
|
|
|
|||
|
|
draft_id, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
m = deepcopy(saved["manifest"])
|
|||
|
|
sid = m["shot_ids"][0]
|
|||
|
|
m["bindings"]["base_video:" + sid] = m["bindings"].pop("video:" + sid)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
owner = (await s.get(WorkflowDraft, draft_id)).owner_id
|
|||
|
|
assert "base_video:" + sid in await _reusable(s, owner, m, system.settings)
|
|||
|
|
m["spec"]["shots"][0]["edit"]["start_frame"] = 1
|
|||
|
|
assert "base_video:" + sid not in await _reusable(s, owner, m, system.settings)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("enabled", "timing", "budget_error"),
|
|||
|
|
[(False, "auto", True), (True, "fixed", True), (True, "auto", False)],
|
|||
|
|
)
|
|||
|
|
async def test_plan_fixed_and_shrinkable_frame_budget(system, enabled, timing, budget_error):
|
|||
|
|
from app.services.orchestration.dialogue_engine import plan_editor
|
|||
|
|
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
m = deepcopy(saved["manifest"])
|
|||
|
|
shots = m["spec"]["shots"]
|
|||
|
|
for index in range(19):
|
|||
|
|
sh = deepcopy(shots[0])
|
|||
|
|
sh["id"] = f"{1000 + index:032x}"
|
|||
|
|
sh["cast"][0]["id"] = f"{2000 + index:032x}"
|
|||
|
|
shots.append(sh)
|
|||
|
|
for sh in shots:
|
|||
|
|
sh["edit"]["duration_frames"] = 360
|
|||
|
|
sh["video_parameters"]["source_seconds"] = 15
|
|||
|
|
sh["performance"]["duration_mode"] = "auto"
|
|||
|
|
m["shot_ids"] = [sh["id"] for sh in shots]
|
|||
|
|
m["spec"]["dialogue"]["enabled"] = enabled
|
|||
|
|
seq = m["spec"]["dialogue"]["sequences"][0]
|
|||
|
|
seq.update(timing_mode=timing, shot_ids=m["shot_ids"].copy())
|
|||
|
|
async with system.app.state.db.session() as session:
|
|||
|
|
draft = await session.get(WorkflowDraft, draft_id)
|
|||
|
|
plan = await plan_editor(session, draft, m, {"output_goal": "film"}, system.settings)
|
|||
|
|
assert any(i["code"] == "dialogue_budget_exceeded" for i in plan["issues"]) is budget_error
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("scheduler", [False, True])
|
|||
|
|
async def test_advance_v5_requests_parent_locks_before_run(system, scheduler):
|
|||
|
|
from sqlalchemy import event
|
|||
|
|
from sqlalchemy.orm import Session
|
|||
|
|
from app.services.orchestration.workflow_engine import advance_workflows
|
|||
|
|
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
rid = await start(system, draft_id, saved["version"], preview=True)
|
|||
|
|
requests = []
|
|||
|
|
|
|||
|
|
def record(orm_state):
|
|||
|
|
stmt = orm_state.statement
|
|||
|
|
if getattr(stmt, "_for_update_arg", None) is not None:
|
|||
|
|
requests.extend(t.name for t in stmt.get_final_froms() if hasattr(t, "name"))
|
|||
|
|
|
|||
|
|
event.listen(Session, "do_orm_execute", record)
|
|||
|
|
try:
|
|||
|
|
if scheduler:
|
|||
|
|
await advance_workflows(system.app.state.db, system.settings, system.provider)
|
|||
|
|
else:
|
|||
|
|
async with system.app.state.db.session() as session:
|
|||
|
|
await advance_run(session, rid, system.settings)
|
|||
|
|
finally:
|
|||
|
|
event.remove(Session, "do_orm_execute", record)
|
|||
|
|
first_run = requests.index(WorkflowRun.__tablename__)
|
|||
|
|
assert requests[first_run - 2 : first_run + 1] == [
|
|||
|
|
User.__tablename__,
|
|||
|
|
WorkflowDraft.__tablename__,
|
|||
|
|
WorkflowRun.__tablename__,
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("story_list", [True, False])
|
|||
|
|
async def test_run_list_orders_narrow_ids_then_loads_snapshots(system, story_list):
|
|||
|
|
from sqlalchemy import event
|
|||
|
|
from sqlalchemy.dialects import mysql
|
|||
|
|
from app.models import utcnow
|
|||
|
|
|
|||
|
|
draft_id, saved = await configure(system)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
ids = [f"{n:032x}" for n in (5001, 5002, 5003)]
|
|||
|
|
async with db.session() as session:
|
|||
|
|
draft = await session.get(WorkflowDraft, draft_id)
|
|||
|
|
created = utcnow()
|
|||
|
|
for rid in ids:
|
|||
|
|
session.add(
|
|||
|
|
WorkflowRun(
|
|||
|
|
id=rid,
|
|||
|
|
owner_id=draft.owner_id,
|
|||
|
|
draft_id=draft_id,
|
|||
|
|
draft_revision=draft.revision,
|
|||
|
|
spec_hash="a" * 64,
|
|||
|
|
spec_snapshot=draft.spec,
|
|||
|
|
run_kind="story_auto",
|
|||
|
|
plan_snapshot={"manifest": saved["manifest"], "padding": "x" * 150000},
|
|||
|
|
created_at=created,
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
await session.commit()
|
|||
|
|
ordered_queries = []
|
|||
|
|
|
|||
|
|
def inspect(conn, clause, multiparams, params, opts):
|
|||
|
|
if not getattr(clause, "is_select", False) or not clause._order_by_clauses:
|
|||
|
|
return
|
|||
|
|
if WorkflowRun.__table__ in clause.get_final_froms():
|
|||
|
|
ordered_queries.append(
|
|||
|
|
str(clause.compile(dialect=mysql.dialect())).split("FROM", 1)[0].strip()
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
engine = db.engine.sync_engine
|
|||
|
|
event.listen(engine, "before_execute", inspect)
|
|||
|
|
try:
|
|||
|
|
url = f"/api/stories/{draft_id}/runs" if story_list else "/api/workflow-runs"
|
|||
|
|
response = await system.client.get(url, params={"page": 2, "page_size": 1})
|
|||
|
|
finally:
|
|||
|
|
event.remove(engine, "before_execute", inspect)
|
|||
|
|
assert response.status_code == 200, response.text[:100]
|
|||
|
|
payload = response.json()
|
|||
|
|
assert payload["total"] == 3 and [r["id"] for r in payload["items"]] == [ids[1]]
|
|||
|
|
assert payload["items"][0]["frozen_spec"]["schema_version"] == 5
|
|||
|
|
assert ordered_queries == ["SELECT visual_workflow_runs.id"]
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("legacy_version", [2, 3, 4, 5])
|
|||
|
|
async def test_legacy_final_requires_new_sync_with_verified_visual_inputs(
|
|||
|
|
system, provider, tmp_path, monkeypatch, legacy_version
|
|||
|
|
):
|
|||
|
|
from app.services.orchestration import dialogue_engine as e
|
|||
|
|
|
|||
|
|
old_contract = {"recipe": "dialogue-final-v2"}
|
|||
|
|
if legacy_version >= 3:
|
|||
|
|
old_contract = e._final_render_contract()
|
|||
|
|
old_contract["speech_silence_policy"] = "neutral-rest-v1"
|
|||
|
|
if legacy_version < 5:
|
|||
|
|
old_contract.pop("audio_context_shift_policy", None)
|
|||
|
|
if legacy_version == 3:
|
|||
|
|
old_contract["recipe"] = "dialogue-final-v3-neutral-rest"
|
|||
|
|
old_contract.pop("mouth_blend_policy", None)
|
|||
|
|
elif legacy_version == 4:
|
|||
|
|
old_contract["recipe"] = "dialogue-final-v4-mouth-policy"
|
|||
|
|
|
|||
|
|
draft_id, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
db = system.app.state.db
|
|||
|
|
|
|||
|
|
async def finish(version, key):
|
|||
|
|
if key == "legacy-final":
|
|||
|
|
dialogue_capabilities(system, "neutral-rest-v1")
|
|||
|
|
with monkeypatch.context() as old:
|
|||
|
|
old.setattr(e, "_final_render_contract", lambda: deepcopy(old_contract))
|
|||
|
|
rid = await start(system, draft_id, version, key=key)
|
|||
|
|
if legacy_version == 2:
|
|||
|
|
async with db.session() as session:
|
|||
|
|
run = await session.get(WorkflowRun, rid)
|
|||
|
|
plan = deepcopy(run.plan_snapshot)
|
|||
|
|
plan["capabilities"].pop("final_render_contract")
|
|||
|
|
run.plan_snapshot = plan
|
|||
|
|
await session.commit()
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
async with db.session() as session:
|
|||
|
|
run = await session.get(WorkflowRun, rid)
|
|||
|
|
assert run.prepared_plan["final_render_contract"] == old_contract
|
|||
|
|
else:
|
|||
|
|
dialogue_capabilities(system, "source-rest-v2")
|
|||
|
|
rid = await start(system, draft_id, version, key=key)
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
async with db.session() as session:
|
|||
|
|
run = await session.get(WorkflowRun, rid)
|
|||
|
|
contract = run.prepared_plan["final_render_contract"]
|
|||
|
|
assert contract == run.plan_snapshot["capabilities"]["final_render_contract"]
|
|||
|
|
assert contract["speech_silence_policy"] == "source-rest-v2"
|
|||
|
|
for _ in range(20):
|
|||
|
|
await tick(system, rid)
|
|||
|
|
await finish_media_jobs(
|
|||
|
|
system,
|
|||
|
|
rid,
|
|||
|
|
provider,
|
|||
|
|
tmp_path,
|
|||
|
|
"legacy_pass" if key == "legacy-final" and legacy_version == 2 else "pass",
|
|||
|
|
**(
|
|||
|
|
{"lip_policy": None, "qa_policy": None}
|
|||
|
|
if key == "legacy-final" and legacy_version < 4
|
|||
|
|
else {}
|
|||
|
|
),
|
|||
|
|
)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
assert r.state != "blocked", r.error_json
|
|||
|
|
if r.state == "succeeded":
|
|||
|
|
jobs = (await s.scalars(select(Job.task_type).where(Job.run_id == rid))).all()
|
|||
|
|
break
|
|||
|
|
else:
|
|||
|
|
pytest.fail("未能完成口型质量门")
|
|||
|
|
assert await apply_pending_result(db, rid, system.settings)
|
|||
|
|
return jobs
|
|||
|
|
|
|||
|
|
await finish(saved["version"], "legacy-final")
|
|||
|
|
latest = (await system.client.get(f"/api/editors/{draft_id}")).json()
|
|||
|
|
jobs = await finish(latest["version"], "rest-policy")
|
|||
|
|
assert not {"audio.speech", "audio.normalize", "audio.dialogue.inspect"}.intersection(jobs)
|
|||
|
|
assert jobs.count("video.lipsync") == 2
|
|||
|
|
assert jobs.count("video.dialogue.inspect") == 2
|
|||
|
|
assert "video.generate" not in jobs and "video.dialogue.analyze" not in jobs
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("old_run", "receipt", "accepted"),
|
|||
|
|
[
|
|||
|
|
(False, "old_pass", False),
|
|||
|
|
(False, "old_reject", False),
|
|||
|
|
(False, "stale_asset", False),
|
|||
|
|
(False, "bad_revision", False),
|
|||
|
|
(True, "pass", False),
|
|||
|
|
(True, "old_pass", True),
|
|||
|
|
(False, "primary_pass", True),
|
|||
|
|
],
|
|||
|
|
)
|
|||
|
|
async def test_audio_qa_contract_migration(system, tmp_path, old_run, receipt, accepted):
|
|||
|
|
from app.services.orchestration import dialogue_engine as e
|
|||
|
|
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
rid = await start(system, did, saved["version"])
|
|||
|
|
db = system.app.state.db
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
plan = deepcopy(r.plan_snapshot)
|
|||
|
|
if old_run:
|
|||
|
|
plan["capabilities"].pop("audio_qa_contract", None)
|
|||
|
|
r.plan_snapshot = plan
|
|||
|
|
await s.commit()
|
|||
|
|
for _ in range(14):
|
|||
|
|
await tick(system, rid)
|
|||
|
|
await record_audio(system, rid, receipt)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
if r.state == "blocked":
|
|||
|
|
assert not accepted and r.error_json["code"] == "dialogue_quality_indeterminate"
|
|||
|
|
assert not r.prepared_plan
|
|||
|
|
return
|
|||
|
|
if r.prepared_plan:
|
|||
|
|
assert accepted
|
|||
|
|
new_caps = e._capabilities(system.settings)
|
|||
|
|
new_caps["reference_shas"] = r.plan_snapshot["capabilities"]["reference_shas"]
|
|||
|
|
m = r.result_manifest
|
|||
|
|
rows = e.preparation_recipes(
|
|||
|
|
m, m["bindings"], {"output_goal": "film"}, system.settings, new_caps
|
|||
|
|
)
|
|||
|
|
assert all(
|
|||
|
|
row["reuse"]
|
|||
|
|
for row in rows
|
|||
|
|
if row["kind"] in {"audio.normalize", "audio.speech"}
|
|||
|
|
)
|
|||
|
|
qa = [row for row in rows if row["kind"] == "audio.dialogue.inspect"]
|
|||
|
|
assert len(qa) == 2 and all(bool(row["reuse"]) == (not old_run) for row in qa)
|
|||
|
|
if not old_run:
|
|||
|
|
assert (
|
|||
|
|
r.prepared_plan["audio_qa_contract"]
|
|||
|
|
== plan["capabilities"]["audio_qa_contract"]
|
|||
|
|
)
|
|||
|
|
return
|
|||
|
|
pytest.fail("QA migration did not reach a decision")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_final_render_contract_identifies_certified_ellipse():
|
|||
|
|
from app.services.orchestration import dialogue_engine as e
|
|||
|
|
|
|||
|
|
contract = e._final_render_contract()
|
|||
|
|
assert contract["mouth_blend_policy"] == "semantic-skin-ellipse-v1"
|
|||
|
|
assert contract["recipe"] == "dialogue-final-v5-bounded-sync"
|
|||
|
|
assert contract["audio_context_shift_policy"] == "bounded-feature-shift-v1"
|
|||
|
|
|
|||
|
|
|
|||
|
|
WITHDRAWN_BLEND_POLICY = "semantic-lip-union-v1"
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("frozen_policy", "lip_policy", "qa_policy", "wrong_sha"),
|
|||
|
|
[
|
|||
|
|
(None, MOUTH_BLEND_POLICY, MOUTH_BLEND_POLICY, None),
|
|||
|
|
(None, None, MOUTH_BLEND_POLICY, None),
|
|||
|
|
(WITHDRAWN_BLEND_POLICY, MOUTH_BLEND_POLICY, MOUTH_BLEND_POLICY, None),
|
|||
|
|
(MOUTH_BLEND_POLICY, WITHDRAWN_BLEND_POLICY, WITHDRAWN_BLEND_POLICY, None),
|
|||
|
|
(MOUTH_BLEND_POLICY, None, MOUTH_BLEND_POLICY, None),
|
|||
|
|
(MOUTH_BLEND_POLICY, MOUTH_BLEND_POLICY, None, None),
|
|||
|
|
(MOUTH_BLEND_POLICY, MOUTH_BLEND_POLICY, MOUTH_BLEND_POLICY, "render"),
|
|||
|
|
(MOUTH_BLEND_POLICY, MOUTH_BLEND_POLICY, MOUTH_BLEND_POLICY, "inspect"),
|
|||
|
|
],
|
|||
|
|
)
|
|||
|
|
async def test_mouth_blend_requires_matching_generation_and_review(
|
|||
|
|
system, provider, tmp_path, monkeypatch, frozen_policy, lip_policy, qa_policy, wrong_sha
|
|||
|
|
):
|
|||
|
|
from app.services.orchestration import dialogue_engine as e
|
|||
|
|
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
contract = e._final_render_contract()
|
|||
|
|
if frozen_policy is None:
|
|||
|
|
contract.pop("mouth_blend_policy")
|
|||
|
|
contract.pop("audio_context_shift_policy", None)
|
|||
|
|
contract["recipe"] = "dialogue-final-v3-neutral-rest"
|
|||
|
|
else:
|
|||
|
|
contract["mouth_blend_policy"] = frozen_policy
|
|||
|
|
monkeypatch.setattr(e, "_final_render_contract", lambda: deepcopy(contract))
|
|||
|
|
rid = await start(system, did, saved["version"])
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
for _ in range(18):
|
|||
|
|
await finish_media_jobs(
|
|||
|
|
system,
|
|||
|
|
rid,
|
|||
|
|
provider,
|
|||
|
|
tmp_path,
|
|||
|
|
"pass",
|
|||
|
|
lip_policy=lip_policy,
|
|||
|
|
qa_policy=qa_policy,
|
|||
|
|
wrong_sha=wrong_sha,
|
|||
|
|
)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
if run.state == "blocked":
|
|||
|
|
assert run.error_json["code"] in {
|
|||
|
|
"dialogue_quality_indeterminate",
|
|||
|
|
"dialogue_render_contract_mismatch",
|
|||
|
|
}
|
|||
|
|
assert not run.current_output_asset_id
|
|||
|
|
assert not any(
|
|||
|
|
key.startswith("synced_video:") for key in run.result_manifest["bindings"]
|
|||
|
|
)
|
|||
|
|
return
|
|||
|
|
assert run.state != "succeeded", "不匹配的渲染政策仍通过了最终镜头验收"
|
|||
|
|
pytest.fail("口型合同不匹配未阻断")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def shift_evidence(speaker, offset=120):
|
|||
|
|
return {
|
|||
|
|
"decision": "reject",
|
|||
|
|
"reasons": ["sync_offset"],
|
|||
|
|
"scores": [
|
|||
|
|
{
|
|||
|
|
"decision": "reject",
|
|||
|
|
"speaker_id": speaker,
|
|||
|
|
"offset_ms": offset,
|
|||
|
|
"confidence": 6.4282,
|
|||
|
|
"voiced_windows": 49,
|
|||
|
|
"working_fps": 25,
|
|||
|
|
}
|
|||
|
|
],
|
|||
|
|
"rest_checks": [
|
|||
|
|
{
|
|||
|
|
"speaker_id": speaker,
|
|||
|
|
"decision": "pass",
|
|||
|
|
"silent_frames": 8,
|
|||
|
|
"windows": [{"decision": "pass", "start_frame": 0, "end_frame": 8}],
|
|||
|
|
}
|
|||
|
|
],
|
|||
|
|
"identity_samples": [{"speaker_id": speaker, "frame": 0, "similarity": 0.8}],
|
|||
|
|
"min_identity_similarity": 0.8,
|
|||
|
|
"max_protected_pixel_error": 0,
|
|||
|
|
"max_protected_block_mae": 0,
|
|||
|
|
"max_protected_block_severe_fraction": 0,
|
|||
|
|
"max_silent_speaker_error": 0,
|
|||
|
|
"listener_sync_checks": [],
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("patch", "current", "wanted"),
|
|||
|
|
[
|
|||
|
|
({}, 0, 3),
|
|||
|
|
({"offset_ms": -120}, 0, -3),
|
|||
|
|
({}, 2, 5),
|
|||
|
|
({}, 4, None),
|
|||
|
|
({"offset_ms": 400}, 0, None),
|
|||
|
|
({"offset_ms": -400}, 0, None),
|
|||
|
|
({"confidence": 2.5}, 0, None),
|
|||
|
|
({"voiced_windows": 14}, 0, None),
|
|||
|
|
({"offset_ms": 0}, 0, None),
|
|||
|
|
({"reason": "identity_changed"}, 0, None),
|
|||
|
|
({"missing": "identity_samples"}, 0, None),
|
|||
|
|
({"missing": "rest_checks"}, 0, None),
|
|||
|
|
({"rest_missing": "windows"}, 0, None),
|
|||
|
|
({"metrics": {"min_identity_similarity": 0.5}}, 0, None),
|
|||
|
|
({"metrics": {"max_protected_pixel_error": 6.1}}, 0, None),
|
|||
|
|
({"metrics": {"max_protected_block_mae": 18.1}}, 0, None),
|
|||
|
|
({"metrics": {"max_protected_block_severe_fraction": 0.16}}, 0, None),
|
|||
|
|
({"metrics": {"max_silent_speaker_error": 8.1}}, 0, None),
|
|||
|
|
({"metrics": {"max_protected_block_mae": float("nan")}}, 0, None),
|
|||
|
|
({"rest_decision": "reject"}, 0, None),
|
|||
|
|
({"multi": True}, 0, None),
|
|||
|
|
],
|
|||
|
|
)
|
|||
|
|
def test_bounded_sync_requires_single_strong_residual(patch, current, wanted):
|
|||
|
|
from app.services.orchestration.dialogue_engine import _next_sync_shift
|
|||
|
|
|
|||
|
|
report = shift_evidence(U)
|
|||
|
|
stems = [{"speaker_id": U}]
|
|||
|
|
if "reason" in patch:
|
|||
|
|
report["reasons"].append(patch["reason"])
|
|||
|
|
elif "missing" in patch:
|
|||
|
|
del report[patch["missing"]]
|
|||
|
|
elif "metrics" in patch:
|
|||
|
|
report.update(patch["metrics"])
|
|||
|
|
elif "rest_decision" in patch:
|
|||
|
|
report["rest_checks"][0]["windows"][0]["decision"] = patch["rest_decision"]
|
|||
|
|
elif "rest_missing" in patch:
|
|||
|
|
del report["rest_checks"][0][patch["rest_missing"]]
|
|||
|
|
elif patch.get("multi"):
|
|||
|
|
stems.append({"speaker_id": V})
|
|||
|
|
else:
|
|||
|
|
report["scores"][0].update(patch)
|
|||
|
|
assert _next_sync_shift(report, stems, current) == wanted
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("old", "receipt"), [(True, "unexpected"), (False, "missing"), (False, "wrong")]
|
|||
|
|
)
|
|||
|
|
async def test_shift_receipt_must_match_frozen_attempt(
|
|||
|
|
system, provider, tmp_path, monkeypatch, old, receipt
|
|||
|
|
):
|
|||
|
|
from app.services.orchestration import dialogue_engine as e
|
|||
|
|
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
if old:
|
|||
|
|
contract = e._final_render_contract()
|
|||
|
|
del contract["audio_context_shift_policy"]
|
|||
|
|
contract["recipe"] = "dialogue-final-v4-mouth-policy"
|
|||
|
|
monkeypatch.setattr(e, "_final_render_contract", lambda: deepcopy(contract))
|
|||
|
|
rid = await start(system, did, saved["version"])
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
for _ in range(16):
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, "pass", shift_receipt=receipt)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
if r.state == "blocked":
|
|||
|
|
assert r.error_json["code"] == "dialogue_render_contract_mismatch"
|
|||
|
|
assert not r.current_output_asset_id
|
|||
|
|
return
|
|||
|
|
pytest.fail("偏移错误或缺凭据的口型不应通过")
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("budget", ["max_total_repairs", "max_repairs_per_shot"])
|
|||
|
|
async def test_shift_respects_repair_budget(system, provider, tmp_path, budget):
|
|||
|
|
did, saved = await configure(
|
|||
|
|
system, video=motion(system.settings, tmp_path), repair_limits={budget: 0}
|
|||
|
|
)
|
|||
|
|
rid = await start(system, did, saved["version"])
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
for _ in range(16):
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, "correct_offset")
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
if r.state == "blocked":
|
|||
|
|
assert r.error_json["reasons"] == ["sync_offset"]
|
|||
|
|
q = (await snapshot_run(s, r.owner_id, rid))["run"]["quality"]
|
|||
|
|
assert q["total_repairs"] == 0
|
|||
|
|
lips = (
|
|||
|
|
await s.scalars(
|
|||
|
|
select(Job).where(Job.run_id == rid, Job.task_type == "video.lipsync")
|
|||
|
|
)
|
|||
|
|
).all()
|
|||
|
|
assert lips and all(j.parameters["audio_context_shift_frames"] == 0 for j in lips)
|
|||
|
|
return
|
|||
|
|
pytest.fail("预算耗尽后不应再次补偿")
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_resume_completed_review_with_nullable_cached_provenance(system, provider, tmp_path):
|
|||
|
|
from app.schemas.editors import BindingV2
|
|||
|
|
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
m = saved["manifest"]
|
|||
|
|
m["spec"]["dialogue"]["enabled"] = False
|
|||
|
|
saved = await system.client.post(
|
|||
|
|
f"/api/editors/{did}/save",
|
|||
|
|
json={"manifest": m, "expected_version": saved["version"]},
|
|||
|
|
headers={"Idempotency-Key": "silent-recovery"},
|
|||
|
|
)
|
|||
|
|
rid = await start(system, did, saved.json()["version"])
|
|||
|
|
db = system.app.state.db
|
|||
|
|
for _ in range(10):
|
|||
|
|
await tick(system, rid)
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, "pass")
|
|||
|
|
async with db.session() as s:
|
|||
|
|
st = {step.step_key: step for step in await steps(s, rid)}
|
|||
|
|
review = st.get("review_0001")
|
|||
|
|
if not review or not review.selected_job_id:
|
|||
|
|
continue
|
|||
|
|
qa_id = review.selected_job_id
|
|||
|
|
assert (await s.get(Job, qa_id)).state == "succeeded"
|
|||
|
|
candidate = st["sel_0001"]
|
|||
|
|
cached = BindingV2.model_validate(candidate.result_json).model_dump()
|
|||
|
|
assert cached["provenance"] is None
|
|||
|
|
candidate.result_json = cached
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
r.state = "blocked"
|
|||
|
|
r.error_json = {"code": "workflow_orchestration_failed", "admission_pending": False}
|
|||
|
|
await s.commit()
|
|||
|
|
break
|
|||
|
|
else:
|
|||
|
|
pytest.fail("未形成已完成评审待收集的冻结状态")
|
|||
|
|
resumed = await system.client.post(
|
|||
|
|
f"/api/workflow-runs/{rid}/resume", json={}, headers={"Idempotency-Key": "resume-original"}
|
|||
|
|
)
|
|||
|
|
assert resumed.status_code == 200, resumed.text
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
st = {step.step_key: step for step in await steps(s, rid)}
|
|||
|
|
assert r.state == "running" and r.error_json is None
|
|||
|
|
assert st["review_0001"].state == "succeeded" and st["review_0001"].selected_job_id == qa_id
|
|||
|
|
result = r.result_manifest["bindings"]["video:" + r.result_manifest["shot_ids"][0]]
|
|||
|
|
assert (
|
|||
|
|
result["asset_id"] == cached["asset_id"] and result["provenance"]["dialogue_signature"]
|
|||
|
|
)
|
|||
|
|
assert result["provenance"]["quality_asset_id"] == st["review_0001"].result_json["asset_id"]
|
|||
|
|
assert not any(
|
|||
|
|
j.task_type == "video.generate"
|
|||
|
|
for j in await s.scalars(select(Job).where(Job.run_id == rid))
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
for _ in range(6):
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, "pass")
|
|||
|
|
async with db.session() as s:
|
|||
|
|
st = {step.step_key: step for step in await steps(s, rid)}
|
|||
|
|
if st["compose"].selected_job_id:
|
|||
|
|
# 跨升级恢复时也可能只有最后一个 compose 的成功回执尚待收集。
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
r.error_json = {"code": "workflow_orchestration_failed", "admission_pending": False}
|
|||
|
|
await s.commit()
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
if r.state == "succeeded":
|
|||
|
|
assert r.error_json is None
|
|||
|
|
return
|
|||
|
|
pytest.fail("恢复后未完成整片")
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("previous_resume", [False, True])
|
|||
|
|
async def test_resume_cannot_advance_a_blocked_quality_step(
|
|||
|
|
system, provider, tmp_path, previous_resume
|
|||
|
|
):
|
|||
|
|
did, saved = await configure(
|
|||
|
|
system, video=motion(system.settings, tmp_path), repair_limits={"max_total_repairs": 0}
|
|||
|
|
)
|
|||
|
|
rid = await start(system, did, saved["version"])
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
db = system.app.state.db
|
|||
|
|
for _ in range(16):
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, "reject")
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
if r.state == "blocked":
|
|||
|
|
error = deepcopy(r.error_json)
|
|||
|
|
assert error["code"] == "dialogue_quality_reject"
|
|||
|
|
jobs = set(await s.scalars(select(Job.id).where(Job.run_id == rid)))
|
|||
|
|
if previous_resume:
|
|||
|
|
# 此前的恢复入口已持久化 queued,但真实质检步骤仍被阻断。
|
|||
|
|
r.state = "queued"
|
|||
|
|
await s.commit()
|
|||
|
|
break
|
|||
|
|
else:
|
|||
|
|
pytest.fail("未能复现质检步骤阻断")
|
|||
|
|
if not previous_resume:
|
|||
|
|
response = await system.client.post(
|
|||
|
|
f"/api/workflow-runs/{rid}/resume",
|
|||
|
|
json={},
|
|||
|
|
headers={"Idempotency-Key": "resume-quality-reject"},
|
|||
|
|
)
|
|||
|
|
assert response.status_code == 409, response.status_code
|
|||
|
|
assert response.json()["detail"]["code"] == "workflow_step_blocked"
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
assert r.state == "blocked" and r.error_json == error
|
|||
|
|
assert any(
|
|||
|
|
st.step_key == error["step_key"] and st.state == "blocked" for st in await steps(s, rid)
|
|||
|
|
)
|
|||
|
|
assert set(await s.scalars(select(Job.id).where(Job.run_id == rid))) == jobs
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_manual_shift_invalidates_only_one_lip_and_accumulates_repair(
|
|||
|
|
system, provider, tmp_path
|
|||
|
|
):
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
db = system.app.state.db
|
|||
|
|
|
|||
|
|
async def finish(version, key, verdict):
|
|||
|
|
rid = await start(system, did, version, key=key)
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
for _ in range(22):
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, verdict)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
assert r.state != "blocked", r.error_json
|
|||
|
|
if r.state == "succeeded":
|
|||
|
|
return rid
|
|||
|
|
pytest.fail("口型方案未完成")
|
|||
|
|
|
|||
|
|
first = await finish(saved["version"], "first-clip", "pass")
|
|||
|
|
assert await apply_pending_result(db, first, system.settings)
|
|||
|
|
dto = (await system.client.get(f"/api/editors/{did}")).json()
|
|||
|
|
m = dto["manifest"]
|
|||
|
|
previous = deepcopy(m["bindings"])
|
|||
|
|
sids = m["shot_ids"]
|
|||
|
|
m["spec"]["shots"][0]["performance"]["audio_context_shift_frames"] = 2
|
|||
|
|
m["spec"]["shots"][1]["performance"]["audio_context_shift_frames"] = 0
|
|||
|
|
changed = await system.client.post(
|
|||
|
|
f"/api/editors/{did}/save",
|
|||
|
|
json={"manifest": m, "expected_version": dto["version"]},
|
|||
|
|
headers={"Idempotency-Key": "manual-shift"},
|
|||
|
|
)
|
|||
|
|
assert changed.status_code == 200, changed.text
|
|||
|
|
saved = changed.json()
|
|||
|
|
assert saved["manifest"]["spec"]["shots"][0]["performance"]["audio_context_shift_frames"] == 2
|
|||
|
|
for key, old in previous.items():
|
|||
|
|
if key.split(":")[0] in {
|
|||
|
|
"frame",
|
|||
|
|
"base_video",
|
|||
|
|
"normalized_speech",
|
|||
|
|
"speech",
|
|||
|
|
"speech_report",
|
|||
|
|
"selected_video",
|
|||
|
|
"face_tracks",
|
|||
|
|
"speech_stem",
|
|||
|
|
}:
|
|||
|
|
assert saved["manifest"]["bindings"][key]["asset_id"] == old["asset_id"], key
|
|||
|
|
second = await finish(saved["version"], "manual-shift-run", "correct_offset")
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, second)
|
|||
|
|
st = {step.step_key: step for step in await steps(s, second)}
|
|||
|
|
assert st["accepted_0002"].state == "succeeded"
|
|||
|
|
all_jobs = (
|
|||
|
|
await s.scalars(select(Job).where(Job.run_id == second).order_by(Job.explicit_attempt))
|
|||
|
|
).all()
|
|||
|
|
lips = [j for j in all_jobs if j.task_type == "video.lipsync"]
|
|||
|
|
assert [(j.step_key, j.parameters["audio_context_shift_frames"]) for j in lips] == [
|
|||
|
|
("lip_0001", 2),
|
|||
|
|
("lip_0001", 5),
|
|||
|
|
]
|
|||
|
|
inspect = [j for j in all_jobs if j.task_type == "video.dialogue.inspect"]
|
|||
|
|
assert len(inspect) == 2 and all(
|
|||
|
|
"audio_context_shift_frames" not in j.parameters for j in inspect
|
|||
|
|
)
|
|||
|
|
assert all(
|
|||
|
|
j.task_type
|
|||
|
|
not in {
|
|||
|
|
"video.generate",
|
|||
|
|
"video.dialogue.select",
|
|||
|
|
"video.dialogue.analyze",
|
|||
|
|
"image.generate",
|
|||
|
|
"image.reference.generate",
|
|||
|
|
"audio.speech",
|
|||
|
|
"audio.normalize",
|
|||
|
|
"audio.dialogue.inspect",
|
|||
|
|
}
|
|||
|
|
and not j.step_key.startswith("stem_")
|
|||
|
|
for j in all_jobs
|
|||
|
|
)
|
|||
|
|
assert (
|
|||
|
|
r.result_manifest["spec"]["shots"][0]["performance"]["audio_context_shift_frames"] == 2
|
|||
|
|
)
|
|||
|
|
assert (
|
|||
|
|
r.result_manifest["bindings"]["video:" + sids[0]]["provenance"][
|
|||
|
|
"audio_context_shift_frames"
|
|||
|
|
]
|
|||
|
|
== 5
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_new_plan_refuses_legacy_silence_certificate(system, tmp_path):
|
|||
|
|
draft_id, saved = await configure(
|
|||
|
|
system, video=motion(system.settings, tmp_path), silence_policy="neutral-rest-v1"
|
|||
|
|
)
|
|||
|
|
plan = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/plan",
|
|||
|
|
json={"expected_version": saved["version"], "output_goal": "film"},
|
|||
|
|
)
|
|||
|
|
assert plan.status_code == 200, plan.text
|
|||
|
|
issues = plan.json()["issues"]
|
|||
|
|
assert any(
|
|||
|
|
issue["code"] == "capability_unavailable"
|
|||
|
|
and issue["unit_id"] == "lipsync"
|
|||
|
|
and "静音" in issue["message"]
|
|||
|
|
for issue in issues
|
|||
|
|
)
|
|||
|
|
analysis = await system.client.post(
|
|||
|
|
f"/api/editors/{draft_id}/plan",
|
|||
|
|
json={
|
|||
|
|
"expected_version": saved["version"],
|
|||
|
|
"output_goal": "media",
|
|||
|
|
"targets": ["face_tracks:" + saved["manifest"]["shot_ids"][0]],
|
|||
|
|
},
|
|||
|
|
)
|
|||
|
|
assert analysis.status_code == 200 and not analysis.json()["issues"], analysis.text
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("reason", "locked", "budget", "repair"),
|
|||
|
|
[
|
|||
|
|
("source_speaking_during_silence", False, 1, True),
|
|||
|
|
("source_speaking_during_silence", True, 1, False),
|
|||
|
|
("source_speaking_during_silence", False, 0, False),
|
|||
|
|
("insufficient_source_rest_evidence", False, 1, False),
|
|||
|
|
],
|
|||
|
|
)
|
|||
|
|
async def test_source_rest_repair_respects_evidence_lock_budget(
|
|||
|
|
system, provider, tmp_path, reason, locked, budget, repair
|
|||
|
|
):
|
|||
|
|
from app.domain.video_generation import H3_PROFILE
|
|||
|
|
|
|||
|
|
did, saved = await configure(
|
|||
|
|
system, video=motion(system.settings, tmp_path),
|
|||
|
|
repair_limits={"max_repairs_per_shot": budget},
|
|||
|
|
)
|
|||
|
|
m = saved["manifest"]
|
|||
|
|
sid = m["shot_ids"][0]
|
|||
|
|
m["spec"]["shots"][0]["video_parameters"]["profile"] = H3_PROFILE
|
|||
|
|
m["bindings"]["video:" + sid]["locked"] = locked
|
|||
|
|
db = system.app.state.db
|
|||
|
|
async with db.session() as s:
|
|||
|
|
ref = await s.get(Asset, m["spec"]["entities"][0]["reference_asset_ids"][0])
|
|||
|
|
m["bindings"]["frame:" + sid] = dict(
|
|||
|
|
asset_id=ref.id, sha256=ref.sha256, kind="image", source="manual",
|
|||
|
|
)
|
|||
|
|
saved = await system.client.post(
|
|||
|
|
f"/api/editors/{did}/save",
|
|||
|
|
json={"manifest": m, "expected_version": saved["version"]},
|
|||
|
|
headers={"Idempotency-Key": "rest-source-manual"},
|
|||
|
|
)
|
|||
|
|
assert saved.status_code == 200, saved.text
|
|||
|
|
rid = await start(system, did, saved.json()["version"])
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
for _ in range(15):
|
|||
|
|
await finish_media_jobs(
|
|||
|
|
system, rid, provider, tmp_path, "pass", silence_reason=reason,
|
|||
|
|
)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
q = (await snapshot_run(s, r.owner_id, rid))["run"]["quality"]
|
|||
|
|
st = {x.step_key: x for x in await steps(s, rid)}
|
|||
|
|
if repair and q["total_repairs"]:
|
|||
|
|
assert st["video_0001"].recipe_json["forced"]
|
|||
|
|
assert "嘴唇自然闭合" in st["video_0001"].recipe_json["input"]["prompt"]
|
|||
|
|
assert not st["lip_0001"].recipe_json["forced"]
|
|||
|
|
assert st["stem_0001_1"].state == "succeeded"
|
|||
|
|
assert q["total_repairs"] == 1
|
|||
|
|
return
|
|||
|
|
if r.state == "blocked":
|
|||
|
|
assert not repair
|
|||
|
|
assert q["total_repairs"] == 0
|
|||
|
|
assert r.error_json["reasons"] == [reason]
|
|||
|
|
assert "底片" in r.error_json["message"]
|
|||
|
|
assert not st["video_0001"].recipe_json["forced"]
|
|||
|
|
assert not st["lip_0001"].recipe_json["forced"]
|
|||
|
|
return
|
|||
|
|
pytest.fail("静音底片质检未完成")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_mouth_receipt_requires_each_source_speaker_and_all_quiet_frames():
|
|||
|
|
from app.services.orchestration.dialogue_engine import _silent_mouth_evidence
|
|||
|
|
|
|||
|
|
checks = {"a": ("pass", [(3, 9)]), "b": ("pass", [(1, 6)])}
|
|||
|
|
rows = [dict(speaker_id=k, silent_frames=n, measured_frames=n, block_count=n,
|
|||
|
|
max_block_mae=2., max_block_severe_fraction=.01, decision="pass")
|
|||
|
|
for k, n in (("a", 6), ("b", 5))]
|
|||
|
|
def good(data):
|
|||
|
|
return _silent_mouth_evidence({"silent_mouth_source_checks":data}, checks, "pass")
|
|||
|
|
assert good(rows)
|
|||
|
|
for change in ({"speaker_id":"a"}, {"measured_frames":4}, {"block_count":0},
|
|||
|
|
{"max_block_mae":19}, {"max_block_severe_fraction":.2}):
|
|||
|
|
assert not good([rows[0], {**rows[1], **change}])
|
|||
|
|
assert not good(rows[:1])
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize(
|
|||
|
|
("wrong_stage", "error_code"),
|
|||
|
|
[
|
|||
|
|
("render", "dialogue_render_contract_mismatch"),
|
|||
|
|
("inspect", "dialogue_quality_indeterminate"),
|
|||
|
|
("missing_source_checks", "dialogue_quality_indeterminate"),
|
|||
|
|
("missing_mouth_checks", "dialogue_quality_indeterminate"),
|
|||
|
|
],
|
|||
|
|
)
|
|||
|
|
async def test_source_rest_old_or_missing_receipts_never_publish(
|
|||
|
|
system, provider, tmp_path, wrong_stage, error_code
|
|||
|
|
):
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
rid = await start(system, did, saved["version"])
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
for _ in range(16):
|
|||
|
|
await finish_media_jobs(
|
|||
|
|
system,
|
|||
|
|
rid,
|
|||
|
|
provider,
|
|||
|
|
tmp_path,
|
|||
|
|
"pass",
|
|||
|
|
wrong_silence_receipt=wrong_stage,
|
|||
|
|
)
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
if r.state == "blocked":
|
|||
|
|
assert r.error_json["code"] == error_code
|
|||
|
|
assert not r.current_output_asset_id
|
|||
|
|
assert not any(k.startswith("synced_video:") for k in r.result_manifest["bindings"])
|
|||
|
|
return
|
|||
|
|
assert r.state != "succeeded"
|
|||
|
|
pytest.fail("错误的静音证据未触发闸门")
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_cancelled_legacy_frame_repair_restores_manual_input_only(
|
|||
|
|
system,
|
|||
|
|
other_client,
|
|||
|
|
tmp_path,
|
|||
|
|
monkeypatch,
|
|||
|
|
):
|
|||
|
|
from app.domain.video_generation import H3_PROFILE
|
|||
|
|
from app.models import Execution
|
|||
|
|
from app.models.workflows import WorkflowVariant, QualityAssessment
|
|||
|
|
from app.services.orchestration import dialogue_engine as engine
|
|||
|
|
|
|||
|
|
system.settings.reference_generation_enabled = True
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
m = saved["manifest"]
|
|||
|
|
sid = m["shot_ids"][0]
|
|||
|
|
db = system.app.state.db
|
|||
|
|
async with db.session() as s:
|
|||
|
|
ref = await s.get(Asset, m["spec"]["entities"][0]["reference_asset_ids"][0])
|
|||
|
|
binding = dict(asset_id=ref.id, sha256=ref.sha256, kind="image", source="manual")
|
|||
|
|
for shot in m["spec"]["shots"]:
|
|||
|
|
shot["video_parameters"]["profile"] = H3_PROFILE
|
|||
|
|
shot["performance"]["lip_sync"] = "required"
|
|||
|
|
m["bindings"]["frame:" + shot["id"]] = binding.copy()
|
|||
|
|
m["bindings"].pop("video:" + shot["id"])
|
|||
|
|
saved = await system.client.post(
|
|||
|
|
f"/api/editors/{did}/save",
|
|||
|
|
json={"manifest": m, "expected_version": saved["version"]},
|
|||
|
|
headers={"Idempotency-Key": "manual-input"},
|
|||
|
|
)
|
|||
|
|
assert saved.status_code == 200, saved.text
|
|||
|
|
rid = await start(system, did, saved.json()["version"])
|
|||
|
|
# 复现部署升级前实际冻结的旧评审配方。
|
|||
|
|
original_recipes = engine.production_recipes
|
|||
|
|
|
|||
|
|
def legacy(*args, **kwargs):
|
|||
|
|
rows = original_recipes(*args, **kwargs)
|
|||
|
|
for r in rows:
|
|||
|
|
if r["kind"] == "video.dialogue.review":
|
|||
|
|
r["input"]["expected"].pop("source_visual_policy", None)
|
|||
|
|
r["repair_root"] = r["key"].replace("review_", "frame_")
|
|||
|
|
return rows
|
|||
|
|
|
|||
|
|
with monkeypatch.context() as patch:
|
|||
|
|
patch.setattr(engine, "production_recipes", legacy)
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
st = {v.step_key: v for v in await steps(s, rid)}
|
|||
|
|
other_h3 = st["video_0002"].selected_job_id
|
|||
|
|
reject = Job(
|
|||
|
|
owner_id=run.owner_id,
|
|||
|
|
run_id=rid,
|
|||
|
|
step_key="review_0001",
|
|||
|
|
task_type="video.dialogue.review",
|
|||
|
|
state="succeeded",
|
|||
|
|
phase="done",
|
|||
|
|
input_json={},
|
|||
|
|
parameters={},
|
|||
|
|
request_hash="a" * 64,
|
|||
|
|
upstream_key=uuid4().hex,
|
|||
|
|
)
|
|||
|
|
s.add(reject)
|
|||
|
|
await s.flush()
|
|||
|
|
variant = WorkflowVariant(
|
|||
|
|
run_id=rid,
|
|||
|
|
step_key="review_0001",
|
|||
|
|
ordinal=0,
|
|||
|
|
resolved_input={},
|
|||
|
|
candidate={"shot_id": sid},
|
|||
|
|
state="repair_requested",
|
|||
|
|
)
|
|||
|
|
s.add(variant)
|
|||
|
|
await s.flush()
|
|||
|
|
s.add(
|
|||
|
|
QualityAssessment(
|
|||
|
|
variant_id=variant.id,
|
|||
|
|
job_id=reject.id,
|
|||
|
|
verdict="reject",
|
|||
|
|
evidence={"reason": "底片张嘴"},
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
rejected_id = reject.id
|
|||
|
|
assert await engine._reset_quality_branch(s, run, "frame_0001", system.settings)
|
|||
|
|
await engine.create_editor_child(s, run, st["frame_0001"], system.settings)
|
|||
|
|
jid = st["frame_0001"].selected_job_id
|
|||
|
|
await s.commit()
|
|||
|
|
|
|||
|
|
url = f"/api/workflow-runs/{rid}/steps/frame_0001/restore-manual-frame"
|
|||
|
|
|
|||
|
|
async def payload():
|
|||
|
|
snap = (await system.client.get(f"/api/workflow-runs/{rid}")).json()
|
|||
|
|
return dict(
|
|||
|
|
expected_run_version=snap["run"]["version"],
|
|||
|
|
target_job_id=jid,
|
|||
|
|
rejected_review_job_id=rejected_id,
|
|||
|
|
frame_asset_id=binding["asset_id"],
|
|||
|
|
frame_sha256=binding["sha256"],
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
headers = {"Idempotency-Key": "restore-frame"}
|
|||
|
|
|
|||
|
|
async def restore(body):
|
|||
|
|
return await system.client.post(url, json=body, headers=headers)
|
|||
|
|
|
|||
|
|
body = await payload()
|
|||
|
|
assert (await other_client.post(url, json=body, headers=headers)).status_code == 404
|
|||
|
|
assert (await restore(body)).status_code == 409
|
|||
|
|
assert (await system.client.post(f"/api/jobs/{jid}/cancel")).status_code == 200
|
|||
|
|
await tick(system, rid)
|
|||
|
|
body = await payload()
|
|||
|
|
assert (await restore({**body, "frame_sha256": "0" * 64})).status_code == 409
|
|||
|
|
async with db.session() as s:
|
|||
|
|
active = Execution(
|
|||
|
|
job_id=jid,
|
|||
|
|
ordinal=1,
|
|||
|
|
phase_key="model",
|
|||
|
|
resource_pool="gpu",
|
|||
|
|
fence_token="x",
|
|||
|
|
state="allocated",
|
|||
|
|
)
|
|||
|
|
s.add(active)
|
|||
|
|
await s.commit()
|
|||
|
|
active_id = active.id
|
|||
|
|
assert (await restore(body)).json()["detail"]["code"] == "cleanup_pending"
|
|||
|
|
async with db.session() as s:
|
|||
|
|
(await s.get(Execution, active_id)).state = "exited"
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
locked = deepcopy(run.result_manifest)
|
|||
|
|
locked["bindings"]["base_video:" + sid] = {"locked": True}
|
|||
|
|
run.result_manifest = locked
|
|||
|
|
await s.commit()
|
|||
|
|
assert (await restore(body)).json()["detail"]["code"] == "quality_repair_locked"
|
|||
|
|
async with db.session() as s:
|
|||
|
|
run = await s.get(WorkflowRun, rid)
|
|||
|
|
unlocked = deepcopy(run.result_manifest)
|
|||
|
|
unlocked["bindings"].pop("base_video:" + sid)
|
|||
|
|
run.result_manifest = unlocked
|
|||
|
|
await s.commit()
|
|||
|
|
restored = await restore(body)
|
|||
|
|
assert restored.status_code == 200, restored.text
|
|||
|
|
snap = restored.json()
|
|||
|
|
assert snap["run"]["quality"]["total_repairs"] == 1
|
|||
|
|
assert (await restore(body)).json()["run"]["version"] == snap["run"]["version"]
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with db.session() as s:
|
|||
|
|
st = {v.step_key: v for v in await steps(s, rid)}
|
|||
|
|
assert (await s.get(Job, jid)).state == "cancelled"
|
|||
|
|
assert st["frame_0001"].result_json["sha256"] == binding["sha256"]
|
|||
|
|
assert st["frame_0001"].recipe_json["manual_frame_recovery"]["cancelled_job_id"] == jid
|
|||
|
|
assert st["review_0001"].state == "waiting"
|
|||
|
|
assert (
|
|||
|
|
other_h3
|
|||
|
|
and st["video_0002"].selected_job_id == other_h3
|
|||
|
|
and not (await s.get(Job, other_h3)).cancel_requested
|
|||
|
|
)
|
|||
|
|
assert st["video_0001"].selected_job_id
|
|||
|
|
job = await s.get(Job, st["video_0001"].selected_job_id)
|
|||
|
|
assert job.input_json["image_asset_id"] == binding["asset_id"]
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def test_existing_required_review_upgraded_at_dispatch(
|
|||
|
|
system, provider, tmp_path, monkeypatch
|
|||
|
|
):
|
|||
|
|
from app.services.orchestration import dialogue_engine as engine
|
|||
|
|
|
|||
|
|
did, saved = await configure(system, video=motion(system.settings, tmp_path))
|
|||
|
|
manifest = saved["manifest"]
|
|||
|
|
manifest["spec"]["shots"][0]["performance"]["lip_sync"] = "required"
|
|||
|
|
reply = await system.client.post(
|
|||
|
|
f"/api/editors/{did}/save",
|
|||
|
|
json={"expected_version": saved["version"], "manifest": manifest},
|
|||
|
|
headers={"Idempotency-Key": "required-review"},
|
|||
|
|
)
|
|||
|
|
assert reply.status_code == 200, reply.text
|
|||
|
|
rid = await start(system, did, reply.json()["version"])
|
|||
|
|
production = engine.production_recipes
|
|||
|
|
|
|||
|
|
def historical(*args, **kwargs):
|
|||
|
|
rows = production(*args, **kwargs)
|
|||
|
|
review = next(r for r in rows if r["key"] == "review_0001")
|
|||
|
|
review["input"]["expected"].pop("source_visual_policy")
|
|||
|
|
review["repair_root"] = "frame_0001"
|
|||
|
|
return rows
|
|||
|
|
|
|||
|
|
with monkeypatch.context() as patch:
|
|||
|
|
patch.setattr(engine, "production_recipes", historical)
|
|||
|
|
await prepare_run(system, rid)
|
|||
|
|
for _ in range(8):
|
|||
|
|
await finish_media_jobs(system, rid, provider, tmp_path, "pass")
|
|||
|
|
await tick(system, rid)
|
|||
|
|
async with system.app.state.db.session() as s:
|
|||
|
|
r = await s.get(WorkflowRun, rid)
|
|||
|
|
original = next(row for row in r.prepared_plan["steps"] if row["key"] == "review_0001")
|
|||
|
|
assert "source_visual_policy" not in original["input"]["expected"]
|
|||
|
|
st = next(row for row in await steps(s, rid) if row.step_key == "review_0001")
|
|||
|
|
if st.selected_job_id:
|
|||
|
|
job = await s.get(Job, st.selected_job_id)
|
|||
|
|
assert job.input_json["expected"]["source_visual_policy"] == "pre-lipsync-visual-v1"
|
|||
|
|
assert st.recipe_json["repair_root"] == "video_0001"
|
|||
|
|
return
|
|||
|
|
pytest.fail("冻结底片评审未提交")
|