Skip to content

Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。

Hear the delivery: shot clips with sound, measured line prosody

juneed9190b9cfbb
diff --git a/rea_video/audio.py b/rea_video/audio.py
index 6fc6d8c..64a0cb4 100644
--- a/rea_video/audio.py
+++ b/rea_video/audio.py
@@ -101,6 +101,12 @@ def _seg_mask(segs: list[list[float]], n: int) -> np.ndarray:
return m
+def speaks_in(audio: dict, start: float, end: float, min_s: float = 0.3) -> bool:
+ """Someone talks for at least min_s inside [start, end] (the voice segments of analyze_audio)."""
+ segs = ((audio or {}).get("voice") or {}).get("segments") or []
+ return sum(max(0.0, min(end, b) - max(start, a)) for a, b in segs) >= min_s
+
+
def _chroma(S: np.ndarray, freqs: np.ndarray) -> np.ndarray:
valid = (freqs > 60) & (freqs < 4000)
pc = (np.round(12 * np.log2(freqs[valid] / 440.0)) + 9) % 12
diff --git a/rea_video/entities.py b/rea_video/entities.py
index 857fd79..2fadacd 100644
--- a/rea_video/entities.py
+++ b/rea_video/entities.py
@@ -107,11 +107,12 @@ def script(b: dict) -> list[dict]:
turns = who.get("turns") or [] if who.get("count", 0) >= 2 else []
from .performance import delivery_at
+ heard = [ln for ln in ((b.get("speech") or {}).get("lines") or []) if isinstance(ln, dict)]
rows = []
for ln in ((w.get("narration") or {}).get("lines") or []):
if isinstance(ln, dict) and _s(ln, "text"):
rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": _s(ln, "speaker", 20), "text": _s(ln, "text", 200)})
- how = _s(ln, "delivery", 60) or delivery_at(b, ln.get("start"), ln.get("end"))
+ how = _with_measured(_s(ln, "delivery", 60) or delivery_at(b, ln.get("start"), ln.get("end")), _heard_at(heard, ln), pause=False)
if how:
rows[-1]["delivery"] = how
if turns and isinstance(ln.get("start"), (int, float)) and isinstance(ln.get("end"), (int, float)):
@@ -125,7 +126,7 @@ def script(b: dict) -> list[dict]:
for ln in ((b.get("speech") or {}).get("lines") or []): # machine transcript: below the VLM's, above segment copy
if isinstance(ln, dict) and _s(ln, "text"):
voice = _s(ln, "speaker", 8) if turns else ""
- how = delivery_at(b, ln.get("start"), ln.get("end"))
+ how = _with_measured(delivery_at(b, ln.get("start"), ln.get("end")), ln)
rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": speaker_label(b, voice) if voice else "",
"text": _s(ln, "text", 200), "source": "asr", **({"voice": voice} if voice else {}),
**({"delivery": how} if how else {})})
@@ -137,6 +138,28 @@ def script(b: dict) -> list[dict]:
return rows
+def _heard_at(heard: list[dict], ln: dict) -> dict:
+ """The transcribed line that overlaps this line most (the reader's timings are rough), or {}."""
+ a, z = ln.get("start"), ln.get("end")
+ if not isinstance(a, (int, float)) or not isinstance(z, (int, float)):
+ return {}
+ best, got = 0.0, {}
+ for h in heard:
+ if isinstance(h.get("start"), (int, float)) and isinstance(h.get("end"), (int, float)):
+ o = min(z, h["end"]) - max(a, h["start"])
+ if o > best and o >= 0.5 * (z - a):
+ best, got = o, h
+ return got
+
+
+def _with_measured(how: str, heard: dict, pause: bool = True) -> str:
+ """The reader's delivery plus what was measured on the line (rate, pitch, loudness, pause, heard emotion)."""
+ from .prosody import describe
+
+ got = describe(heard.get("prosody"), heard.get("emotion", ""), pause=pause)
+ return semi().join(x for x in (how, got) if x)
+
+
def open_questions(b: dict) -> list[str]:
"""What a reader should verify by eye / ear, collected from every part of the breakdown. Ordered: picture, material, audio, packaging."""
q: list[str] = []
diff --git a/rea_video/performance.py b/rea_video/performance.py
index d75fbf1..bc7c681 100644
--- a/rea_video/performance.py
+++ b/rea_video/performance.py
@@ -29,7 +29,7 @@ GUIDE = """画面里有人物、动物、卡通角色或数字人在表演(脸
- face:看得见的面部动作,不写情绪词:眼睛(睁大、眯起、看镜头、眼神躲开、眨眼)、眉(上扬、皱起、眉心收紧)、嘴(嘴角上扬或下压、抿嘴、张嘴)、脸颊和下巴
- body:头、肩、手、姿态、呼吸(点头、歪头、耸肩、手捂嘴、身体前倾、深吸一口气)
- arc:镜头里情绪有变化时按秒写,t 是相对镜头开头的秒:[{"t": 0.0, "state": "这一刻看得见的表情和动作"}];没变化写 []
-- voice:画面里的角色在这一镜开口(说话、笑、叹气)时写语气、语速、音量、停顿("压低声音,语速慢,句尾带笑");画外旁白或没人开口留空
+- voice:画面里的角色在这一镜开口(说话、笑、叹气)时,按听到的写语气、语速、音量、停顿("压低声音,语速慢,句尾带笑");听不到声音时只写口型看得出的(大笑、喊),语气语速不猜;画外旁白或没人开口留空
- key:true = 表演是这一镜的看点(反应镜头、情绪爆发、反转时的表情),复刻时要专门保证
- en:把 face、body、arc 合成一句英文,只写看得见的动作,不写情绪词("eyes slightly red, corners of the mouth pressed down; at 1.5s she looks up"),给英文提示词用;上面几项已经是英文时留空"""
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 0af5e2a..f984f8e 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -10,7 +10,7 @@ import numpy as np
from . import SCHEMA, __version__
from .assets import detect_embedded, material_summary
-from .audio import analyze_audio, merge_audio_with_vlm
+from .audio import analyze_audio, merge_audio_with_vlm, speaks_in
from .sound_source import MUSIC_ZH, classify_sound_sources, per_clip_audio
from .classify import FILM_HINT_ZH, LABEL_ZH, OVERLAY_KIND_ZH, RULES, UNMEASURED, decide, deterministic, drop_scene_text, fuse, group_of, image_source_guess, overlay_layers, top, verdict_text, video_context
from .features import collect_samples, crop_box, intersect_box, photo_letterbox, shot_features
@@ -25,7 +25,7 @@ from . import aspects
from .faces import shot_faces
from .visual import LABEL_SHORT, shot_sheet, storyboard
from .i18n import T, join, semi, set_lang
-from .vlm import SHOT_PROMPT, TAKE_NOTE, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, normalize_whole, prompt_lang_note, shot_hints, take_results, vlm_note
+from .vlm import SHOT_PROMPT, SILENT_NOTE, SOUND_NOTE, TAKE_NOTE, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, normalize_whole, prompt_lang_note, shot_hints, take_results, vlm_note
def _sha256_head(path: Path, limit: int = 64 << 20) -> str:
@@ -252,16 +252,27 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
prompt = SHOT_PROMPT.format(hints=shot_hints(lead["features"], lead["deterministic"]["facts"], dl, dp))
if len(unit) > 1:
prompt += TAKE_NOTE.format(n=len(unit), cuts=", ".join(f"{r['start'] - first['start']:.2f}" for r in unit[1:]))
+ spoken = speaks_in(audio, first["start"], first["start"] + min(span, 12.0))
+ if cfg.media in ("both", "video"):
+ prompt += SOUND_NOTE if spoken else SILENT_NOTE
prompt += prompt_lang_note()
fallback = None
try:
if cfg.media in ("both", "video"): # a clip that fails to encode costs this unit its video, not the run
- clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}.mp4", width=480)
+ clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}.mp4", width=480, audio=spoken)
media.insert(0, (clip, "video/mp4"))
raw = client.ask_json(prompt, media)
except Exception as exc: # keep going; deterministic result stands
raw = None
- if cfg.media == "both":
+ if spoken and cfg.media in ("both", "video"): # an endpoint that refuses a clip with sound still gets the picture
+ try:
+ clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}_mute.mp4", width=480)
+ raw = client.ask_json(prompt.replace(SOUND_NOTE, SILENT_NOTE.replace("这一段没检测到人声,", "")),
+ [(clip, "video/mp4")] + [m for m in media if m[1] != "video/mp4"])
+ fallback = "mute_clip"
+ except Exception as exc2: # noqa: BLE001
+ exc = exc2
+ if raw is None and cfg.media == "both":
try:
raw = client.ask_json(prompt, [m for m in media if m[1] != "video/mp4"])
fallback = "frames_only"
@@ -327,6 +338,17 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
source="vocals_stem" if on_stem else "mix")
else:
heard = {"ok": False, "reason": "not_installed"}
+ if heard.get("ok") and heard.get("lines"): # how each line is said, for the script and the voice-over
+ from . import prosody
+ from .media import extract_audio
+
+ try: # pitch and level only on the vocal track: music under the voice gives a wrong pitch and level
+ x = extract_audio(voice_src, 16000) if on_stem else None
+ for ln, m in zip(heard["lines"], prosody.measure(x, 16000, heard["lines"], pitch=on_stem)):
+ if m:
+ ln["prosody"] = m
+ except Exception as exc: # noqa: BLE001 an extra: the breakdown goes on without it
+ LOG.warning("line delivery measure failed: %s", str(exc)[:160])
breakdown = {
"schema": SCHEMA, "tool": {"name": "rea-video", "version": __version__}, "lang": lang,
"source": {"path": str(video), "filename": video.name, "sha256_head": _sha256_head(video), "width": info.width,
diff --git a/rea_video/prosody.py b/rea_video/prosody.py
new file mode 100644
index 0000000..5aae2cd
--- /dev/null
+++ b/rea_video/prosody.py
@@ -0,0 +1,145 @@
+"""How each line is said, measured: speaking rate, pitch movement, loudness against the other lines, the pause
+before it, and the emotion the speech recognizer hears.
+
+A reader writing "急促" or "带笑" guesses; a TTS voice needs numbers it can follow (rate, where to pause, which line
+is louder or higher). Pitch and loudness are only measured on the separated vocal track: music under the voice
+gives a wrong pitch and a wrong level. Rate and pauses come from the line timings and hold on the mix too.
+"""
+from __future__ import annotations
+
+import re
+
+import numpy as np
+
+from .i18n import LangDict, T
+
+FRAME_S, HOP_S = 0.04, 0.02
+SLOW, FAST = {"zh": 3.5, "en": 2.0}, {"zh": 6.5, "en": 3.3} # characters / words per second
+FLAT_ST, WIDE_ST = 2.5, 10.0 # pitch spread inside a line (10th to 90th percentile, semitones); voiced cartoons sit at 8-11
+SPREAD_ST = 3.0 # spread against the median line: what sets one line apart in an already lively voice
+LOUD_DB, HIGH_ST, PAUSE_S = 4.0, 2.0, 0.6 # against the median line (same speaker for pitch)
+EMOTION = LangDict({"happy": "开心", "sad": "难过", "angry": "生气", "fearful": "害怕", "surprised": "惊讶", "disgusted": "厌恶"},
+ en={"happy": "happy", "sad": "sad", "angry": "angry", "fearful": "fearful", "surprised": "surprised",
+ "disgusted": "disgusted"})
+_CJK = re.compile(r"[぀-ヿ㐀-鿿가-힯]")
+
+
+def emotion_tag(raw) -> str:
+ """SenseVoice's emotion token ("<|HAPPY|>") to a key of EMOTION; neutral and unknown give ""."""
+ s = str(raw or "").strip("<|>").lower()
+ return s if s in EMOTION else ""
+
+
+def units(text: str) -> tuple[int, str]:
+ """Spoken units in a line: characters for CJK text, words otherwise."""
+ n = len(_CJK.findall(text or ""))
+ if n:
+ return n, "zh"
+ return len(re.findall(r"[A-Za-z0-9']+", text or "")), "en"
+
+
+def _frames(x: np.ndarray, sr: int) -> tuple[np.ndarray, np.ndarray]:
+ """Per frame (pitch in Hz or 0, level in dB)."""
+ n, h = int(FRAME_S * sr), int(HOP_S * sr)
+ lo, hi = int(sr / 400), int(sr / 70)
+ f0, db = [], []
+ for s in range(0, max(0, len(x) - n), h):
+ seg = x[s:s + n] - x[s:s + n].mean()
+ rms = float(np.sqrt(np.mean(seg ** 2)))
+ db.append(20 * np.log10(rms + 1e-9))
+ ac = np.correlate(seg, seg, "full")[n - 1:]
+ if rms < 0.01 or ac[0] <= 0 or hi >= len(ac):
+ f0.append(0.0)
+ continue
+ lag = lo + int(np.argmax(ac[lo:hi]))
+ f0.append(sr / lag if ac[lag] / ac[0] > 0.45 else 0.0)
+ return np.array(f0), np.array(db)
+
+
+def measure(x: np.ndarray | None, sr: int, lines: list[dict], pitch: bool = True) -> list[dict]:
+ """One dict per line: rate (+unit), pause before, and with pitch=True (a clean vocal track) the pitch, its
+ spread and the level, each also relative to the other lines. Lines without times give {}."""
+ out: list[dict] = []
+ prev_end = None
+ for ln in lines:
+ a, z = ln.get("start"), ln.get("end")
+ if not isinstance(a, (int, float)) or not isinstance(z, (int, float)) or z - a < 0.3:
+ out.append({})
+ continue
+ n, unit = units(ln.get("text") or "")
+ m: dict = {"unit": unit}
+ if n:
+ m["rate"] = round(n / (z - a), 1)
+ if prev_end is not None and a - prev_end >= PAUSE_S:
+ m["pause_before"] = round(a - prev_end, 1)
+ prev_end = z
+ if pitch and x is not None:
+ f0, db = _frames(x[int(a * sr):int(z * sr)], sr)
+ voiced = f0[f0 > 0]
+ if len(voiced) >= 8:
+ p10, p50, p90 = np.percentile(voiced, [10, 50, 90])
+ m.update(f0_hz=round(float(p50), 1), range_st=round(float(12 * np.log2(p90 / p10)), 1))
+ if len(db):
+ m["level_db"] = round(float(np.percentile(db, 75)), 1)
+ out.append(m)
+ _relative(out, lines)
+ return out
+
+
+def _relative(ms: list[dict], lines: list[dict]) -> None:
+ """Level against the median line, pitch against the median line of the same speaker (three lines or more)."""
+ lv = [m["level_db"] for m in ms if "level_db" in m]
+ if len(lv) >= 3:
+ med = float(np.median(lv))
+ for m in ms:
+ if "level_db" in m:
+ m["level_rel"] = round(m["level_db"] - med, 1)
+ sp = [m["range_st"] for m in ms if "range_st" in m]
+ if len(sp) >= 3:
+ med = float(np.median(sp))
+ for m in ms:
+ if "range_st" in m:
+ m["range_rel_st"] = round(m["range_st"] - med, 1)
+ by: dict[str, list[float]] = {}
+ for m, ln in zip(ms, lines):
+ if "f0_hz" in m:
+ by.setdefault(str(ln.get("speaker") or ""), []).append(m["f0_hz"])
+ for m, ln in zip(ms, lines):
+ hz = by.get(str(ln.get("speaker") or ""), [])
+ if "f0_hz" in m and len(hz) >= 3:
+ m["pitch_rel_st"] = round(float(12 * np.log2(m["f0_hz"] / np.median(hz))), 1)
+
+
+def describe(m: dict | None, emotion: str = "", pause: bool = True) -> str:
+ """The measured delivery in a few words: "实测:语速快(6.8 字/秒),音调起伏大,句前停 0.8 秒;语音模型听着偏开心".
+ Only what stands out is named, except the rate, which a voice always needs."""
+ m = m or {}
+ bits = []
+ if m.get("rate"):
+ u = m.get("unit", "zh")
+ speed = (T("快", "fast") if m["rate"] > FAST[u] else T("慢", "slow") if m["rate"] < SLOW[u] else T("正常", "normal"))
+ bits.append(T("语速{s}({r} 字/秒)", "rate {s} ({r} words/s)", s=speed, r=m["rate"]) if u == "zh"
+ else T("语速{s}({r} 词/秒)", "rate {s} ({r} words/s)", s=speed, r=m["rate"]))
+ if "range_st" in m:
+ if m["range_st"] >= WIDE_ST:
+ bits.append(T("音调起伏大", "wide pitch movement"))
+ elif m["range_st"] <= FLAT_ST:
+ bits.append(T("音调平", "flat pitch"))
+ elif m.get("range_rel_st", 0) >= SPREAD_ST:
+ bits.append(T("起伏比别的句子大", "more pitch movement than the other lines"))
+ elif m.get("range_rel_st", 0) <= -SPREAD_ST:
+ bits.append(T("起伏比别的句子平", "flatter than the other lines"))
+ if m.get("pitch_rel_st", 0) >= HIGH_ST:
+ bits.append(T("比这人别的句子高", "higher than this speaker's other lines"))
+ elif m.get("pitch_rel_st", 0) <= -HIGH_ST:
+ bits.append(T("比这人别的句子低", "lower than this speaker's other lines"))
+ if m.get("level_rel", 0) >= LOUD_DB:
+ bits.append(T("比别的句子响", "louder than the other lines"))
+ elif m.get("level_rel", 0) <= -LOUD_DB:
+ bits.append(T("比别的句子轻", "quieter than the other lines"))
+ if pause and m.get("pause_before"):
+ bits.append(T("句前停 {p} 秒", "{p}s pause before", p=m["pause_before"]))
+ text = T(",", ", ").join(bits)
+ if emotion in EMOTION:
+ text += (T(";", "; ") if text else "") + T("语音模型听着偏{e}", "speech model hears {e}", e=EMOTION[emotion])
+ return T("实测:", "measured: ") + text if text else ""
diff --git a/rea_video/speech.py b/rea_video/speech.py
index c818186..6570044 100644
--- a/rea_video/speech.py
+++ b/rea_video/speech.py
@@ -23,6 +23,7 @@ from pathlib import Path
import numpy as np
from .media import extract_audio
+from .prosody import emotion_tag
from .stems import models_dir
from .util import ASR_LANGS, LOG, fetch, sha256_file
@@ -191,8 +192,8 @@ def _sentences(start: float, end: float, text: str) -> list[dict]:
return out
-def _decode(rec, samples: np.ndarray, streaming: bool) -> tuple[str, str]:
- """One spoken stretch -> (text, language heard; empty when the recognizer does not say)."""
+def _decode(rec, samples: np.ndarray, streaming: bool) -> tuple[str, str, str]:
+ """One spoken stretch -> (text, language heard, emotion heard); the last two empty when the recognizer does not say."""
st = rec.create_stream()
st.accept_waveform(SR, samples)
if streaming:
@@ -200,9 +201,10 @@ def _decode(rec, samples: np.ndarray, streaming: bool) -> tuple[str, str]:
st.input_finished()
while rec.is_ready(st):
rec.decode_stream(st)
- return (rec.get_result(st) or "").strip(), ""
+ return (rec.get_result(st) or "").strip(), "", ""
rec.decode_stream(st)
- return (st.result.text or "").strip(), str(getattr(st.result, "lang", "") or "").strip("<|>")
+ return ((st.result.text or "").strip(), str(getattr(st.result, "lang", "") or "").strip("<|>"),
+ emotion_tag(getattr(st.result, "emotion", "")))
def transcribe(audio: str | Path, language: str | None = None, threads: int = 2, turns: list[dict] | None = None) -> dict:
@@ -233,7 +235,7 @@ def transcribe(audio: str | Path, language: str | None = None, threads: int = 2,
engine = "sensevoice-small-int8 (sherpa-onnx)"
lines, langs = [], []
for start, samples in _by_speaker(_stretches(x, vad_model), turns):
- text, heard = _decode(rec, samples, streaming=lang == "bn")
+ text, heard, emotion = _decode(rec, samples, streaming=lang == "bn")
if len(text.strip("。,、!?.,!? ")) < 1:
continue
got = _sentences(start, start + len(samples) / SR, text)
@@ -242,6 +244,8 @@ def transcribe(audio: str | Path, language: str | None = None, threads: int = 2,
who = speaker_at(turns, start, start + len(samples) / SR)
got = [dict(ln, speaker=who) for ln in got] if who else got
+ if emotion: # SenseVoice hears it per stretch; every sentence cut from the stretch shares it
+ got = [dict(ln, emotion=emotion) for ln in got]
lines += got
if heard:
langs.append(heard)
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index 21d19ba..4c5f3ec 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -359,6 +359,10 @@ AI 仿定格风格(材质在帧间漂移)与真正的定格动画(同一
# appended to SHOT_PROMPT when one clip covers several jump-cut pieces of the same take
+# which clip the shot pass gets: with its sound when someone speaks in it, so the delivery is heard, not read off lips
+SOUND_NOTE = "\n这段片段带原声:performance.voice 按听到的写(语气、语速、音量、停顿、句尾上扬还是下沉),不要只看口型猜。\n"
+SILENT_NOTE = "\n这一段没检测到人声,片段不带声音:performance.voice 留空。\n"
+
TAKE_NOTE = """
这段片子是同一机位、同一条素材剪成的 {n} 段(跳剪),后面几段从片段开头后 {cuts} 秒开始。
制作方式、拍法和素材(label_probs、aspects、embedded_assets 等)对整段给一次即可;
diff --git a/tests/test_prosody.py b/tests/test_prosody.py
new file mode 100644
index 0000000..5860971
--- /dev/null
+++ b/tests/test_prosody.py
@@ -0,0 +1,51 @@
+"""Measured delivery per line: rate, pitch, loudness, pauses and the emotion the recognizer hears, merged into the script."""
+import numpy as np
+
+from rea_video import prosody
+from rea_video.audio import speaks_in
+from rea_video.entities import script
+from rea_video.i18n import set_lang
+
+SR = 16000
+
+
+def _tone(hz: float, s: float, amp: float = 0.3) -> np.ndarray:
+ return (amp * np.sin(2 * np.pi * hz * np.arange(int(s * SR)) / SR)).astype(np.float32)
+
+
+def test_measure_rate_pitch_level_and_pause():
+ x = np.concatenate([_tone(200, 1.0), np.zeros(SR, np.float32), _tone(200, 1.0), _tone(320, 1.0, 0.9)])
+ lines = [{"start": 0.0, "end": 1.0, "text": "你好你好你好", "speaker": "A"},
+ {"start": 2.0, "end": 3.0, "text": "还好", "speaker": "A"},
+ {"start": 3.0, "end": 4.0, "text": "one two three four", "speaker": "A"}]
+ m = prosody.measure(x, SR, lines)
+ assert m[0]["rate"] == 6.0 and m[1]["rate"] == 2.0 and m[2]["unit"] == "en" and m[2]["rate"] == 4.0
+ assert abs(m[0]["f0_hz"] - 200) < 5 and m[0]["range_st"] < 1
+ assert m[1]["pause_before"] == 1.0 and "pause_before" not in m[2]
+ assert m[2]["pitch_rel_st"] >= 7 and m[2]["level_rel"] >= 8 # the high, loud line stands out
+ assert prosody.measure(None, SR, lines, pitch=False)[0] == {"unit": "zh", "rate": 6.0} # the mix: timings only
+
+
+def test_describe_names_what_stands_out():
+ set_lang("zh")
+ got = prosody.describe({"unit": "zh", "rate": 7.1, "pitch_rel_st": -7.2, "pause_before": 0.8, "range_st": 6.0}, "angry")
+ assert got == "实测:语速快(7.1 字/秒),比这人别的句子低,句前停 0.8 秒;语音模型听着偏生气"
+ assert "句前停" not in prosody.describe({"unit": "zh", "rate": 5.0, "pause_before": 0.8}, pause=False)
+ assert prosody.describe({}, "") == ""
+ assert prosody.emotion_tag("<|HAPPY|>") == "happy" and prosody.emotion_tag("<|NEUTRAL|>") == "" and prosody.emotion_tag(None) == ""
+
+
+def test_script_carries_the_measured_delivery():
+ set_lang("zh")
+ heard = [{"start": 0.1, "end": 3.0, "text": "你信不信", "emotion": "happy",
+ "prosody": {"unit": "zh", "rate": 7.0, "pause_before": 1.0}}]
+ b = {"shots": [], "speech": {"ok": True, "lines": heard}}
+ assert script(b)[0]["delivery"] == "实测:语速快(7.0 字/秒),句前停 1.0 秒;语音模型听着偏开心"
+ # a reader's line borrows the measure of the transcribed line under it; its own rough timing gives no pause
+ b["whole_video_vlm"] = {"narration": {"lines": [{"start": 0.3, "end": 2.8, "text": "你信不信", "delivery": "挑衅"}]}}
+ assert script(b)[0]["delivery"] == "挑衅;实测:语速快(7.0 字/秒);语音模型听着偏开心"
+
+
+def test_shot_clip_gets_sound_only_where_someone_speaks():
+ audio = {"voice": {"segments": [[1.0, 2.0]]}}
+ assert speaks_in(audio, 0.0, 1.5) and not speaks_in(audio, 1.9, 4.0) and not speaks_in({"has_audio": False}, 0, 9)