cmvr-visual/backend/app/domain/editors.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

166 lines
5.7 KiB
Python

"""编辑真源转换和时间冲突报告,不访问数据库。"""
from copy import deepcopy
import re
import uuid
from pydantic import ValidationError
from app.schemas.editors import EditorManifest
from app.domain.timeline import WorkflowSpec
from app.domain.stories import StorySpecV3
from app.core.errors import fail
def validate_manifest(manifest):
try:
m = EditorManifest.model_validate(manifest).model_dump(mode="json")
raw = deepcopy(m["spec"])
raw.pop("compiled", None)
raw.setdefault("render", {}).update(audio=None, subtitles=[], total_frames=None)
model = StorySpecV3 if m["source_kind"] == "story" else WorkflowSpec
m["spec"] = model.model_validate(raw).model_dump(mode="json")
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")
valid_keys = {f"{kind}:{id}" for kind in ("frame", "video") for id in ids}
valid_keys.update("audio:" + x["id"] for x in m["audio"]["segments"])
if set(m["bindings"]) - valid_keys:
raise ValueError("unknown binding key")
for key, b in m["bindings"].items():
if (
b["kind"]
!= {"frame": "image", "video": "video", "audio": "audio"}[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
],
}
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=1,
source_kind="story" if story else "workflow",
spec=spec,
shot_ids=ids,
bindings={},
audio=audio,
captions={"mode": "manual" if cues else "none", "cues": cues},
)
)
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"])
}
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))
for s in segments.values():
if 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["shot_id"]) if segment else None
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 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}