cmvr-visual/backend/tests/test_caption_rhythm.py

437 lines
16 KiB
Python
Raw Permalink Normal View History

from copy import deepcopy
import json
from pathlib import Path
import pytest
from fastapi import HTTPException
from app.domain.editors import validate_manifest
from app.services import editor_media
from test_dialogue_domain import A, B, U, C, manifest
STYLE = dict(punctuation="hide", pacing="rhythm")
SHA = "a" * 64
VIDEO = "b" * 64
def case():
m = manifest()
m["schema_version"] = 4
m["captions"].update(mode="script", presentation=STYLE.copy(), edits=[], cues=[])
d = m["spec"]["dialogue"]
d.update(generation="native_av", language="Chinese")
d["utterances"][0]["text"] = "陈叔,以后还开吗?"
speaker = d["utterances"][0]["speaker_id"]
for shot, assigned in zip(m["spec"]["shots"], [[], [U]]):
shot["performance"]["native_utterance_ids"] = assigned
shot["edit"].update(start_frame=0, duration_frames=124, dedup_frames=0)
m["spec"]["render"]["total_frames"] = 248
words = [
dict(text="陈叔", start_sample=0, end_sample=45000),
dict(text="以后还开吗", start_sample=48000, end_sample=112000),
]
r = dict(
audio_sha256=SHA,
sample_rate=48000,
source_start_sample=0,
source_end_sample=153600,
timestamp_source="whisper-word-timestamps",
timestamp_origin="audio_asset",
native_av_policy="native_av_v1",
decision="pass",
word_alignment_status="completed",
expected_text=d["utterances"][0]["text"],
speaker_id=speaker,
asr_revision="41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
content_verification_policy="whisper-sensevoice-consensus-v1",
content_decision_source="whisper_sensevoice_consensus",
secondary_status="completed",
secondary_asr_revision="90c1c61912018b70ada0fcc024ea24aca62f2e63",
secondary_runtime_revision="6991744856587fa44379e8b5dcc432debffeb1be",
transcript="陈叔以后还开吗",
secondary_transcript="陈叔以后还开吗",
normalized_expected_text="陈叔以后还开吗",
normalized_transcript="陈叔以后还开吗",
normalized_secondary_transcript="陈叔以后还开吗",
reasons=[],
content_error_rate=0,
secondary_content_error_rate=0,
words=words,
)
probs = [0.99 if 8 <= i < 23 or 40 <= i < 75 else 0.01 for i in range(100)]
from app.domain.native_silence import POLICY, REVISION, MODEL_SHA256
r["silence_verification"] = dict(
policy=POLICY,
revision=REVISION,
model_sha256=MODEL_SHA256,
status="completed",
source="silero-vad-onnx-cpu",
decision="speech",
channels=2,
source_audio_sha256=SHA,
source_start_sample=0,
source_end_sample=153600,
sample_rate=16000,
sample_count=51200,
window_size_samples=512,
window_count=100,
threshold=0.5,
negative_threshold=0.35,
channel_probabilities=[probs, probs],
probabilities=probs,
)
bindings = {
"video:" + B: dict(sha256=VIDEO),
"native_audio:" + B: dict(
sha256=SHA, sample_count=153600, provenance=dict(audio_offset_samples=4000)
),
"native_alignment:" + B: dict(
provenance=dict(
native_av_policy="native_av_v1",
audio_sha256=SHA,
video_sha256=VIDEO,
shot_id=B,
audio_offset_samples=4000,
)
),
}
return m, bindings, {B: r}
def project(m, b, r):
return editor_media.preview_captions(m, b, reports=r)
def test_v4_keeps_edits_and_rejects_missing_parent_and_ambiguous_ids():
m, b, r = case()
legacy = manifest()
assert "presentation" not in validate_manifest(legacy)["captions"]
assert validate_manifest(m)["captions"]["presentation"] == STYLE
item = dict(
id=C,
utterance_id=U,
source_text="陈叔,以后还开吗?",
source_start=0,
source_end=3,
deleted=True,
)
m["captions"]["edits"] = [item, item]
with pytest.raises(HTTPException):
validate_manifest(m)
m["captions"]["edits"] = [dict(item, utterance_id=A)]
with pytest.raises(HTTPException):
validate_manifest(m)
def test_vad_pauses_and_author_glyphs_use_single_projection():
m, b, r = case()
before = deepcopy(m)
result = project(m, b, r)
assert not result["issues"]
left, right = result["rows"]
assert (left["text"], right["text"]) == ("陈叔", "以后还开吗")
assert 5 <= left["local_start_frame"] <= 9
assert left["end_frame"] + 6 <= right["start_frame"]
assert (left["source_start"], left["source_end"], right["source_end"]) == (0, 3, 9)
assert left["start_frame"] == 124 + left["local_start_frame"]
assert left["audio_sha256"] == SHA and left["status"] == "automatic"
assert editor_media.compile_captions(m, b, reports=r) == [
{k: row[k] for k in ("start_frame", "end_frame", "text")} for row in result["rows"]
]
assert m == before
def test_unmeasured_preview_identifies_parent_and_manual_calibration_resolves_it():
m, b, r = case()
r[B]["silence_verification"]["source_audio_sha256"] = VIDEO
pending = project(m, b, r)
assert pending["issues"][0]["unit_id"] == U
assert pending["rows"][0]["start_frame"] is None
with pytest.raises(ValueError, match="待校时"):
editor_media.compile_captions(m, b, reports=r)
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_start=0,
source_end=9,
source_text="陈叔,以后还开吗?",
timing_override=True,
start_frame=7,
end_frame=52,
)
]
assert editor_media.compile_captions(m, b, reports={}) == [
dict(start_frame=131, end_frame=176, text="陈叔以后还开吗")
]
def test_suppression_and_separate_locks_follow_source_range():
m, b, r = case()
parent = m["spec"]["dialogue"]["utterances"][0]
edit = dict(id=C, utterance_id=U, source_start=0, source_end=3, source_text=parent["text"])
m["captions"]["edits"] = [dict(edit, deleted=True)]
assert [row["text"] for row in project(m, b, r)["rows"]] == ["以后还开吗"]
m["captions"]["edits"] = [dict(edit, text_override=True, text="陈叔!")]
left, right = project(m, b, r)["rows"]
assert left["id"] == C and left["text"] == "陈叔!" and left["local_start_frame"] > 0
parent["text"] = "陈叔,陈叔,以后还开吗?"
assert project(m, b, r)["issues"]
def test_display_punctuation_preserves_semantic_tokens():
from app.domain.rhythm_captions import display_text
assert (
display_text("“8:30”,值 -3.25,型号 X-100;don't!", "hide")
== "8:30 值 -3.25 型号 X-100 don't"
)
assert display_text("等……等。", "hide") == "等等"
assert display_text("下班?", "preserve") == "下班?"
def test_real_lamp_historical_rows_and_late_speech():
root = Path(__file__).resolve().parents[2] / "outputs" / "留一盏灯_H3多人对白_20261127"
if not (root / "editor-v3.json").exists():
pytest.skip("local approved production sample is not installed")
m = json.loads((root / "editor-v3.json").read_text(encoding="utf-8-sig"))
frozen = json.loads((root / "字幕_绝对帧.json").read_text(encoding="utf-8-sig"))
assert editor_media.compile_captions(m, m["bindings"]) == frozen
m["schema_version"] = 4
m["captions"].update(presentation=STYLE.copy(), edits=[])
by_sha = {}
for path in root.glob("media/*/speech-report.json"):
r = json.loads(path.read_text(encoding="utf-8-sig"))
by_sha[r["audio_sha256"]] = r
reports = {sid: by_sha[m["bindings"]["native_audio:" + sid]["sha256"]] for sid in m["shot_ids"]}
result = project(m, m["bindings"], reports)
assert set(row["shot_id"] for row in result["rows"]) == set(m["shot_ids"])
assert not result["issues"]
first = [row for row in result["rows"] if row["shot_id"] == m["shot_ids"][0]]
assert [r["text"] for r in first] == ["陈叔", "以后不营业了吗"]
assert (
first[0]["local_start_frame"] > 48
and first[1]["local_start_frame"] - first[0]["local_end_frame"] >= 12
)
(eighth,) = [row for row in result["rows"] if row["shot_id"] == m["shot_ids"][7]]
assert eighth["text"] == "周末让我来吧" and eighth["status"] == "sentence_fallback"
assert 120 <= eighth["local_start_frame"] < eighth["local_end_frame"] <= 158
def test_single_line_recalculation_uses_only_its_shot_without_moving_it():
m, b, r = case()
result = editor_media.preview_captions(m, b, reports=r, utterance_id=U)
assert result == project(m, b, r)
assert editor_media.caption_shot_ids(m, U) == {B}
assert not editor_media.preview_captions(m, b, reports=r, utterance_id=C)["rows"]
def test_native_offsets_are_applied_once_after_trim_and_reorder():
m, b, r = case()
m["spec"]["shots"][1]["edit"].update(start_frame=4, duration_frames=120)
m["spec"]["render"]["total_frames"] = 244
before = project(m, b, r)
assert not before["issues"]
old = before["rows"][0]
assert old["start_frame"] == 128 and old["local_start_frame"] == 4
m["spec"]["shots"].reverse()
m["shot_ids"].reverse()
m["spec"]["dialogue"]["sequences"][0]["shot_ids"].reverse()
after = project(m, b, r)
assert [(row["id"], row["start_frame"] + 124) for row in after["rows"]] == [
(row["id"], row["start_frame"]) for row in before["rows"]
]
@pytest.mark.parametrize("count", [999, 1000, 1001])
def test_limit_counts_absolute_rows_and_auto_phrases_and_merges_only_same_turn(count):
m, b, r = case()
silent, speaking = m["spec"]["shots"]
intros = [dict(deepcopy(silent), id=f"{n + 7900:032x}") for n in range(9)]
m["spec"]["shots"] = [*intros, speaking]
m["shot_ids"] = [shot["id"] for shot in m["spec"]["shots"]]
m["spec"]["dialogue"]["sequences"][0]["shot_ids"] = m["shot_ids"].copy()
m["spec"]["render"]["total_frames"] = len(m["shot_ids"]) * 124
m["captions"]["cues"] = [
dict(id=f"{n + 891:032x}", anchor="absolute", start_frame=n, end_frame=n + 1, text="片名")
for n in range(count - 2)
]
result = project(m, b, r)
assert len(result["rows"]) == min(1000, count)
assert not result["issues"]
if count == 1001:
row = result["rows"][-1]
assert row["text"] == "陈叔以后还开吗" and row["utterance_id"] == U
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_text="陈叔,以后还开吗?",
source_start=0,
source_end=3,
text_override=True,
text="陈叔",
)
]
assert any(
i["code"] == "caption_limit" and i["unit_id"] == U for i in project(m, b, r)["issues"]
)
def test_two_manual_halves_can_merge_or_be_suppressed_without_automatic_revival():
m, b, r = case()
template = dict(id=C, utterance_id=U, source_text="陈叔,以后还开吗?", timing_override=True)
m["captions"]["edits"] = [
dict(template, source_start=0, source_end=3, start_frame=8, end_frame=22),
dict(template, id=A, source_start=3, source_end=9, start_frame=30, end_frame=49),
]
assert [(row["id"], row["text"]) for row in project(m, b, r)["rows"]] == [
(C, "陈叔"),
(A, "以后还开吗"),
]
m["captions"]["edits"] = [
dict(template, source_start=0, source_end=9, start_frame=8, end_frame=49)
]
assert [(row["id"], row["text"]) for row in project(m, b, r)["rows"]] == [(C, "陈叔以后还开吗")]
m["captions"]["edits"][0]["deleted"] = True
assert project(m, b, r) == dict(rows=[], issues=[])
def test_source_rewrite_ambiguous_word_map_falls_back_to_entire_utterance():
m, b, r = case()
line = m["spec"]["dialogue"]["utterances"][0]
line["spoken_text"] = line["text"]
line["text"] = "8:30,再开门。"
(row,) = project(m, b, r)["rows"]
assert (row["text"], row["status"]) == ("8:30 再开门", "sentence_fallback")
def test_protected_legacy_utterance_maps_each_lock_and_new_edit_can_unlock_timing():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
m["captions"]["cues"] = [
dict(
id=C,
anchor="utterance",
utterance_id=U,
text="人工改字!",
start_frame=1,
end_frame=6,
text_override=True,
timing_override=True,
)
]
b["native_alignment:" + B]["provenance"]["utterances"] = [
dict(utterance_id=U, start_sample=4000, end_sample=116000)
]
(row,) = project(m, b, r)["rows"]
assert row["id"] == C and row["text_override"] and row["timing_override"]
assert (row["local_start_frame"], row["local_end_frame"], row["text"]) == (3, 8, "人工改字!")
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_text=source,
source_start=0,
source_end=len(source),
text_override=True,
text=row["text"],
timing_override=False,
)
]
(edited,) = project(m, b, r)["rows"]
assert edited["text"] == "人工改字!" and not edited["timing_override"]
assert edited["local_start_frame"] > 3 and edited["local_end_frame"] > 8
def test_uncertain_turns_or_overlapping_manual_frames_cannot_be_burned():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
item = dict(
id=C,
utterance_id=U,
source_text=source,
source_start=0,
source_end=3,
timing_override=True,
start_frame=8,
end_frame=56,
)
m["captions"]["edits"] = [item]
assert any(i["code"] == "caption_overlap" for i in project(m, b, r)["issues"])
with pytest.raises(ValueError, match="重叠"):
editor_media.compile_captions(m, b, reports=r)
def test_ambiguous_old_occurrence_of_tombstone_survives_for_review():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_text="陈叔," + source,
source_start=0,
source_end=3,
deleted=True,
)
]
assert any(i["code"] == "caption_edit_conflict" for i in project(m, b, r)["issues"])
def test_accepted_two_person_audio_uses_shot_scoped_recognition_and_separate_turns():
m, b, r = case()
m["spec"]["schema_version"] = 6
d = m["spec"]["dialogue"]
first = d["utterances"][0]
second = dict(first, id="e" * 32, speaker_id=C, text="以后还开吗?")
first["text"] = "陈叔,"
d["utterances"].append(second)
d["speakers"].append(dict(d["speakers"][0], id=C, name="乙"))
d["sequences"][0]["utterance_ids"] = [U, "e" * 32]
m["spec"]["shots"][1]["performance"].update(
dialogue_staging="two_person_turns", native_utterance_ids=[U, "e" * 32]
)
r[B]["speaker_id"] = B
gate = b["native_alignment:" + B]
gate["sha256"] = "e" * 64
b["native_report:" + B] = dict(sha256=gate["sha256"])
gate["provenance"].update(
turn_decision="pass",
turn_certificate_sha256="c" * 64,
turn_report_sha256="d" * 64,
turn_report_asset_id=C,
)
projected = project(m, b, r)
assert not projected["issues"]
assert [(row["turn_id"], row["speaker_id"], row["text"]) for row in projected["rows"]] == [
(U, first["speaker_id"], "陈叔"),
("e" * 32, C, "以后还开吗"),
]
assert projected["rows"][0]["end_frame"] < projected["rows"][1]["start_frame"]
del gate["provenance"]["turn_decision"]
assert all(row["status"] == "pending" for row in project(m, b, r)["rows"])
def test_replaced_source_preserves_timing_lock_for_explicit_renewal():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
edit = dict(
id=C,
utterance_id=U,
source_text=source,
source_start=0,
source_end=len(source),
timing_override=True,
start_frame=8,
end_frame=52,
audio_sha256="e" * 64,
)
m["captions"]["edits"] = [edit]
stale = project(m, b, r)
assert stale["rows"][0]["local_start_frame"] == 8 and stale["rows"][0]["timing_override"]
assert any(i["code"] == "caption_audio_changed" for i in stale["issues"])
edit["audio_sha256"] = SHA
assert not project(m, b, r)["issues"]