282 lines
11 KiB
Python
282 lines
11 KiB
Python
"""编辑真源转换和时间冲突报告,不访问数据库。"""
|
|
|
|
from copy import deepcopy
|
|
import re
|
|
import uuid
|
|
from pydantic import ValidationError
|
|
from app.schemas.editors import parse_editor_manifest
|
|
from app.domain.timeline import WorkflowSpec
|
|
from app.domain.stories import parse_story_spec
|
|
from app.core.errors import fail
|
|
|
|
|
|
def validate_manifest(manifest):
|
|
try:
|
|
m = parse_editor_manifest(manifest).model_dump(mode="json")
|
|
raw = deepcopy(m["spec"])
|
|
raw.pop("compiled", None)
|
|
raw.setdefault("render", {}).update(audio=None, subtitles=[], total_frames=None)
|
|
parse = parse_story_spec if m["source_kind"] == "story" else WorkflowSpec.model_validate
|
|
m["spec"] = parse(raw).model_dump(mode="json")
|
|
if raw.get("schema_version") == 4 and m["schema_version"] != 2:
|
|
raise ValueError("V4 story requires V2 editor")
|
|
if (raw.get("schema_version") in (5, 6)) != (m["schema_version"] in (3, 4)):
|
|
raise ValueError("dialogue story requires dialogue editor")
|
|
if raw.get("schema_version") == 6 and m["schema_version"] != 4:
|
|
raise ValueError("V6 story requires V4 editor")
|
|
ids = m["shot_ids"]
|
|
if (
|
|
len(ids) != len(m["spec"]["shots"])
|
|
or len(set(ids)) != len(ids)
|
|
or any(not re.fullmatch("[0-9a-f]{32}", i) for i in ids)
|
|
):
|
|
raise ValueError("shot_ids must match ordered shots")
|
|
if m["source_kind"] == "story" and ids != [s["id"] for s in m["spec"]["shots"]]:
|
|
raise ValueError("story shot_ids mismatch")
|
|
for group in (m["audio"]["segments"], m["captions"]["cues"]):
|
|
if len({x["id"] for x in group}) != len(group):
|
|
raise ValueError("duplicate stable id")
|
|
roles = {"frame": "image", "video": "video"}
|
|
if m["schema_version"] in (2, 3, 4):
|
|
roles.update(end_frame="image", join_anchor="image")
|
|
if m["schema_version"] in (3, 4):
|
|
roles.update(
|
|
original_audio="audio",
|
|
base_video="video",
|
|
selected_video="video",
|
|
synced_video="video",
|
|
face_tracks="json",
|
|
dialogue_report="json",
|
|
native_audio="audio",
|
|
native_report="json",
|
|
native_alignment="json",
|
|
)
|
|
valid_keys = {f"{role}:{sid}" for role in roles for sid in ids}
|
|
valid_keys.update("audio:" + x["id"] for x in m["audio"]["segments"])
|
|
if m["schema_version"] in (3, 4):
|
|
from app.domain.dialogue import speech_stem_id
|
|
|
|
dialogue = m["spec"]["dialogue"]
|
|
speakers = {u["id"]: u["speaker_id"] for u in dialogue["utterances"]}
|
|
lines = speakers.keys()
|
|
if any(e["utterance_id"] not in lines for e in m["captions"].get("edits", [])):
|
|
raise ValueError("字幕编辑对应的父台词不存在")
|
|
roles["speech_stem"] = "audio"
|
|
if any(key.startswith("speech_stem:") for key in m["bindings"]):
|
|
for seq in dialogue["sequences"]:
|
|
talkers = {speakers[uid] for uid in seq["utterance_ids"]}
|
|
valid_keys.update(
|
|
"speech_stem:" + speech_stem_id(sid, who)
|
|
for sid in seq["shot_ids"]
|
|
for who in talkers
|
|
)
|
|
roles["speech_report"] = "json"
|
|
valid_keys.update("speech_report:" + uid for uid in lines)
|
|
for role in ("speech", "normalized_speech"):
|
|
roles[role] = "audio"
|
|
valid_keys.update(f"{role}:{uid}" for uid in lines)
|
|
for cue in m["captions"]["cues"]:
|
|
if cue["anchor"] == "utterance" and cue["utterance_id"] not in lines:
|
|
raise ValueError("unknown utterance caption anchor")
|
|
if set(m["bindings"]) - valid_keys:
|
|
raise ValueError("unknown binding key")
|
|
roles["audio"] = "audio"
|
|
for key, binding in m["bindings"].items():
|
|
if binding["kind"] != roles[key.split(":")[0]]:
|
|
raise ValueError("wrong binding kind")
|
|
return m
|
|
except (ValidationError, ValueError, TypeError, KeyError) as exc:
|
|
fail(422, "invalid_editor_manifest", str(exc))
|
|
|
|
|
|
def manifest_from_draft(draft):
|
|
if draft.editor_manifest:
|
|
return deepcopy(draft.editor_manifest)
|
|
spec = deepcopy(draft.spec)
|
|
spec.pop("compiled", None)
|
|
spec.pop("render_inputs", None)
|
|
story = draft.kind == "story_v3"
|
|
ids = [
|
|
s["id"] if story else uuid.uuid5(uuid.NAMESPACE_URL, f"editor:{draft.id}:{s['key']}").hex
|
|
for s in spec["shots"]
|
|
]
|
|
old = spec.get("render", {})
|
|
audio = {
|
|
"mode": "manual_track" if old.get("audio") else "silent",
|
|
"voice": "",
|
|
"speed": 1.0,
|
|
"track": old.get("audio"),
|
|
"segments": [
|
|
{
|
|
"id": uuid.uuid5(uuid.NAMESPACE_URL, f"segment:{draft.id}:{id}").hex,
|
|
"shot_id": id,
|
|
"text": "",
|
|
}
|
|
for id in ids
|
|
],
|
|
}
|
|
dialogue_story = story and spec.get("schema_version") in (5, 6)
|
|
if dialogue_story:
|
|
audio["segments"] = []
|
|
audio["mix_mode"] = "manual_mix" if old.get("audio") else "composed"
|
|
cues = [
|
|
dict(
|
|
id=uuid.uuid5(uuid.NAMESPACE_URL, f"cue:{draft.id}:{i}").hex,
|
|
anchor="absolute",
|
|
text_override=True,
|
|
timing_override=True,
|
|
**c,
|
|
)
|
|
for i, c in enumerate(old.get("subtitles", []))
|
|
]
|
|
return validate_manifest(
|
|
dict(
|
|
schema_version={4: 2, 5: 3, 6: 4}.get(spec.get("schema_version"), 1) if story else 1,
|
|
source_kind="story" if story else "workflow",
|
|
editing_mode="manual" if dialogue_story else "auto",
|
|
spec=spec,
|
|
shot_ids=ids,
|
|
bindings={},
|
|
audio=audio,
|
|
captions={"mode": "manual" if cues else "none", "cues": cues},
|
|
)
|
|
)
|
|
|
|
|
|
def apply_birth_captions(draft, manifest):
|
|
"""仅消费创建事务保存的作者选择;历史草稿一直为空。"""
|
|
intent = draft.caption_birth_intent
|
|
dialogue = manifest["spec"].get("dialogue") or {}
|
|
if not intent or not dialogue.get("enabled") or dialogue.get("generation") != "native_av":
|
|
return False
|
|
draft.caption_birth_intent = None
|
|
caps = manifest["captions"]
|
|
if caps.get("mode") == "manual" or caps.get("presentation"):
|
|
return False
|
|
if intent["mode"] in {"none", "manual"}:
|
|
caps["mode"] = intent["mode"]
|
|
return True
|
|
if (dialogue.get("language") or "Chinese") != "Chinese":
|
|
caps["mode"] = intent["mode"]
|
|
return True
|
|
manifest["schema_version"] = 4
|
|
caps.update(mode=intent["mode"], presentation=intent["presentation"], edits=[])
|
|
return True
|
|
|
|
|
|
def editor_issues(manifest):
|
|
m = manifest
|
|
shots = {
|
|
id: s.get("edit", {}).get("duration_frames", s.get("duration_frames", 120))
|
|
for id, s in zip(m["shot_ids"], m["spec"]["shots"])
|
|
}
|
|
if m["spec"].get("schema_version") in (4, 5, 6):
|
|
from app.domain.continuity import compile_story_timing
|
|
|
|
shots = {
|
|
row["shot_id"]: row["contribution_frames"]
|
|
for row in compile_story_timing(m["spec"])["shots"]
|
|
}
|
|
total = sum(shots.values())
|
|
segments = {s["id"]: s for s in m["audio"]["segments"]}
|
|
issues = []
|
|
|
|
def issue(code, id, message):
|
|
issues.append(dict(code=code, unit_id=id, message=message))
|
|
|
|
dialogue = m["spec"].get("dialogue", {})
|
|
if (
|
|
dialogue.get("enabled")
|
|
and dialogue["utterances"]
|
|
and (m["audio"].get("mix_mode") == "manual_mix" or m["audio"]["mode"] == "manual_track")
|
|
):
|
|
issue("manual_mix_conflict", "audio", "自动对白与手工混音互斥")
|
|
for s in segments.values():
|
|
if s.get("anchor", "shot") == "shot" and s["shot_id"] not in shots:
|
|
issue("orphan_audio_segment", s["id"], "配音段引用的镜头不存在")
|
|
for c in m["captions"]["cues"]:
|
|
limit = total
|
|
if c["anchor"] == "shot":
|
|
limit = shots.get(c["shot_id"])
|
|
elif c["anchor"] == "audio_segment":
|
|
segment = segments.get(c["segment_id"])
|
|
limit = shots.get(segment.get("shot_id")) if segment else None
|
|
if segment and segment.get("anchor", "shot") != "shot":
|
|
limit = total
|
|
elif c["anchor"] == "utterance":
|
|
# 实测音频产生后才知道句内字幕上限。
|
|
if c["start_frame"] >= 0 and c["end_frame"] > c["start_frame"]:
|
|
continue
|
|
if limit is None:
|
|
issue("orphan_caption_anchor", c["id"], "字幕锚点不存在")
|
|
elif c["start_frame"] < 0 or c["end_frame"] <= c["start_frame"] or c["end_frame"] > limit:
|
|
issue("invalid_timeline", c["id"], "字幕时间超出锚点范围")
|
|
a = m["audio"].get("track")
|
|
if m["audio"]["mode"] == "manual_track":
|
|
if not a:
|
|
issue("missing_audio_track", "audio", "请选择音轨")
|
|
elif "source_end_sample" in a:
|
|
if (
|
|
a["offset_sample"] + a["source_end_sample"] - a["source_start_sample"]
|
|
> total * 2000
|
|
):
|
|
issue("invalid_timeline", "audio", "音轨超出成片范围")
|
|
elif a["offset_frame"] + (a["source_end_ms"] - a["source_start_ms"]) * 24 / 1000 > total:
|
|
issue("invalid_timeline", "audio", "音轨超出成片范围")
|
|
return issues
|
|
|
|
|
|
def collect_manifest_asset_ids(manifest):
|
|
result = set()
|
|
|
|
def visit(value):
|
|
if isinstance(value, dict):
|
|
for k, v in value.items():
|
|
if k.endswith("asset_id") and isinstance(v, str):
|
|
result.add(v)
|
|
elif k.endswith("asset_ids") and isinstance(v, list):
|
|
result.update(v)
|
|
else:
|
|
visit(v)
|
|
elif isinstance(value, list):
|
|
for item in value:
|
|
visit(item)
|
|
|
|
visit(manifest)
|
|
return result
|
|
|
|
|
|
def editing_mode(draft):
|
|
return (
|
|
(draft.editor_manifest or {}).get("editing_mode", "auto")
|
|
if draft.editor_manifest
|
|
else "manual"
|
|
)
|
|
|
|
|
|
def is_editor_auto(draft):
|
|
return bool(draft.editor_manifest) and editing_mode(draft) == "auto"
|
|
|
|
|
|
MODE_CAPABILITIES = {"mode_switch": True, "manual": True, "auto": True, "name_edit": True}
|
|
|
|
|
|
def invalidate_join_anchors(manifest, previous):
|
|
"""Discard derived frames whose source binding or selected trim changed."""
|
|
if manifest.get("schema_version") not in (2, 3, 4):
|
|
return
|
|
|
|
def sources(m):
|
|
bindings = m.get("bindings", {})
|
|
result = {}
|
|
for sid, shot in zip(m.get("shot_ids", []), m.get("spec", {}).get("shots", [])):
|
|
video = bindings.get("video:" + sid, {})
|
|
result[sid] = (video.get("asset_id"), video.get("sha256"), shot.get("edit", {}))
|
|
return result
|
|
|
|
before, after = sources(previous), sources(manifest)
|
|
for key in list(manifest["bindings"]):
|
|
role, _, sid = key.partition(":")
|
|
if role == "join_anchor" and before.get(sid) != after.get(sid):
|
|
del manifest["bindings"][key]
|