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

675 lines
28 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""编辑命令:真实会话复核、CAS、资源引用与幂等回执在同一事务提交。"""
from copy import deepcopy
from math import ceil
from types import SimpleNamespace
from sqlalchemy import select, delete
from app.models import WorkflowDraft, WorkflowRun, WorkflowStep, Asset, AssetReference, User, utcnow
from app.core.errors import fail
from app.core.maintenance import require_writable
from app.domain.editors import (
validate_manifest,
manifest_from_draft,
editor_issues,
collect_manifest_asset_ids,
editing_mode,
MODE_CAPABILITIES,
invalidate_join_anchors,
)
from app.services.auth import require_session_user
from app.services.snapshots import owned, asset_dto, snapshot_run
from app.services.submissions import accept_submission, request_payload
async def sync_editor_refs(session, draft, manifest):
assets = {}
for id in sorted(collect_manifest_asset_ids(manifest)):
asset = await session.scalar(
select(Asset)
.where(
Asset.id == id,
Asset.owner_id == draft.owner_id,
Asset.library_scope == "private",
Asset.ready.is_(True),
Asset.deleted_at.is_(None),
)
.with_for_update()
)
if not asset:
fail(404, "asset_not_found", "素材不存在或不可访问")
assets[id] = asset
for key, b in manifest["bindings"].items():
a = assets[b["asset_id"]]
if a.kind != b["kind"]:
fail(422, "wrong_asset_kind", "绑定素材类型不正确")
b["sha256"] = a.sha256
if a.duration_seconds is not None:
b["duration_seconds"] = a.duration_seconds
b["duration_frames"] = (
ceil(a.duration_seconds * 24)
if a.kind == "audio"
else round(a.duration_seconds * 24)
)
def image_refs(value):
if isinstance(value, dict):
for key, item in value.items():
if key in {"image_asset_id", "face_reference_asset_id"} and item:
yield item
elif key == "reference_asset_ids":
yield from item
else:
yield from image_refs(item)
elif isinstance(value, list):
for item in value:
yield from image_refs(item)
if any(assets[id].kind != "image" for id in image_refs(manifest["spec"])):
fail(422, "wrong_asset_kind", "视觉参考必须为图片素材")
track = manifest["audio"].get("track")
if track and assets[track["asset_id"]].kind != "audio":
fail(422, "wrong_asset_kind", "音轨需要音频素材")
for layer in manifest["audio"].get("layers", []):
if assets[layer["asset_id"]].kind != "audio":
fail(422, "wrong_asset_kind", "背景音乐和音效需要音频素材")
dialogue = manifest["spec"].get("dialogue", {})
speech_ids = {sp["voice"].get("reference_asset_id") for sp in dialogue.get("speakers", [])}
speech_ids.update(sp.get("voice_reference_asset_id") for sp in dialogue.get("speakers", []))
speech_ids.update(u.get("asset_id") for u in dialogue.get("utterances", []))
if any(assets[aid].kind != "audio" for aid in speech_ids - {None}):
fail(422, "wrong_asset_kind", "对白录音和参考音色必须是音频素材")
# 独立草稿引用不能依赖旧 Run 的存活。
await session.execute(
delete(AssetReference).where(
AssetReference.owner_id == draft.owner_id,
AssetReference.ref_kind == "draft",
AssetReference.ref_id == draft.id,
)
)
for id in assets:
session.add(
AssetReference(owner_id=draft.owner_id, asset_id=id, ref_kind="draft", ref_id=draft.id)
)
return assets
async def load_manifest(session, draft):
m = manifest_from_draft(draft)
if draft.editor_manifest or draft.kind != "story_v3":
return m
from app.services.stories.common import selections, current_hash, selection_source_kind
latest = await selections(session, draft)
for row in latest.values():
if not row.asset_id or row.shot_id not in m["shot_ids"]:
continue
a = await session.get(Asset, row.asset_id)
if (
not a
or a.owner_id != draft.owner_id
or a.deleted_at is not None
or not a.ready
or a.library_scope != "private"
):
continue
source_kind = await selection_source_kind(session, row)
if row.context_hash != await current_hash(
session,
draft,
row.shot_id,
row.kind,
latest=latest,
source_kind=source_kind,
source_sha256=a.sha256,
):
continue
expected = "image" if row.kind in {"frame", "end_frame", "join_anchor"} else "video"
if a.kind != expected or row.decision_json.get("asset_sha256") != a.sha256:
continue
m["bindings"][row.kind + ":" + row.shot_id] = dict(
asset_id=a.id, sha256=a.sha256, kind=a.kind, source="manual", locked=True
)
return m
async def dto(session, draft, manifest=None):
m = manifest if manifest is not None else await load_manifest(session, draft)
ids = collect_manifest_asset_ids(m)
assets = (
(
await session.scalars(
select(Asset).where(
Asset.id.in_(ids), Asset.owner_id == draft.owner_id, Asset.deleted_at.is_(None)
)
)
).all()
if ids
else []
)
return dict(
draft_id=draft.id,
editing_mode=editing_mode(draft),
capabilities={
**MODE_CAPABILITIES,
"mode_switch": draft.kind == "story_v3",
"manual": draft.kind == "story_v3",
},
name=draft.name,
version=draft.version,
revision=draft.revision,
manifest=m,
issues=editor_issues(m),
assets=[asset_dto(a) for a in assets],
)
def check_version(draft, version):
if draft.version != version:
fail(409, "draft_version_conflict", "草稿已更新,请刷新版本")
async def write_manifest(session, draft, manifest, settings=None):
if draft.spec.get("schema_version") in (5, 6) and manifest.get("schema_version") not in (3, 4):
fail(409, "dialogue_editor_required", "请使用支持对白的编辑器保存")
m = validate_manifest(manifest)
if settings:
from app.core.runtime_policy import read_runtime_policy
policy = read_runtime_policy(settings)
if policy.get("configuration_error"):
fail(503, "runtime_policy_unavailable", "运行配置无效")
if len(m["shot_ids"]) > policy["workflow_max_shots"]:
fail(422, "workflow_shot_limit", "镜头数量超过当前限制")
if (m["source_kind"] == "story") != (draft.kind == "story_v3"):
fail(422, "invalid_editor_manifest", "草稿类型不能改变")
# 来源只作谱系,允许已经归档的同草稿历史,绝不能跨owner/draft扩大可读范围。
if m.get("base_run_id"):
source = await session.scalar(
select(WorkflowRun.id).where(
WorkflowRun.id == m["base_run_id"],
WorkflowRun.owner_id == draft.owner_id,
WorkflowRun.draft_id == draft.id,
)
)
if not source:
fail(404, "resource_not_found", "来源运行不存在或不属于此草稿")
await sync_editor_refs(session, draft, m)
draft.editor_manifest = m
draft.spec = deepcopy(m["spec"])
draft.version += 1
draft.revision += 1
draft.updated_at = utcnow()
await session.flush()
from app.services.events import emit_asset
if draft.kind == "story_v3":
from app.services.stories.common import story_dto
emit_asset(
session, draft.owner_id, "story.updated", {"story": await story_dto(session, draft)}
)
else:
from app.services.snapshots import draft_dto
emit_asset(session, draft.owner_id, "draft.updated", {"draft": draft_dto(draft)})
async def get_editor(runtime, actor, draft_id):
async with runtime.db.session() as s:
d = await owned(s, WorkflowDraft, draft_id, actor.id)
return await dto(s, d)
DIALOGUE_DERIVED = {
"speech",
"normalized_speech",
"base_video",
"selected_video",
"synced_video",
"face_tracks",
"original_audio",
"speech_stem",
"speech_report",
"dialogue_report",
"join_anchor",
"native_audio",
"native_report",
"native_alignment",
}
def sanitize_dialogue_bindings(manifest, old):
"""派生素材仅由运行选用;客户端可修改人物、台词和镜头的作者字段。"""
from app.domain.dialogue import speech_content_hash, speech_stem_id
from app.schemas.editors import BindingV2
bindings = manifest["bindings"]
previous = old.get("bindings", {})
for key, binding in bindings.items():
if key.partition(":")[0] not in DIALOGUE_DERIVED:
continue
saved = previous.get(key)
if not saved or BindingV2.model_validate(saved) != BindingV2.model_validate(binding):
fail(422, "derived_binding_readonly", "对白派生绑定仅由服务端写入")
def contents(m):
d = m["spec"].get("dialogue", {})
voices = {sp["id"]: sp["voice"] for sp in d.get("speakers", [])}
return {
u["id"]: speech_content_hash(u, voices[u["speaker_id"]], {})
for u in d.get("utterances", [])
if u["speaker_id"] in voices
}
# 先校验作者结构,旧派生键待清理后再做一次全量校验。
manifest["spec"] = validate_manifest({**manifest, "bindings": {}})["spec"]
spec = manifest["spec"]
new_content, old_content = contents(manifest), contents(old)
shots = {s["id"]: s for s in spec["shots"]}
old_shots = {s["id"]: s for s in old["spec"]["shots"]}
d = spec.get("dialogue", {})
old_d = old["spec"].get("dialogue", {})
def native_context(dialogue, shot):
performance = shot.get("performance") or {}
seq = next(
(q for q in dialogue.get("sequences", []) if q["id"] == performance.get("sequence_id")),
{},
)
utterances = {u["id"]: u for u in dialogue.get("utterances", [])}
ids = performance.get("native_utterance_ids")
inferred_sequence = None
if ids is None:
# 旧多镜段落可能早于逐镜台词分配。依赖不明确时沿用整段失效规则。
ids = seq.get("utterance_ids", [])
inferred_sequence = seq
ordered = [utterances[uid] for uid in ids if uid in utterances]
talkers = {u["speaker_id"] for u in ordered} | set(
performance.get("visible_speaker_ids", [])
)
speakers = {sp["id"]: sp for sp in dialogue.get("speakers", []) if sp["id"] in talkers}
return dict(
generation=dialogue.get("generation"),
language=dialogue.get("language"),
utterances=ordered,
speakers=speakers,
inferred_sequence=inferred_sequence,
shot=shot,
)
line_maps = [{u["id"]: u for u in x.get("utterances", [])} for x in (d, old_d)]
old_seqs = {q["id"]: q for q in old_d.get("sequences", [])}
dirty_sequences = set()
valid_stems = {}
has_stems = any(key.startswith("speech_stem:") for key in previous)
for seq in d.get("sequences", []):
seq_id = seq["id"]
if seq != old_seqs.get(seq_id) or any(
any(
line_maps[0].get(uid, {}).get(field) != line_maps[1].get(uid, {}).get(field)
for field in (
"source_start_sample",
"source_end_sample",
"speaker_id",
"gap_after_sample",
)
)
or new_content.get(uid) != old_content.get(uid)
for uid in seq["utterance_ids"]
):
dirty_sequences.add(seq_id)
if has_stems:
talkers = {
line_maps[0][uid]["speaker_id"]
for uid in seq["utterance_ids"]
if uid in line_maps[0]
}
valid_stems.update(
{speech_stem_id(sid, who): sid for sid in seq["shot_ids"] for who in talkers}
)
for key, saved in previous.items():
role, _, uid = key.partition(":")
if role not in DIALOGUE_DERIVED:
continue
if role in {"native_audio", "native_report", "native_alignment"}:
# 原声、内容证据和逐词锚点来自同次生成;作者或选段变化后不能沿用旧签名。
shot, old_shot = shots.get(uid), old_shots.get(uid)
video_key = "video:" + uid
retain = bool(shot and old_shot) and d.get("generation") == "native_av" and native_context(d, shot) == native_context(old_d, old_shot)
retain = retain and all(bindings.get(video_key, {}).get(field) == previous.get(video_key, {}).get(field) for field in ("asset_id","sha256"))
if retain:
bindings[key] = deepcopy(saved)
else:
bindings.pop(key,None)
continue
if role in {"speech", "normalized_speech", "speech_report"}:
retain = uid in new_content and (
saved.get("locked") or new_content[uid] == old_content.get(uid)
)
else:
sid = valid_stems.get(uid) if role == "speech_stem" else uid
shot = shots.get(sid, {})
previous_shot = old_shots.get(sid, {})
video_key = f"video:{sid}"
retain = bool(shot) and bindings.get(video_key, {}).get("asset_id") == previous.get(
video_key, {}
).get("asset_id")
if role != "base_video":
retain = retain and shot.get("edit") == previous_shot.get("edit")
if role in {"synced_video", "dialogue_report", "speech_stem", "join_anchor"}:
perf = shot.get("performance", {})
old_perf = previous_shot.get("performance", {})
changed = {
key
for key in perf.keys() | old_perf.keys()
if perf.get(key) != old_perf.get(key)
}
if role == "speech_stem":
changed.discard("audio_context_shift_frames")
retain = retain and not changed and perf.get("sequence_id") not in dirty_sequences
if retain:
bindings[key] = deepcopy(saved)
else:
bindings.pop(key, None)
def sanitize_bindings(manifest, old):
if manifest.get("schema_version") in (3, 4):
sanitize_dialogue_bindings(manifest, old)
if manifest.get("schema_version") == 2:
for key, binding in list(manifest["bindings"].items()):
if not key.startswith("join_anchor:"):
continue
previous = old.get("bindings", {}).get(key, {})
if previous.get("asset_id") != binding["asset_id"] or previous.get(
"sha256"
) != binding.get("sha256"):
fail(422, "derived_binding_readonly", "实际接续锚点只能由服务端从选用视频生成")
invalidate_join_anchors(manifest, old)
for key, b in manifest["bindings"].items():
if manifest.get("schema_version") in (3, 4) and key.partition(":")[0] in DIALOGUE_DERIVED:
continue
previous = old.get("bindings", {}).get(key, {})
if previous.get("asset_id") == b["asset_id"] and previous.get("sha256") == b["sha256"]:
manifest["bindings"][key] = deepcopy(previous)
manifest["bindings"][key]["locked"] = b.get("locked", False)
else:
for field in (
"input_hash",
"context_hash",
"source_run_id",
"source_job_id",
"generation_parameters",
"duration_seconds",
"duration_frames",
"sample_count",
"sample_rate",
"provenance",
):
b.pop(field, None)
b["source"] = "manual"
async def run_manifest(session, run):
if run.result_manifest:
return {**deepcopy(run.result_manifest), "base_run_id": run.id}
if run.plan_snapshot and run.plan_snapshot.get("manifest"):
return {**deepcopy(run.plan_snapshot["manifest"]), "base_run_id": run.id}
source = SimpleNamespace(
id=run.draft_id,
kind="story_v3" if run.spec_snapshot.get("schema_version") in (3, 4, 5, 6) else "three_shot",
spec=run.spec_snapshot,
editor_manifest=None,
)
m = manifest_from_draft(source)
m["base_run_id"] = run.id
for selection in run.spec_snapshot.get("render_inputs", {}).get("selections", []):
if selection.get("shot_id") not in m["shot_ids"]:
continue
a = await session.get(Asset, selection.get("asset_id"))
if not a or a.owner_id != run.owner_id or a.deleted_at is not None or not a.ready:
fail(404, "asset_not_found", "冻结运行素材不可访问")
kind = selection.get("kind")
prefix = "frame" if kind in {"frame", "image"} else "video"
m["bindings"][prefix + ":" + selection["shot_id"]] = dict(
asset_id=a.id, sha256=a.sha256, kind=a.kind, source="reused", source_run_id=run.id
)
# legacy 实际输出按冻结顺序恢复,不能读取当前草稿或选择。
steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == run.id))).all()
from app.models import Job
for index, id in enumerate(m["shot_ids"]):
shot = m["spec"]["shots"][index]
step = next((x for x in steps if x.step_key == shot.get("key", f"shot_{index + 1}")), None)
if step and step.selected_job_id:
job = await session.get(Job, step.selected_job_id)
if job and job.owner_id == run.owner_id:
from app.services.workflows import selected_output
a = await selected_output(session, job.id, run.owner_id)
if a:
m["bindings"]["video:" + id] = dict(
asset_id=a.id,
sha256=a.sha256,
kind=a.kind,
source="reused",
source_run_id=run.id,
source_job_id=job.id,
)
return m
async def apply_run_result(session, run, settings):
if run.state != "succeeded" or not run.result_manifest or run.desired_state == "cancel":
return False
owner = await session.scalar(select(User).where(User.id == run.owner_id).with_for_update())
d = await session.scalar(
select(WorkflowDraft)
.where(
WorkflowDraft.id == run.draft_id,
WorkflowDraft.owner_id == run.owner_id,
WorkflowDraft.deleted_at.is_(None),
)
.with_for_update()
)
dialogue_run = run.spec_snapshot.get("schema_version") in (5, 6)
expected_mode = (run.plan_snapshot or {}).get("manifest", {}).get("editing_mode")
if (
not owner
or owner.disabled
or not d
or d.version != run.source_draft_version
or (dialogue_run and editing_mode(d) != expected_mode)
or (not dialogue_run and d.editor_manifest and editing_mode(d) != "auto")
):
run.apply_state = "conflict"
return False
if run.output_goal == "film" and run.state == "succeeded" and run.current_output_asset_id:
d.current_run_id = run.id
run.result_manifest = {**deepcopy(run.result_manifest), "base_run_id": run.id}
await write_manifest(session, d, run.result_manifest, settings)
run.apply_state = "applied"
return True
async def command(runtime, actor, draft_id, body, key, operation):
require_writable(runtime.settings)
async with runtime.db.session() as s:
await require_session_user(s, actor)
payload = request_payload(body)
# 可选改名为空时仍使用旧请求指纹,升级前已接纳的保存可以原幂等键重放。
if operation == "editor.save" and body.name is None:
payload.pop("name", None)
sub = await accept_submission(
s, actor.id, operation, key, 1, {"draft_id": draft_id, **payload}
)
d = await owned(s, WorkflowDraft, draft_id, actor.id)
from app.services.editor_modes import require_auto
require_auto(d)
if sub.resource_json:
if operation == "editor.run":
return await snapshot_run(s, actor.id, sub.resource_json["run_id"])
return await dto(s, d)
check_version(d, body.expected_version)
from app.services.editor_modes import require_auto
require_auto(d)
if not d.editor_manifest:
from app.services.editor_modes import assert_idle
await assert_idle(s, d)
if operation == "editor.save":
m = body.manifest.model_dump(mode="json")
previous = d.editor_manifest or {}
if previous.get("schema_version") == 4 and (
m["schema_version"] != 4
or m["spec"]["schema_version"] < d.spec["schema_version"]
or previous["captions"].get("presentation") and not m["captions"].get("presentation")
):
fail(409, "editor_upgrade_required", "此草稿已使用新版字幕或同框对白,请刷新编辑器后保存")
expected_mode = editing_mode(d) if d.spec.get("schema_version") in (5, 6) else "auto"
if m["editing_mode"] != expected_mode:
fail(409, "editor_mode_conflict", "编辑模式只能通过切换命令修改")
m["editing_mode"] = expected_mode
sanitize_bindings(m, await load_manifest(s, d))
if body.name is not None:
d.name = body.name
await write_manifest(s, d, m, runtime.settings)
elif operation in {"editor.from_run", "editor.apply"}:
r = await owned(s, WorkflowRun, body.run_id, actor.id)
if r.draft_id != d.id:
fail(404, "resource_not_found", "运行不属于此草稿")
if operation == "editor.apply":
if r.state != "succeeded" or not r.result_manifest:
fail(409, "run_result_unavailable", "运行尚无可应用结果")
if r.source_draft_version != d.version:
fail(409, "draft_version_conflict", "草稿已编辑,请显式恢复运行版本")
if operation == "editor.apply":
r.apply_state = "applied"
if r.output_goal == "film" and r.state == "succeeded" and r.current_output_asset_id:
d.current_run_id = r.id
restored = await run_manifest(s, r)
if d.spec.get("schema_version") in (5, 6) and restored.get("schema_version") not in (3, 4):
from app.domain.dialogue import upgrade_dialogue_manifest
restored = upgrade_dialogue_manifest(restored)
restored["editing_mode"] = (
editing_mode(d) if d.spec.get("schema_version") in (5, 6) else "auto"
)
await write_manifest(s, d, restored, runtime.settings)
else:
from app.services.orchestration.editor_engine import start_editor_run
from app.adapters.provider.contracts import h3_tp2_available
from app.services.quotas import reserve_budget
await reserve_budget(s, actor.id, "editor.run", units=0, settings=runtime.settings)
r = await start_editor_run(
s,
d,
await load_manifest(s, d),
body,
runtime.settings,
tp2_capability=lambda: h3_tp2_available(runtime.provider, runtime.settings),
)
sub.resource_json = {"draft_id": d.id, "run_id": r.id}
await s.commit()
result = await snapshot_run(s, actor.id, r.id)
from app.services.workflows import wake
wake(runtime)
return result
sub.resource_json = {"draft_id": d.id}
result = await dto(s, d)
await s.commit()
return result
async def save_editor(runtime, actor, draft_id, body, key):
return await command(runtime, actor, draft_id, body, key, "editor.save")
async def from_run(runtime, actor, draft_id, body, key):
return await command(runtime, actor, draft_id, body, key, "editor.from_run")
async def apply_editor(runtime, actor, draft_id, body, key):
return await command(runtime, actor, draft_id, body, key, "editor.apply")
async def start_editor_request(runtime, actor, draft_id, body, key):
# 外部健康探测不占业务锁;接纳事务仍重新校验会话、草稿版本及计划。
from app.models import Submission
async with runtime.db.session() as s:
await require_session_user(s, actor)
previous = await s.scalar(
select(Submission).where(
Submission.owner_id == actor.id,
Submission.operation == "editor.run",
Submission.key == key,
)
)
d = await owned(s, WorkflowDraft, draft_id, actor.id)
from app.services.editor_modes import require_auto
require_auto(d)
m = await load_manifest(s, d)
replay = previous is not None and bool(previous.resource_json)
if m.get("schema_version") in (3, 4) and not replay and body.output_goal not in {"caption_film", "mix_film"}:
from app.services.system import refresh_dialogue_capabilities
await refresh_dialogue_capabilities(runtime)
needs_speech = (
body.output_goal == "film" or any(t.startswith("audio:") for t in body.targets)
) and m["audio"]["mode"] == "generated_narration"
if needs_speech and not replay:
if not getattr(runtime.settings, "tts_base_url", "") or not getattr(
runtime.settings, "tts_voices", ()
):
fail(503, "capability_unavailable", "中文配音服务尚未配置")
probe = getattr(runtime.provider, "speech_health", None)
if probe:
try:
health = await probe()
except Exception:
fail(503, "capability_unavailable", "配音服务暂不可用")
if not health.get("configured") or not health.get("reachable"):
fail(503, "capability_unavailable", "配音服务暂不可用")
return await command(runtime, actor, draft_id, body, key, "editor.run")
async def plan_editor_request(runtime, actor, draft_id, body):
# 能力探测在事务之外执行,取回证书后重新核验所有者和草稿版本。
async with runtime.db.session() as s:
await require_session_user(s, actor)
version = await s.scalar(
select(WorkflowDraft.spec["schema_version"].as_integer()).where(
WorkflowDraft.id == draft_id,
WorkflowDraft.owner_id == actor.id,
WorkflowDraft.deleted_at.is_(None),
)
)
if version in (5, 6) and body.output_goal not in {"caption_film", "mix_film"}:
from app.services.system import refresh_dialogue_capabilities
await refresh_dialogue_capabilities(runtime)
async with runtime.db.session() as s:
await require_session_user(s, actor)
d = await owned(s, WorkflowDraft, draft_id, actor.id)
check_version(d, body.expected_version)
from app.services.editor_modes import require_auto
require_auto(d)
from app.services.orchestration.editor_engine import plan_editor
from app.adapters.provider.contracts import h3_tp2_available
return await plan_editor(
s,
d,
await load_manifest(s, d),
body,
runtime.settings,
tp2_capability=lambda: h3_tp2_available(runtime.provider, runtime.settings),
)