286 lines
13 KiB
Python
286 lines
13 KiB
Python
"""编辑字幕投影:作者数据与最后编译的绝对帧分离。"""
|
||
|
||
from copy import deepcopy
|
||
import math
|
||
from uuid import NAMESPACE_URL, uuid5
|
||
|
||
from app.domain.timeline import Subtitle
|
||
from app.domain.continuity import compile_story_timing, supports_sample_timing
|
||
|
||
|
||
def shot_ranges(manifest):
|
||
if supports_sample_timing(manifest) and supports_sample_timing(manifest["spec"]):
|
||
timing = compile_story_timing(manifest["spec"])
|
||
return {
|
||
row["shot_id"]: (row["start_frame"], row["end_frame"]) for row in timing["shots"]
|
||
}, timing["total_frames"]
|
||
position, ranges = 0, {}
|
||
for sid, shot in zip(manifest["shot_ids"], manifest["spec"]["shots"], strict=True):
|
||
duration = shot.get("edit", {}).get("duration_frames", shot.get("duration_frames", 120))
|
||
if type(duration) is not int or duration < 1:
|
||
raise ValueError("镜头选用时长无效")
|
||
ranges[sid] = (position, position + duration)
|
||
position += duration
|
||
return ranges, position
|
||
|
||
|
||
def audio_segment_ranges(manifest, bindings):
|
||
if (
|
||
supports_sample_timing(manifest)
|
||
and manifest.get("audio", {}).get("mode") == "generated_narration"
|
||
):
|
||
from app.domain.audio_timeline import audio_sample_ranges
|
||
|
||
# 对全局样本端点各量化一次,共用端点得到同一帧,避免逐句ceil累积或重叠。
|
||
return {
|
||
key: ((start + 1000) // 2000, (end + 1000) // 2000)
|
||
for key, (start, end) in audio_sample_ranges(manifest, bindings).items()
|
||
}
|
||
if supports_sample_timing(manifest):
|
||
from app.domain.audio_timeline import _timeline, _position
|
||
|
||
shots, scenes, total = _timeline(manifest)
|
||
groups = {}
|
||
for segment in manifest.get("audio", {}).get("segments", []):
|
||
start, end = _position(segment, shots, scenes, total)
|
||
groups.setdefault((start, end), []).append(segment)
|
||
result = {}
|
||
for (start, end), segments in groups.items():
|
||
index = 0
|
||
while index < len(segments):
|
||
begin = start + segments[index].get("offset_sample", 0)
|
||
stop = index + 1
|
||
while stop < len(segments) and not segments[stop].get("offset_sample", 0):
|
||
stop += 1
|
||
limit = start + segments[stop]["offset_sample"] if stop < len(segments) else end
|
||
batch = segments[index:stop]
|
||
weights = [max(1, len(s["text"].strip())) for s in batch]
|
||
weight_sum = sum(weights)
|
||
consumed = 0
|
||
previous = (begin + 1000) // 2000
|
||
for segment, weight in zip(batch, weights):
|
||
consumed += weight
|
||
boundary = (begin + (limit - begin) * consumed // weight_sum + 1000) // 2000
|
||
if limit > end or boundary <= previous:
|
||
raise ValueError("字幕超出锚定时间范围")
|
||
result[segment["id"]] = previous, boundary
|
||
previous = boundary
|
||
index = stop
|
||
return result
|
||
ranges, _ = shot_ranges(manifest)
|
||
grouped = {sid: [] for sid in ranges}
|
||
for segment in manifest.get("audio", {}).get("segments", []):
|
||
if segment["shot_id"] not in ranges:
|
||
raise ValueError("旁白对应的镜头已删除,请删除该段或重新绑定")
|
||
grouped[segment["shot_id"]].append(segment)
|
||
output = {}
|
||
spoken = manifest.get("audio", {}).get("mode") == "generated_narration"
|
||
for sid, segments in grouped.items():
|
||
start, end = ranges[sid]
|
||
if not segments:
|
||
continue
|
||
cursor, weight = start, sum(max(1, len(s["text"].strip())) for s in segments)
|
||
consumed = 0
|
||
for segment in segments:
|
||
if spoken:
|
||
binding = bindings.get("audio:" + segment["id"], {})
|
||
if binding.get("sample_count") is not None:
|
||
duration = (int(binding["sample_count"]) + 1999) // 2000
|
||
elif binding.get("duration_frames") is not None:
|
||
duration = int(binding["duration_frames"])
|
||
elif binding.get("duration_seconds") is not None:
|
||
seconds = float(binding["duration_seconds"])
|
||
if not math.isfinite(seconds):
|
||
raise ValueError("配音时长无效")
|
||
duration = math.ceil(seconds * 24)
|
||
else:
|
||
raise ValueError("配音尚未完成,无法计算字幕时间")
|
||
target = cursor + duration
|
||
else:
|
||
consumed += max(1, len(segment["text"].strip()))
|
||
target = start + (end - start) * consumed // weight
|
||
if target <= cursor or target > end:
|
||
raise ValueError("旁白超出镜头选用时长,请调整文案、语速或镜头时长")
|
||
output[segment["id"]] = (cursor, target)
|
||
cursor = target
|
||
return output
|
||
|
||
|
||
def _dialogue_projection(manifest, bindings, prepared, *, allow_pending):
|
||
from app.domain.dialogue import has_dialogue, prepare_dialogue
|
||
|
||
captions = manifest.get("captions", {})
|
||
use_utterances = captions.get("mode") in {"script", "ai_script"} or any(
|
||
c["anchor"] == "utterance" for c in captions.get("cues", [])
|
||
)
|
||
if not has_dialogue(manifest) or not use_utterances:
|
||
return manifest, {}
|
||
lines = manifest["spec"]["dialogue"]["utterances"]
|
||
if not lines:
|
||
return manifest, {}
|
||
if prepared is None:
|
||
from app.domain.native_dialogue import enabled as native_enabled, compile_native_shots
|
||
if native_enabled(manifest):
|
||
native = compile_native_shots(manifest)
|
||
actual = []
|
||
for shot, timing in zip(native["shots"], native["timing"]["shots"], strict=True):
|
||
evidence = bindings.get("native_alignment:" + shot["shot_id"], {}).get("provenance", {})
|
||
video = bindings.get("video:" + shot["shot_id"], {})
|
||
audio = bindings.get("native_audio:" + shot["shot_id"], {})
|
||
if evidence.get("native_av_policy") != "native_av_v1" or evidence.get("video_sha256") != video.get("sha256") or evidence.get("audio_sha256") != audio.get("sha256"):
|
||
if allow_pending:
|
||
return manifest, {}
|
||
raise ValueError("原生对白逐词验收尚未就绪,无法确定字幕时间")
|
||
actual.extend({**u, "start_sample": u["start_sample"] + timing["start_frame"] * 2000,
|
||
"end_sample": u["end_sample"] + timing["start_frame"] * 2000}
|
||
for u in evidence.get("utterances", []))
|
||
prepared = dict(effective_manifest=native["manifest"], utterances=actual, issues=native["issues"])
|
||
manifest = native["manifest"]
|
||
if prepared is None:
|
||
# 某一段未测时,后续段落绝对起点也未确定;草稿保留作者覆盖,成片明确阻塞。
|
||
if any(
|
||
not u.get("text", "").strip()
|
||
or not (
|
||
bindings.get("normalized_speech:" + u["id"]) or bindings.get(u["id"]) or {}
|
||
).get("sample_count")
|
||
for u in lines
|
||
):
|
||
if allow_pending:
|
||
return manifest, {}
|
||
raise ValueError("对白台词或实测配音尚未就绪,无法确定字幕时间")
|
||
prepared = prepare_dialogue(manifest, bindings, {})
|
||
manifest = prepared["effective_manifest"]
|
||
if prepared.get("issues"):
|
||
if allow_pending:
|
||
return manifest, {}
|
||
raise ValueError(prepared["issues"][0]["message"])
|
||
ranges = {}
|
||
for u in prepared.get("utterances", []):
|
||
# 以最终24fps量化全局端点,不能用工作副本fps或单句独立四舍五入时长。
|
||
a, b = (u["start_sample"] + 1000) // 2000, (u["end_sample"] + 1000) // 2000
|
||
if b <= a:
|
||
if allow_pending:
|
||
continue
|
||
raise ValueError("实测对白不足一个字幕帧")
|
||
ranges[u["utterance_id"]] = (a, b)
|
||
if not allow_pending and any(u["id"] not in ranges for u in lines):
|
||
raise ValueError("对白配音尚未测量,无法确定字幕时间")
|
||
return manifest, ranges
|
||
|
||
|
||
def materialize_cues(manifest, bindings, *, prepared=None, allow_pending=True):
|
||
manifest, ranges = _dialogue_projection(
|
||
manifest, bindings, prepared, allow_pending=allow_pending
|
||
)
|
||
return _materialize_cues(manifest, bindings, ranges)
|
||
|
||
|
||
def _materialize_cues(manifest, bindings, utterance_ranges):
|
||
"""保留稳定字幕身份;文字和时间覆盖互相独立,不改调用者的编辑数据。"""
|
||
captions = manifest.get("captions", {})
|
||
cues = deepcopy(captions.get("cues", []))
|
||
if manifest["spec"].get("dialogue", {}).get("enabled") is False:
|
||
cues = [c for c in cues if c.get("anchor") != "utterance"]
|
||
if captions.get("mode", "none") not in {"script", "ai_script"}:
|
||
return cues
|
||
segments = manifest.get("audio", {}).get("segments", [])
|
||
known = {cue.get("segment_id"): cue for cue in cues if cue.get("segment_id")}
|
||
ranges = audio_segment_ranges(manifest, bindings) if segments else {}
|
||
for segment in segments:
|
||
sid = segment["id"]
|
||
if not segment["text"].strip():
|
||
raise ValueError("请补全旁白文案或生成自动文案")
|
||
start, end = ranges[sid]
|
||
cue = known.get(sid)
|
||
if cue is None:
|
||
cues.append(
|
||
{
|
||
"id": sid,
|
||
"anchor": "audio_segment",
|
||
"segment_id": sid,
|
||
"start_frame": 0,
|
||
"end_frame": end - start,
|
||
"text": segment["text"],
|
||
"text_override": False,
|
||
"timing_override": False,
|
||
}
|
||
)
|
||
else:
|
||
if not cue.get("text_override", False):
|
||
cue["text"] = segment["text"]
|
||
if not cue.get("timing_override", False):
|
||
cue["start_frame"], cue["end_frame"] = 0, end - start
|
||
by_line = {cue["utterance_id"]: cue for cue in cues if cue.get("utterance_id")}
|
||
by_cue_id = {cue["id"]: cue for cue in cues}
|
||
for line in manifest["spec"].get("dialogue", {}).get("utterances", []):
|
||
uid = line["id"]
|
||
if uid not in utterance_ranges:
|
||
continue
|
||
a, b = utterance_ranges[uid]
|
||
# 旧旁白与对白允许同名作者 ID;字幕 ID 使用独立且稳定的命名空间。
|
||
cue_id = uuid5(NAMESPACE_URL, f"cmvr:dialogue:caption:{uid}").hex
|
||
cue = by_line.get(uid) or by_cue_id.get(cue_id)
|
||
if cue is None:
|
||
cues.append(
|
||
dict(
|
||
id=cue_id,
|
||
anchor="utterance",
|
||
utterance_id=uid,
|
||
text=line["text"],
|
||
start_frame=0,
|
||
end_frame=b - a,
|
||
text_override=False,
|
||
timing_override=False,
|
||
)
|
||
)
|
||
else:
|
||
if not cue.get("text_override"):
|
||
cue["text"] = line["text"]
|
||
if cue["anchor"] == "utterance" and not cue.get("timing_override"):
|
||
cue.update(start_frame=0, end_frame=b - a)
|
||
return cues
|
||
|
||
|
||
def compile_captions(manifest, bindings, *, prepared=None):
|
||
if manifest.get("captions", {}).get("mode", "none") == "none":
|
||
return []
|
||
manifest, utterance_ranges = _dialogue_projection(
|
||
manifest, bindings, prepared, allow_pending=False
|
||
)
|
||
shots, total = shot_ranges(manifest)
|
||
cues = _materialize_cues(manifest, bindings, utterance_ranges)
|
||
segment_ranges = None
|
||
output = []
|
||
for cue in cues:
|
||
anchor, offset, limit = cue.get("anchor", "absolute"), 0, total
|
||
if anchor == "shot":
|
||
if cue.get("shot_id") not in shots:
|
||
raise ValueError("字幕对应的镜头已删除,请重新绑定")
|
||
offset, end = shots[cue["shot_id"]]
|
||
limit = end - offset
|
||
elif anchor == "audio_segment":
|
||
if segment_ranges is None:
|
||
segment_ranges = audio_segment_ranges(manifest, bindings)
|
||
if cue.get("segment_id") not in segment_ranges:
|
||
raise ValueError("字幕对应的音频段已删除,请重新绑定")
|
||
offset, end = segment_ranges[cue["segment_id"]]
|
||
limit = end - offset
|
||
elif anchor == "utterance":
|
||
if cue.get("utterance_id") not in utterance_ranges:
|
||
raise ValueError("字幕引用的对白缺少实测配音")
|
||
offset, end = utterance_ranges[cue["utterance_id"]]
|
||
limit = end - offset
|
||
elif anchor != "absolute":
|
||
raise ValueError("字幕时间锚点无效")
|
||
a, b = cue["start_frame"], cue["end_frame"]
|
||
if type(a) is not int or type(b) is not int or a < 0 or b <= a or b > limit:
|
||
raise ValueError("字幕时间越界,请调整后再成片")
|
||
try:
|
||
row = Subtitle(start_frame=offset + a, end_frame=offset + b, text=cue["text"])
|
||
except ValueError as exc:
|
||
raise ValueError("字幕文字为空或含不支持的控制字符") from exc
|
||
output.append(row.model_dump())
|
||
if len(output) > 1000:
|
||
raise ValueError("字幕数量超过1000条")
|
||
return sorted(output, key=lambda row: (row["start_frame"], row["end_frame"]))
|