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

344 lines
13 KiB
Python
Raw Permalink Normal View History

"""同一草稿的可逆编辑入口;模式、当前事实和保护引用在同一事务提交。"""
from copy import deepcopy
import uuid
from sqlalchemy import select, or_
from fastapi import HTTPException
from app.models import WorkflowDraft, WorkflowRun, ShotCandidate, Batch, BatchItem, Job, Execution
from app.domain.editors import invalidate_join_anchors, is_editor_auto, validate_manifest
from app.core.errors import fail
def require_auto(d):
if d.editor_manifest and not is_editor_auto(d) and d.spec.get("schema_version") not in (5, 6):
fail(409, "editor_mode_conflict", "当前为逐步骤确认,请先切换为自动成片")
def manual_spec(d, strict=False):
if d.spec.get("schema_version") in (5, 6) and strict:
fail(409, "dialogue_editor_required", "请使用对白编辑器的成片步骤")
if not d.editor_manifest or is_editor_auto(d) or d.spec.get("schema_version") in (5, 6):
return deepcopy(d.spec)
m = d.editor_manifest
raw = deepcopy(m["spec"])
raw["render"]["audio"] = (
deepcopy(m["audio"].get("track")) if m["audio"]["mode"] != "silent" else None
)
from app.services.editor_media import compile_captions
try:
raw["render"]["subtitles"] = compile_captions(m, m["bindings"])
if strict and m["audio"]["mode"] == "generated_narration" and not raw["render"]["audio"]:
fail(422, "missing_audio_track", "旁白尚未合成,请切回自动成片生成或选择人工音轨")
except HTTPException:
if strict:
raise
raw["render"]["subtitles"] = []
except ValueError as exc:
if strict:
fail(422, "invalid_timeline", str(exc))
raw["render"]["subtitles"] = []
audio = raw["render"]["audio"]
frames = raw["render"]["total_frames"]
if audio and "source_end_sample" in audio:
exceeds = (
audio["offset_sample"] + audio["source_end_sample"] - audio["source_start_sample"]
> frames * 2000
)
else:
exceeds = (
audio
and audio["offset_frame"] * 1000
+ (audio["source_end_ms"] - audio["source_start_ms"]) * 24
> frames * 1000
)
if exceeds:
if strict:
fail(422, "invalid_timeline", "音轨超出成片范围")
raw["render"]["audio"] = None
return raw
async def assert_idle(s, d):
from app.domain.tasks import RUN_TERMINAL, TERMINAL
runs = select(WorkflowRun.id).where(
WorkflowRun.owner_id == d.owner_id, WorkflowRun.draft_id == d.id
)
candidates = select(ShotCandidate.id).where(
ShotCandidate.owner_id == d.owner_id, ShotCandidate.draft_id == d.id
)
batches = select(BatchItem.batch_id).where(
or_(
BatchItem.target_id == d.id,
BatchItem.target_id.in_(candidates),
BatchItem.target_id.in_(runs),
)
)
pending_run = await s.scalar(
select(WorkflowRun.id)
.where(WorkflowRun.id.in_(runs), WorkflowRun.state.not_in(RUN_TERMINAL))
.limit(1)
)
pending_candidate = await s.scalar(
select(ShotCandidate.id)
.where(
ShotCandidate.id.in_(candidates),
ShotCandidate.deleted_at.is_(None),
ShotCandidate.state.not_in({"ready", "failed"}),
)
.limit(1)
)
pending_batch = await s.scalar(
select(Batch.id)
.where(
Batch.owner_id == d.owner_id,
Batch.id.in_(batches),
Batch.state.not_in({"succeeded", "cancelled", "completed_with_errors"}),
)
.limit(1)
)
related_jobs = select(Job.id).where(
Job.owner_id == d.owner_id,
or_(
Job.run_id.in_(runs),
Job.id.in_(select(ShotCandidate.job_id).where(ShotCandidate.id.in_(candidates))),
Job.batch_id.in_(batches),
),
)
pending_job = await s.scalar(
select(Job.id).where(Job.id.in_(related_jobs), Job.state.not_in(TERMINAL)).limit(1)
)
pending_execution = await s.scalar(
select(Execution.id)
.where(
Execution.job_id.in_(related_jobs), Execution.state.not_in({"exited", "results_ready"})
)
.limit(1)
)
if any((pending_run, pending_candidate, pending_batch, pending_job, pending_execution)):
fail(409, "mode_switch_busy", "故事仍有运行、候选或执行等待清理,请结束后再切换")
async def import_candidates(s, d, settings):
if d.kind != "story_v3":
return
from app.services.stories.common import current_hash, private_asset, add_ref, candidate_dto
from app.services.workflows import verified_output
from app.services.events import emit_asset
for key, b in d.editor_manifest["bindings"].items():
kind, sid = key.split(":", 1)
if kind not in {"frame", "video", "end_frame"}:
continue
a = await private_asset(
s, b["asset_id"], d.owner_id, "image" if kind != "video" else "video"
)
if a.sha256 != b["sha256"] or not await verified_output(a, settings):
fail(409, "asset_integrity_failed", "自动素材校验失败")
h = await current_hash(s, d, sid, kind, source_kind="manual", source_sha256=a.sha256)
existing = await s.scalar(
select(ShotCandidate).where(
ShotCandidate.owner_id == d.owner_id,
ShotCandidate.draft_id == d.id,
ShotCandidate.shot_id == sid,
ShotCandidate.kind == kind,
ShotCandidate.asset_id == a.id,
ShotCandidate.context_hash == h,
ShotCandidate.deleted_at.is_(None),
ShotCandidate.state == "ready",
)
)
if existing:
continue
from app.domain.stories import digest
provenance = deepcopy(b)
c = ShotCandidate(
owner_id=d.owner_id,
draft_id=d.id,
shot_id=sid,
kind=kind,
source_kind="manual",
state="ready",
asset_id=a.id,
asset_sha256=a.sha256,
context_hash=h,
generation_hash=digest({"editor_import": provenance, "context_hash": h}),
created_revision=d.revision,
plan_json={
"task_type": None,
"input": {},
"parameters": {},
"editor_import": provenance,
"input_snapshot": {"reference_mode": "manual", "actual_image_refs": []},
},
)
s.add(c)
await s.flush()
await add_ref(s, d, a.id, "candidate", c.id)
emit_asset(s, d.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)})
async def change_mode(runtime, actor, draft_id, body, key):
from app.core.maintenance import require_writable
from app.services.auth import require_session_user
from app.services.snapshots import owned
from app.services.submissions import accept_submission, request_payload
from app.services.editors import check_version, load_manifest, write_manifest, dto
require_writable(runtime.settings)
async with runtime.db.session() as s:
await require_session_user(s, actor)
d = await owned(s, WorkflowDraft, draft_id, actor.id)
if d.kind != "story_v3":
fail(422, "mode_not_supported", "当前仅故事支持切换逐步骤确认")
sub = await accept_submission(
s, actor.id, "editor.mode", key, 1, {"draft_id": draft_id, **request_payload(body)}
)
if not sub.resource_json:
check_version(d, body.expected_version)
await assert_idle(s, d)
m = await load_manifest(s, d)
m["editing_mode"] = body.mode
await write_manifest(s, d, m, runtime.settings)
if body.mode == "manual":
await import_candidates(s, d, runtime.settings)
sub.resource_json = {"draft_id": d.id}
result = await dto(s, d)
from app.services.stories.common import story_dto
result["story"] = await story_dto(s, d)
await s.commit()
return result
async def sync_manual_patch(s, d, new_spec):
if not d.editor_manifest or is_editor_auto(d):
return
from app.services.editors import sync_editor_refs
m = deepcopy(d.editor_manifest)
if m["schema_version"] in (3, 4) and new_spec.get("schema_version") not in (5, 6):
fail(409, "dialogue_editor_required", "请使用支持对白版本的编辑器")
baseline = manual_spec(d)
render = new_spec.get("render", {})
if render.get("audio") != baseline.get("render", {}).get("audio"):
m["audio"]["track"] = deepcopy(render.get("audio"))
m["audio"]["mode"] = "manual_track" if render.get("audio") else "silent"
if render.get("subtitles", []) != baseline.get("render", {}).get("subtitles", []):
if m["captions"].get("presentation"):
fail(409, "caption_editor_required", "请在成片页修改节奏字幕,以保留分段和人工锁定")
m["captions"]["mode"] = "manual" if render.get("subtitles") else "none"
# 对投影里没有改变的字幕保留稳定ID、锚点及人工override;只转换确实改动的条目。
from app.services.editor_media import compile_captions
originals = []
for cue in m["captions"]["cues"]:
single = deepcopy(m)
single["captions"] = {"mode": "manual", "cues": [cue]}
try:
rendered = compile_captions(single, m["bindings"])
except ValueError:
continue
if len(rendered) == 1:
originals.append((rendered[0], cue))
updated = []
for c in render.get("subtitles", []):
match = next((i for i, (rendered, _) in enumerate(originals) if rendered == c), None)
if match is not None:
updated.append(deepcopy(originals.pop(match)[1]))
else:
updated.append(
dict(
id=uuid.uuid4().hex,
anchor="absolute",
text_override=True,
timing_override=True,
**c,
)
)
m["captions"]["cues"] = updated
old_ids = dict(zip([x.get("key") for x in m["spec"]["shots"]], m["shot_ids"]))
ids = [
x["id"] if m["source_kind"] == "story" else old_ids.get(x.get("key"), uuid.uuid4().hex)
for x in new_spec["shots"]
]
removed_segments = {
x["id"]
for x in m["audio"]["segments"]
if x.get("anchor", "shot") == "shot" and x["shot_id"] not in ids
}
m["audio"]["segments"] = [x for x in m["audio"]["segments"] if x["id"] not in removed_segments]
m["captions"]["cues"] = [
c
for c in m["captions"]["cues"]
if not (
c["anchor"] == "shot"
and c.get("shot_id") not in ids
or c["anchor"] == "audio_segment"
and c.get("segment_id") in removed_segments
)
]
for segment_id in removed_segments:
m["bindings"].pop("audio:" + segment_id, None)
if new_spec.get("schema_version") == 4:
m["schema_version"] = 2
m["spec"] = deepcopy(new_spec)
m["shot_ids"] = ids
m["bindings"] = {
k: v
for k, v in m["bindings"].items()
if not k.startswith(("frame:", "video:", "end_frame:", "join_anchor:"))
or k.split(":", 1)[1] in ids
}
for sid in ids if m["schema_version"] not in (3, 4) else []:
if not any(x.get("shot_id") == sid for x in m["audio"]["segments"]):
m["audio"]["segments"].append(dict(id=uuid.uuid4().hex, shot_id=sid, text=""))
if m["schema_version"] in (3, 4):
from app.services.editors import sanitize_dialogue_bindings
lines = {u["id"] for u in m["spec"]["dialogue"]["utterances"]}
m["captions"]["cues"] = [
c
for c in m["captions"]["cues"]
if c.get("anchor") != "utterance" or c.get("utterance_id") in lines
]
sanitize_dialogue_bindings(m, d.editor_manifest)
m = validate_manifest(m)
invalidate_join_anchors(m, d.editor_manifest)
await sync_editor_refs(s, d, m)
d.editor_manifest = m
d.spec = deepcopy(m["spec"])
async def sync_manual_selection(s, d, row, asset, candidate=None):
if not d.editor_manifest or is_editor_auto(d):
return
from app.services.editors import sync_editor_refs
m = deepcopy(d.editor_manifest)
key = row.kind + ":" + row.shot_id
if asset:
provenance = (candidate.plan_json.get("editor_import") if candidate else None) or m[
"bindings"
].get(key, {})
b = (
deepcopy(provenance)
if provenance.get("asset_id") == asset.id and provenance.get("sha256") == asset.sha256
else {}
)
b.update(
asset_id=asset.id, sha256=asset.sha256, kind=asset.kind, source="manual", locked=True
)
m["bindings"][key] = b
else:
m["bindings"].pop(key, None)
if m["schema_version"] in (3, 4):
from app.services.editors import sanitize_dialogue_bindings
sanitize_dialogue_bindings(m, d.editor_manifest)
invalidate_join_anchors(m, d.editor_manifest)
await sync_editor_refs(s, d, m)
d.editor_manifest = m