"""预览同框转切镜,确认后以独立故事保存,原候选仍归原故事。""" from copy import deepcopy from uuid import NAMESPACE_URL, uuid5 from app.core.errors import fail from app.core.maintenance import require_writable from app.domain.dialogue import speech_stem_id from app.domain.native_dialogue import compile_native_shots from app.models import WorkflowDraft from app.services.auth import require_session_user from app.services.editors import check_version, dto, load_manifest, write_manifest from app.services.snapshots import owned from app.services.submissions import accept_submission, request_payload def project_cuts(manifest, shot_id, name): m = deepcopy(manifest) spec = m["spec"] if spec.get("schema_version") != 6 or shot_id not in m["shot_ids"]: fail(422, "invalid_turn_shot", "请选择同框双人镜头") index = m["shot_ids"].index(shot_id) original = spec["shots"][index] perf = original["performance"] ids = perf.get("native_utterance_ids") or [] all_lines = {u["id"]: u for u in spec["dialogue"]["utterances"]} roles = {s["id"]: s for s in spec["dialogue"]["speakers"]} lines = [all_lines[uid] for uid in ids if uid in all_lines] if ( perf.get("dialogue_staging") != "two_person_turns" or len(lines) != 2 or len({u["speaker_id"] for u in lines}) != 2 or len(ids) != 2 ): fail(422, "invalid_turn_shot", "需要两位角色按顺序各说一句,才能预览切镜") sequence = next( ( s for s in spec["dialogue"]["sequences"] if s["id"] == perf.get("sequence_id") and shot_id in s["shot_ids"] ), None, ) if not sequence or any(uid not in sequence["utterance_ids"] for uid in ids): fail(422, "invalid_turn_shot", "台词不属于镜头段落") warnings = [ "副本需要为两位角色各生成一张单人首帧和一段原声视频,重做本镜对白检查及后续混音、成片。" ] locks = ["structure_locked"] if perf.get("structure_locked") else [] old_entities = {e["id"]: e for e in spec["entities"]} # 保留第一镜的稳定编号,使旧的镜头局部锚仍可回看、核对;台词锚继续引用原始台词 ID。 new_id = uuid5(NAMESPACE_URL, f"cmvr:cut:{shot_id}:{ids[1]}").hex if new_id in m["shot_ids"]: fail(409, "cut_id_conflict", "副本中已存在同一次切镜的镜头编号") new_shots = [] for i, line in enumerate(lines): role = roles[line["speaker_id"]] s = deepcopy(original) s["id"] = shot_id if i == 0 else new_id s["name"] = f"{original.get('name') or '对白'} · {role['name']}" s["cast"] = [ c for c in s["cast"] if c["entity_id"] == role["entity_id"] or old_entities[c["entity_id"]]["kind"] != "person" ] if not any(c["entity_id"] == role["entity_id"] for c in s["cast"]): fail(422, "invalid_turn_cast", "说话人须出现在原镜演员表中") for c in s["cast"]: if i: c["id"] = uuid5(NAMESPACE_URL, f"cmvr:cut-cast:{new_id}:{c['id']}").hex if c["entity_id"] == role["entity_id"]: c["position"] = "画面中央" s["visual_prompt"] = ( f"沿用本场景的地点、布光和服饰;{role['name']}的单人中近景,清晰呈现正面或四分之三侧脸。" ) s["motion_prompt"] = ( f"{role['name']}面向画外对手自然说出本句,收声后闭唇,保持眼神和轻微反应。" ) s["performance"] = { k: v for k, v in perf.items() if k not in ("dialogue_staging", "first_frame_sha256", "listener_reactions") } s["performance"].update( visible_speaker_ids=[role["id"]], native_utterance_ids=[line["id"]], lip_sync="auto", duration_mode="auto", ) s["continuity"].update(transition="cut", endpoint_mode="first_frame") s["edit"].update(start_frame=0, dedup_frames=0) new_shots.append(s) second_index = sequence["shot_ids"].index(shot_id) + 1 sequence["shot_ids"].insert(second_index, new_id) m["shot_ids"].insert(index + 1, new_id) spec["shots"][index : index + 1] = new_shots affected = {shot_id, *(speech_stem_id(shot_id, line["speaker_id"]) for line in lines)} next_join = ( "join_anchor:" + m["shot_ids"][index + 2] if index + 2 < len(m["shot_ids"]) else None ) for key, binding in list(m["bindings"].items()): if key.partition(":")[2] in affected or key == next_join: if binding.get("locked"): locks.append(key) del m["bindings"][key] if locks: warnings.append("受保护的镜头结构或选片会被替换,请先核对并解除对应锁:" + "、".join(locks)) for cue in m["captions"]["cues"]: if cue.get("shot_id") == shot_id: warnings.append(f"字幕 {cue['id']} 保留在第一镜原局部帧,请复核是否应移到第二镜。") if any(c.get("anchor") == "absolute" for c in m["captions"]["cues"]): warnings.append("全片绝对锚字幕保留原帧位,请随新时长复核。") if any( r.get("utterance_id") in ids and r.get("timing_override") for r in m["captions"].get("edits", []) ): warnings.append("两句台词的锁时记录均已保留,请在获得新原声后复核。") if any(a.get("shot_id") == shot_id for a in [*m["audio"]["segments"], *m["audio"]["layers"]]): warnings.append("原镜头锚定的音频段或配乐仍锚定第一镜,请复核覆盖区间。") m["base_run_id"] = None projection = compile_native_shots(m) derived = {r["shot_id"]: r for r in projection["shots"]} shots = [] for shot, line in zip(new_shots, lines, strict=True): frames = derived[shot["id"]]["parameters"]["num_frames"] shot["edit"]["duration_frames"] = frames shots.append( dict( speaker_id=line["speaker_id"], speaker_name=roles[line["speaker_id"]]["name"], text=line["text"], duration_frames=frames, ) ) spec["render"]["total_frames"] = sum( s["edit"]["duration_frames"] - s["edit"].get("dedup_frames", 0) for s in spec["shots"] ) warnings.extend( i["message"] for i in projection["issues"] if i["unit_id"] in {shot_id, new_id, *ids} ) if len(m["shot_ids"]) > min(60, m.get("production", {}).get("max_shots", 60)): warnings.append("新增镜头后已超过整片制作镜数上限,需调整制作计划。") return m, dict(shots=shots, warnings=list(dict.fromkeys(warnings)), name=name), locks async def fork_cuts(runtime, actor, draft_id, body, key): if body.confirm: require_writable(runtime.settings) async with runtime.db.session() as session: await require_session_user(session, actor) source = await owned(session, WorkflowDraft, draft_id, actor.id) if body.confirm: receipt = await accept_submission( session, actor.id, "editor.dialogue.fork_cuts", key, 1, dict(draft_id=draft_id, **request_payload(body)), ) if receipt.resource_json: target = await owned( session, WorkflowDraft, receipt.resource_json["draft_id"], actor.id ) return await dto(session, target) check_version(source, body.expected_version) if source.kind != "story_v3": fail(422, "invalid_turn_shot", "切镜副本仅适用于故事") name = (body.name or (source.name[:110] + " · 切镜版")).strip() if not name: fail(422, "name_required", "请输入副本名称") projected, preview, locks = project_cuts( await load_manifest(session, source), body.shot_id, name ) if not body.confirm: return preview if locks: fail(409, "cut_dependency_locked", preview["warnings"][1]) target = WorkflowDraft( owner_id=actor.id, name=name, kind=source.kind, folder_id=source.folder_id, spec=deepcopy(projected["spec"]), ) session.add(target) await session.flush() await write_manifest(session, target, projected, runtime.settings) receipt.resource_json = dict(draft_id=target.id) result = await dto(session, target) await session.commit() return result