"""编辑真源转换和时间冲突报告,不访问数据库。""" 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") 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"] == 2: roles.update(end_frame="image", join_anchor="image") 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 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 ], } 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=2 if story and spec.get("schema_version") == 4 else 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"]) } if m["spec"].get("schema_version") == 4: 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)) 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 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") != 2: 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]