cmvr-visual/backend/app/services/editor_media.py

179 lines
8.0 KiB
Python
Raw Normal View History

"""编辑字幕投影:作者数据与最后编译的绝对帧分离。"""
from copy import deepcopy
import math
from app.domain.timeline import Subtitle
def shot_ranges(manifest):
if manifest.get("schema_version") == 2 and manifest["spec"].get("schema_version") == 4:
from app.domain.continuity import compile_story_timing
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 (
manifest.get("schema_version") == 2
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 manifest.get("schema_version") == 2:
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 materialize_cues(manifest, bindings):
"""保留稳定字幕身份;文字和时间覆盖互相独立,不改调用者的编辑数据。"""
captions = manifest.get("captions", {})
cues = deepcopy(captions.get("cues", []))
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)
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
return cues
def compile_captions(manifest, bindings):
if manifest.get("captions", {}).get("mode", "none") == "none":
return []
shots, total = shot_ranges(manifest)
cues = materialize_cues(manifest, bindings)
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 != "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"]))