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

383 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""编辑字幕投影:作者数据与最后编译的绝对帧分离。"""
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 captions_manual(cue):
return cue.get("anchor") not in {"utterance", "audio_segment"} or (
cue.get("text_override") or cue.get("timing_override")
)
def _legacy_rows(manifest, bindings, *, prepared=None, limit_count=True):
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
sid = cue.get("shot_id") or next(
(sid for sid, (left, right) in shots.items() if left <= offset + a < right), None
)
shot_start = shots[sid][0] if sid else 0
output.append(
dict(
**row.model_dump(),
id=cue["id"],
utterance_id=cue.get("utterance_id"),
turn_id=cue.get("utterance_id"),
shot_id=sid,
source_text=cue["text"],
source_start=0,
source_end=len(cue["text"]),
local_start_frame=offset + a - shot_start,
local_end_frame=offset + b - shot_start,
text_override=cue.get("text_override", False),
timing_override=cue.get("timing_override", False),
status="manual" if captions_manual(cue) else "automatic",
algorithm_version="legacy",
)
)
if limit_count and len(output) > 1000:
raise ValueError("字幕数量超过1000条")
return sorted(output, key=lambda row: (row["start_frame"], row["end_frame"]))
def assigned_utterance_ids(shot, sequences):
perf = shot.get("performance") or {}
ids = perf.get("native_utterance_ids")
if ids is not None:
return ids
seq = sequences.get(perf.get("sequence_id"), {})
return seq.get("utterance_ids", []) if len(seq.get("shot_ids", [])) == 1 else []
def caption_shot_ids(manifest, utterance_id):
spec = manifest["spec"]
sequences = {s["id"]: s for s in spec.get("dialogue", {}).get("sequences", [])}
return {
shot["id"]
for shot in spec["shots"]
if utterance_id in assigned_utterance_ids(shot, sequences)
}
def preview_captions(manifest, bindings, *, reports=None, prepared=None, utterance_id=None):
"""所有使用者读取同一份按全片帧排序的显示表;草稿保留待校时行。"""
captions = manifest.get("captions", {})
if captions.get("mode", "none") == "none":
return dict(rows=[], issues=[])
if captions.get("presentation"):
from app.services.rhythm_projection import project_captions
return project_captions(
manifest, bindings, reports or {}, prepared, utterance_id=utterance_id
)
try:
rows = _legacy_rows(manifest, bindings, prepared=prepared)
if utterance_id is not None:
rows = [r for r in rows if r["utterance_id"] == utterance_id]
return dict(rows=rows, issues=[])
except ValueError as exc:
return dict(
rows=[],
issues=[dict(code="caption_timing_pending", unit_id="captions", message=str(exc))],
)
def compile_captions(manifest, bindings, *, prepared=None, reports=None):
result = preview_captions(manifest, bindings, reports=reports, prepared=prepared)
return rendered_cues(result)
def rendered_cues(result):
if result["issues"]:
issue = result["issues"][0]
raise ValueError(f"{issue['message']}({issue['unit_id']})")
return [
{key: row[key] for key in ("start_frame", "end_frame", "text")} for row in result["rows"]
]