cmvr-visual/backend/app/services/editor_media.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

130 lines
5.6 KiB
Python

"""编辑字幕投影:作者数据与最后编译的绝对帧分离。"""
from copy import deepcopy
import math
from app.domain.timeline import Subtitle
def shot_ranges(manifest):
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):
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"]))