388 lines
15 KiB
Python
388 lines
15 KiB
Python
from copy import deepcopy
|
|
|
|
import pytest
|
|
from pydantic import ValidationError
|
|
|
|
from test_native_dialogue_engine import manifest
|
|
|
|
|
|
def pair():
|
|
m = manifest()
|
|
spec = m["spec"]
|
|
spec["schema_version"] = 6
|
|
d, shot = spec["dialogue"], spec["shots"][0]
|
|
one = d["speakers"][0]
|
|
two = dict(deepcopy(one), id="5" * 32, entity_id="6" * 32, name="陈叔")
|
|
for i, sp in enumerate([one, two]):
|
|
sp.update(
|
|
model_speaker_number=i + 3,
|
|
face_reference_asset_id=str(i + 1) * 32,
|
|
voice_reference_asset_id=str(i + 7) * 32,
|
|
)
|
|
spec["entities"].append(dict(deepcopy(spec["entities"][0]), id=two["entity_id"]))
|
|
shot["cast"].append(dict(deepcopy(shot["cast"][0]), id="9" * 32, entity_id=two["entity_id"]))
|
|
d["speakers"].append(two)
|
|
line = dict(d["utterances"][0], id="a" * 32, speaker_id=two["id"], text="好啊。")
|
|
d["utterances"].append(line)
|
|
ids = [u["id"] for u in d["utterances"]]
|
|
d["sequences"][0]["utterance_ids"] = ids
|
|
shot["performance"].update(
|
|
dialogue_staging="two_person_turns",
|
|
native_utterance_ids=ids,
|
|
visible_speaker_ids=[one["id"], two["id"]],
|
|
first_frame_sha256="a" * 64,
|
|
listener_reactions={ids[0]: "听着点头", ids[1]: "微微一笑"},
|
|
)
|
|
return m
|
|
|
|
|
|
def test_explicit_v6_turns_use_stable_numbers_and_prompt():
|
|
from app.domain.dialogue import StorySpecV6, StorySpecV5
|
|
from app.domain.native_dialogue import compile_native_shots
|
|
|
|
m = pair()
|
|
StorySpecV6.model_validate(m["spec"])
|
|
with pytest.raises(ValidationError):
|
|
StorySpecV5.model_validate(dict(m["spec"], schema_version=5))
|
|
r = compile_native_shots(m)
|
|
assert not r["issues"]
|
|
shot = r["shots"][0]
|
|
assert shot["speaker_id"] is None
|
|
assert [t["utterance_id"] for t in shot["turns"]] == m["spec"]["dialogue"]["sequences"][0][
|
|
"utterance_ids"
|
|
]
|
|
assert all(word in shot["prompt"] for word in ["S3", "S4", "微微一笑", "点头", "闭"])
|
|
m["spec"]["dialogue"]["speakers"].reverse()
|
|
assert compile_native_shots(m)["shots"][0]["context_hash"] == shot["context_hash"]
|
|
|
|
|
|
def test_incomplete_pair_is_editable_but_unplannable():
|
|
from app.domain.dialogue import StorySpecV6
|
|
from app.domain.native_dialogue import compile_native_shots
|
|
|
|
m = pair()
|
|
del m["spec"]["dialogue"]["speakers"][0]["voice_reference_asset_id"]
|
|
StorySpecV6.model_validate(m["spec"])
|
|
assert "native_turn_reference_required" in {
|
|
i["code"] for i in compile_native_shots(m)["issues"]
|
|
}
|
|
|
|
|
|
def test_single_native_cert_does_not_admit_two_person_workflow():
|
|
from app.services.orchestration.native_dialogue_engine import _turn_generation_issue
|
|
|
|
m = pair()
|
|
from app.domain.native_dialogue import compile_native_shots
|
|
|
|
shot = compile_native_shots(m)["shots"][0]
|
|
assert _turn_generation_issue(shot, {"sha256": "a" * 64})["code"] == "native_turns_uncertified"
|
|
assert _turn_generation_issue(shot, {"sha256": "b" * 64})["code"] == "native_turn_frame_changed"
|
|
|
|
|
|
def test_only_turn_scope_certificate_can_open_printed_frame_count():
|
|
from app.adapters.provider.native_av import turn_certificate
|
|
from app.domain.video_generation import H3_NATIVE_AV_TP2_PROFILE as profile
|
|
|
|
p = dict(profile=profile, width=1344, height=768, num_frames=158)
|
|
assert turn_certificate({"video_generation": {"native_av_tp2": {"available": True}}}, p) is None
|
|
proof = dict(
|
|
available=True,
|
|
decision="pass",
|
|
audited=True,
|
|
policy="h3-two-person-turns-screen-v1",
|
|
release_policy="h3-two-person-turns-release-v1",
|
|
profile=profile,
|
|
revision="12253298adb81e36757eabebb81d2ba1c0cc70cc",
|
|
runtime_revision="423ab90580b2847998591669b8326f47b6d14d8b",
|
|
width=1344,
|
|
height=768,
|
|
num_frames=158,
|
|
language="Chinese",
|
|
fps=24,
|
|
first_pass=18,
|
|
overall_pass=22,
|
|
tasks=24,
|
|
report_sha256="b" * 64,
|
|
)
|
|
upstream = {"dialogue": {"two_person_turns": proof}}
|
|
assert turn_certificate(upstream, p) == "b" * 64
|
|
assert turn_certificate(upstream, dict(p, num_frames=141)) is None
|
|
assert turn_certificate(upstream, dict(p, width=768, height=1344)) is None
|
|
|
|
|
|
def test_turn_audit_uses_only_owned_asset_slots_and_distinct_refs():
|
|
from app.adapters.provider.dialogue_gpu import validate, SPEECH_INSPECT
|
|
from app.domain.errors import MediaError
|
|
|
|
ids = [f"{i:032x}" for i in range(10)]
|
|
args = dict(
|
|
profile="dialogue-audio-v1",
|
|
turn_policy="h3-two-person-turns-screen-v1",
|
|
certificate_sha256="d" * 64,
|
|
first_frame_sha256="a" * 64,
|
|
speaker_ids=["a" * 32, "b" * 32],
|
|
turns=[
|
|
dict(utterance_id="f" * 32, speaker_id="a" * 32, text="等等。"),
|
|
dict(utterance_id="e" * 32, speaker_id="b" * 32, text="好的。"),
|
|
],
|
|
)
|
|
validate(SPEECH_INSPECT, {"asset_ids": ids}, args)
|
|
with pytest.raises(MediaError):
|
|
validate(SPEECH_INSPECT, {"asset_ids": ids[:-1] + [ids[-2]]}, args)
|
|
|
|
|
|
@pytest.mark.parametrize("candidate_status", ["pass", "indeterminate", "reject", "incomplete"])
|
|
async def test_save_pair_then_plan_dedicated_check_and_gate_without_single_face_bypass(
|
|
system, tmp_path, candidate_status
|
|
):
|
|
from io import BytesIO
|
|
import wave
|
|
from PIL import Image
|
|
from app.models import WorkflowDraft
|
|
from test_dialogue_workflow import asset
|
|
from test_native_dialogue_workflow import native_story, capabilities
|
|
from app.adapters.provider.native_av import REVISION, RUNTIME_REVISION, TURN_POLICY
|
|
from app.domain.native_dialogue import compile_native_shots
|
|
|
|
capabilities(system)
|
|
did, state = await native_story(system)
|
|
m = state["manifest"]
|
|
m["schema_version"] = 4
|
|
m["spec"] = pair()["spec"]
|
|
shot = m["spec"]["shots"][0]
|
|
async with system.app.state.db.session() as session:
|
|
owner = (await session.get(WorkflowDraft, did)).owner_id
|
|
pictures = []
|
|
for color in ("navy", "gold", "pink"):
|
|
image = BytesIO()
|
|
Image.new("RGB", (128, 128), color).save(image, format="PNG")
|
|
pictures.append(await asset(session, system, owner, "image", image.getvalue()))
|
|
for i, role in enumerate(m["spec"]["dialogue"]["speakers"]):
|
|
sound = BytesIO()
|
|
with wave.open(sound, "wb") as w:
|
|
w.setparams((1, 2, 48000, 0, "NONE", ""))
|
|
w.writeframes(bytes([i, 0]) * 48000)
|
|
voice = await asset(session, system, owner, "audio", sound.getvalue(), 1)
|
|
role.update(face_reference_asset_id=pictures[i].id, voice_reference_asset_id=voice.id)
|
|
frame = pictures[2]
|
|
m["bindings"]["frame:" + shot["id"]] = dict(
|
|
asset_id=frame.id, sha256=frame.sha256, kind="image", source="manual", locked=False
|
|
)
|
|
shot["performance"]["first_frame_sha256"] = frame.sha256
|
|
await session.commit()
|
|
saved = await system.client.post(
|
|
f"/api/editors/{did}/save",
|
|
json=dict(expected_version=state["version"], manifest=m),
|
|
headers={"Idempotency-Key": "pair-save"},
|
|
)
|
|
assert saved.status_code == 200, saved.text
|
|
reopened = await system.client.get(f"/api/editors/{did}")
|
|
assert (
|
|
reopened.status_code == 200
|
|
and reopened.json()["manifest"]["spec"]["shots"][0]["performance"]
|
|
== saved.json()["manifest"]["spec"]["shots"][0]["performance"]
|
|
)
|
|
args = dict(
|
|
expected_version=saved.json()["version"],
|
|
output_goal="media",
|
|
targets=["video:" + shot["id"]],
|
|
)
|
|
p = await system.client.post(f"/api/editors/{did}/plan", json=args)
|
|
assert p.status_code == 200, p.text
|
|
assert {i["code"] for i in p.json()["issues"]} == {"native_turns_uncertified"}, p.text
|
|
assert [r["key"] for r in p.json()["steps"] if r["kind"] == "audio.dialogue.inspect"] == [
|
|
"nq_0001",
|
|
"nt_0001",
|
|
]
|
|
refused = await system.client.post(
|
|
f"/api/editors/{did}/runs",
|
|
json={**args, "expected_plan_hash": p.json()["plan_hash"]},
|
|
headers={"Idempotency-Key": "pair-closed"},
|
|
)
|
|
assert refused.status_code == 422, refused.text
|
|
original = system.provider.upstream_capabilities
|
|
native = compile_native_shots(m)["shots"][0]
|
|
|
|
async def audited():
|
|
snapshot = await original()
|
|
snapshot["dialogue"]["two_person_turns"] = dict(
|
|
available=True,
|
|
decision="pass",
|
|
audited=True,
|
|
policy=TURN_POLICY,
|
|
release_policy="h3-two-person-turns-release-v1",
|
|
revision=REVISION,
|
|
runtime_revision=RUNTIME_REVISION,
|
|
profile=native["parameters"]["profile"],
|
|
width=1344,
|
|
height=768,
|
|
num_frames=native["parameters"]["num_frames"],
|
|
language="Chinese",
|
|
fps=24,
|
|
first_pass=18,
|
|
overall_pass=22,
|
|
tasks=24,
|
|
report_sha256="f" * 64,
|
|
)
|
|
return snapshot
|
|
|
|
system.provider.upstream_capabilities = audited
|
|
permitted = await system.client.post(f"/api/editors/{did}/plan", json=args)
|
|
assert permitted.status_code == 200 and not permitted.json()["issues"], permitted.text
|
|
assert permitted.json()["plan_hash"] != p.json()["plan_hash"]
|
|
system.provider.upstream_capabilities = original
|
|
revoked = await system.client.post(
|
|
f"/api/editors/{did}/runs",
|
|
json={**args, "expected_plan_hash": permitted.json()["plan_hash"]},
|
|
headers={"Idempotency-Key": "revoked-pair"},
|
|
)
|
|
assert revoked.status_code in (409, 422), revoked.text
|
|
system.provider.upstream_capabilities = audited
|
|
run = await system.client.post(
|
|
f"/api/editors/{did}/runs",
|
|
json={**args, "expected_plan_hash": permitted.json()["plan_hash"]},
|
|
headers={"Idempotency-Key": "pair-media"},
|
|
)
|
|
assert run.status_code == 202, run.text
|
|
from test_native_dialogue_workflow import _drive
|
|
from app.adapters.provider.native_av import TURN_SOURCES
|
|
from app.domain.stories import digest
|
|
|
|
turns = m["spec"]["dialogue"]["utterances"]
|
|
|
|
def split_speech(report):
|
|
report["words"] = [
|
|
dict(text=u["text"], start_sample=12000 + i * 48000, end_sample=48000 + i * 48000)
|
|
for i, u in enumerate(turns)
|
|
]
|
|
|
|
def measured(step):
|
|
# 外部模型替身只在隔离测试中使用,产物绑定、驱动 DAG 和放行使用真实服务路径。
|
|
result = step.resolved_input_json
|
|
contract = result["parameters"]
|
|
hashes = dict(
|
|
zip(
|
|
TURN_SOURCES,
|
|
[result["input_sha256"][a] for a in result["input"]["asset_ids"]],
|
|
strict=True,
|
|
)
|
|
)
|
|
ids = contract["speaker_ids"]
|
|
checks = {
|
|
k: dict(decision="pass")
|
|
for k in (
|
|
"geometry",
|
|
"audio_binding",
|
|
"visual",
|
|
"tracking",
|
|
*["tail_" + sp for sp in ids],
|
|
)
|
|
}
|
|
checks["geometry"].update(
|
|
width=1344, height=768, fps=24, frames=native["parameters"]["num_frames"]
|
|
)
|
|
checks["visual"].update(source_matched=True, review_sha256=hashes["visual_review"])
|
|
return dict(
|
|
policy=TURN_POLICY,
|
|
controls=False,
|
|
certificate_sha256=contract["certificate_sha256"],
|
|
source_sha256=hashes,
|
|
decision=candidate_status if candidate_status != "incomplete" else "indeterminate",
|
|
checks=checks,
|
|
tracks={
|
|
sp: [
|
|
dict(
|
|
frame=i,
|
|
identity_similarities=[0.9, 0.1] if side == 0 else [0.1, 0.9],
|
|
box=[5, 5, 60, 60],
|
|
track_iou=1.0,
|
|
)
|
|
for i in range(native["parameters"]["num_frames"])
|
|
]
|
|
for side, sp in enumerate(ids)
|
|
},
|
|
author_sha256=digest(
|
|
dict(
|
|
speaker_ids=ids,
|
|
turns=contract["turns"],
|
|
first_frame_sha256=hashes["first_frame"],
|
|
references=[hashes[k] for k in ("face_0", "face_1", "voice_0", "voice_1")],
|
|
)
|
|
),
|
|
turns=[]
|
|
if candidate_status == "incomplete"
|
|
else [
|
|
dict(
|
|
utterance_id=u["id"],
|
|
expected_speaker_id=u["speaker_id"],
|
|
listener_id=ids[1 - i],
|
|
start_sample=12000 + i * 48000,
|
|
end_sample=48000 + i * 48000,
|
|
decision=candidate_status
|
|
if candidate_status != "incomplete"
|
|
else "indeterminate",
|
|
voice=dict(
|
|
observed_speaker_id=u["speaker_id"]
|
|
if candidate_status == "pass"
|
|
else ids[1 - i]
|
|
if candidate_status == "reject"
|
|
else None
|
|
),
|
|
speaker_sync=dict(decision="pass"),
|
|
listener_sync=dict(decision="indeterminate"),
|
|
listener_rest=dict(decision="pass"),
|
|
)
|
|
for i, u in enumerate(turns)
|
|
],
|
|
)
|
|
|
|
final, _, status, error, calls = await _drive(
|
|
system, run.json()["run"]["id"], tmp_path, bad_report=split_speech, turn_inspector=measured
|
|
)
|
|
if candidate_status != "pass":
|
|
from sqlalchemy import select
|
|
from app.models import WorkflowRun, WorkflowStep
|
|
|
|
rid = run.json()["run"]["id"]
|
|
assert status == "blocked", error
|
|
async with system.app.state.db.session() as s:
|
|
stored = await s.get(WorkflowRun, rid)
|
|
version = stored.version
|
|
gate = await s.scalar(
|
|
select(WorkflowStep).where(
|
|
WorkflowStep.run_id == rid, WorkflowStep.step_key == "ng_0001"
|
|
)
|
|
)
|
|
audit = await s.scalar(
|
|
select(WorkflowStep).where(
|
|
WorkflowStep.run_id == rid, WorkflowStep.step_key == "nt_0001"
|
|
)
|
|
)
|
|
assert gate.state == (
|
|
"awaiting_review" if candidate_status == "indeterminate" else "blocked"
|
|
)
|
|
sha = audit.result_json["sha256"]
|
|
review = await system.client.post(
|
|
f"/api/editors/{did}/runs/{rid}/turns/{shot['id']}/review",
|
|
json=dict(
|
|
expected_version=version,
|
|
decision="accept",
|
|
note="逐轮核对了两位角色的画面和原声",
|
|
report_sha256=sha,
|
|
),
|
|
headers={"Idempotency-Key": "manual-choice"},
|
|
)
|
|
if candidate_status in ("reject", "incomplete"):
|
|
assert review.status_code == 409, review.text
|
|
return
|
|
assert review.status_code == 200, review.text
|
|
final, _, status, error, further = await _drive(
|
|
system, rid, tmp_path, bad_report=split_speech, turn_inspector=measured
|
|
)
|
|
assert not further
|
|
assert status == "succeeded", error
|
|
assert calls["video.generate"] == 1 and calls["audio.dialogue.inspect"] == 2
|
|
assert final["bindings"]["native_alignment:" + shot["id"]]["provenance"]["turn_decision"] == (
|
|
"manual" if candidate_status == "indeterminate" else "pass"
|
|
)
|