cmvr-visual/backend/app/services/stories/api.py

713 lines
29 KiB
Python
Raw Normal View History

"""故事命令的单事务边界:幂等结果、CAS、可信选择和引用一起提交。"""
import asyncio
from sqlalchemy import select, delete, func
from app.models import (
Asset,
WorkflowDraft,
WorkflowRun,
WorkflowStep,
ShotCandidate,
ShotSelection,
AssetReference,
Batch,
BatchItem,
User,
utcnow,
)
from app.core.errors import fail
from app.domain.editors import is_editor_auto
from app.core.maintenance import require_writable
from app.domain.stories import digest, canvas
from app.services.stories.common import (
story,
cas,
shot_model,
spec_assets,
preview,
selections,
current_hash,
private_asset,
story_dto,
readiness,
candidate_dto,
selection_dto,
add_ref,
emit_story,
)
from app.services.stories.candidates import make_candidate, refresh_candidate, validate_video
from app.services.submissions import accept_submission, request_payload
from app.services.events import emit_asset
from app.services.snapshots import asset_dto, snapshot_run, cursor, run_history_page
from app.schemas.stories import CandidateCreate
async def create(runtime, actor, body):
require_writable(runtime.settings)
async with runtime.db.session() as s:
model, assets = await spec_assets(s, actor.id, body.spec, runtime.settings)
from app.services.folders import owned_folder, create_folder
folder_id = body.folder_id
if folder_id:
await owned_folder(s, folder_id, actor.id, lock=True)
elif "folder_id" not in body.model_fields_set and body.create_folder:
folder_id = (await create_folder(s, actor.id, body.name, unique_name=True)).id
d = WorkflowDraft(
owner_id=actor.id,
name=body.name,
folder_id=folder_id,
kind="story_v3",
spec=model.model_dump(mode="json"),
)
s.add(d)
await s.flush()
for a in assets.values():
await add_ref(s, d, a.id, "draft", d.id)
dto = await emit_story(s, d)
await s.commit()
return dto
async def listing(runtime, actor, page, page_size, folder_id=""):
if page < 1 or not 1 <= page_size <= 100:
fail(422, "invalid_page", "分页参数无效")
async with runtime.db.session() as s:
q = select(WorkflowDraft).where(
WorkflowDraft.owner_id == actor.id,
WorkflowDraft.kind == "story_v3",
WorkflowDraft.deleted_at.is_(None),
)
from app.services.folders import folder_filter
q = q.where(await folder_filter(s, WorkflowDraft, actor.id, folder_id))
total = await s.scalar(select(func.count()).select_from(q.subquery()))
# 先只排序编号,避免MySQL把大型spec/editor_manifest带入filesort缓冲区。
ids = (
await s.scalars(
q.with_only_columns(WorkflowDraft.id)
.order_by(WorkflowDraft.created_at.desc(), WorkflowDraft.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
).all()
rows = (await s.scalars(q.where(WorkflowDraft.id.in_(ids)))).all() if ids else []
by_id = {row.id: row for row in rows}
return dict(
items=[await story_dto(s, by_id[id]) for id in ids if id in by_id],
total=total,
page=page,
page_size=page_size,
cursor=await cursor(s, actor.id),
)
async def get(runtime, actor, id, view=None):
async with runtime.db.session() as s:
d = await story(s, id, actor.id)
if view == "preview":
return await preview(s, d)
if view == "readiness":
return await readiness(s, d)
return await story_dto(s, d)
async def patch(runtime, actor, id, body, if_match):
require_writable(runtime.settings)
async with runtime.db.session() as s:
d = await story(s, id, actor.id)
if is_editor_auto(d):
fail(409, "editor_required", "请使用可编辑成片接口")
if if_match is None or if_match.strip('"') != str(d.version):
fail(409, "draft_version_conflict", "故事版本冲突")
if "folder_id" in body.model_fields_set:
from app.services.folders import owned_folder
if body.folder_id:
await owned_folder(s, body.folder_id, actor.id, lock=True)
d.folder_id = body.folder_id
if body.name is not None:
d.name = body.name
cleared = []
if body.spec is not None:
if d.spec.get("schema_version") == 5 and body.spec.schema_version != 5:
fail(409, "dialogue_editor_required", "请使用支持对白版本的编辑器")
model, assets = await spec_assets(s, actor.id, body.spec, runtime.settings)
removed_shots = {shot["id"] for shot in d.spec["shots"]} - {
shot.id for shot in model.shots
}
if removed_shots:
latest = await selections(s, d)
retired = [
row.id for (shot_id, _), row in latest.items() if shot_id in removed_shots
]
# 镜头移除后审批仅留审计;只释放当前选择的引用,Run/候选仍各自保护素材。
await s.execute(
delete(AssetReference).where(
AssetReference.owner_id == actor.id,
AssetReference.ref_kind == "selection",
AssetReference.ref_id.in_(retired),
)
)
for (shot_id, _), previous in latest.items():
if shot_id not in removed_shots or not (
previous.candidate_id or previous.asset_id
):
continue
# 追加空选择让删除成为真实失效边界;同ID重建或晚到结果均不能复活旧批准。
row = ShotSelection(
owner_id=actor.id,
draft_id=d.id,
shot_id=shot_id,
kind=previous.kind,
candidate_id=None,
asset_id=None,
context_hash=previous.context_hash,
version=previous.version + 1,
decision_json={
"asset_sha256": None,
"approver_id": actor.id,
"generation_hash": None,
"compiler_version": "story-v4-v1"
if d.spec.get("schema_version") == 4
else "story-v3-v1",
"clear_reason": "shot_removed",
},
)
s.add(row)
cleared.append(row)
d.spec = model.model_dump(mode="json")
await s.execute(
delete(AssetReference).where(
AssetReference.ref_kind == "draft", AssetReference.ref_id == d.id
)
)
for a in assets.values():
await add_ref(s, d, a.id, "draft", d.id)
if d.editor_manifest:
from app.services.editor_modes import sync_manual_patch
await sync_manual_patch(s, d, model.model_dump(mode="json"))
dto = await emit_story(s, d, True)
for row in cleared:
emit_asset(
s, actor.id, "selection.updated", {"selection": await selection_dto(s, d, row)}
)
await s.commit()
return dto
async def command(s, d, actor, operation, key, body):
if is_editor_auto(d):
fail(409, "editor_required", "请使用可编辑成片接口")
sub = await accept_submission(
s,
actor.id,
"story." + operation,
key,
3,
{"draft_id": d.id, **request_payload(body)},
)
if sub.resource_json:
return sub, sub.resource_json["response"]
cas(d, body.expected_version)
return sub, None
async def create_candidates(runtime, actor, id, body, key, batch=False, retry_id=None):
require_writable(runtime.settings)
if (
getattr(body, "execution_mode", None) == "interactive"
and actor.auth_kind == "bearer"
and "interactive:write" not in actor.scopes
):
fail(403, "scope_required", "Interactive scope required.")
async with runtime.db.session() as s:
d = await story(s, id, actor.id)
if is_editor_auto(d):
fail(409, "editor_required", "请使用可编辑成片接口")
if d.spec.get("schema_version") == 5 and (
batch or retry_id or body.source_kind == "generated"
):
fail(409, "dialogue_editor_required", "请在对白编辑器中针对该镜头运行生成步骤")
operation = (
"candidate.retry" if retry_id else "candidate.batch" if batch else "candidate.create"
)
# retry target is part of the durable body; keys cannot be replayed against another candidate.
payload = request_payload(body)
if retry_id:
payload["candidate_id"] = retry_id
sub = await accept_submission(
s, actor.id, "story." + operation, key, 3, {"draft_id": id, **payload}
)
if sub.resource_json:
return sub.resource_json["response"]
cas(d, body.expected_version)
from app.services.quotas import (
reserve_budget,
check_parent_capacity,
check_story_candidate_capacity,
)
await reserve_budget(s, actor.id, "story." + operation, units=0, settings=runtime.settings)
b = None
if batch:
if len(set(body.shot_ids)) != len(body.shot_ids):
fail(422, "duplicate_shot", "镜头编号不可重复")
if not retry_id:
units = body.count * (len(body.shot_ids) if batch else 1)
pending = not (getattr(body, "source_kind", None) == "manual" and body.kind == "video")
if pending:
await check_parent_capacity(s, runtime.settings, actor.id, "batch")
await check_story_candidate_capacity(s, runtime.settings, actor.id, units)
if batch:
b = Batch(
owner_id=actor.id,
name=d.name,
spec_snapshot={"kind": "story_candidates", "draft_id": d.id},
state="queued",
)
s.add(b)
await s.flush()
candidates = []
compiled = await preview(s, d)
latest = await selections(s, d)
if retry_id:
old = await s.scalar(
select(ShotCandidate).where(
ShotCandidate.id == retry_id,
ShotCandidate.draft_id == d.id,
ShotCandidate.owner_id == actor.id,
ShotCandidate.deleted_at.is_(None),
)
)
if old is None:
fail(404, "candidate_not_found", "候选不存在")
await refresh_candidate(s, d, old, runtime.settings)
if old.state != "failed":
fail(409, "candidate_not_retryable", "仅失败候选可以重试")
if (
old.plan_json.get("execution_mode") == "interactive"
and actor.auth_kind == "bearer"
and "interactive:write" not in actor.scopes
):
fail(403, "scope_required", "Interactive scope required.")
if old.job_id:
from app.models import Execution, Job
active = await s.scalar(
select(Execution.id)
.where(
Execution.job_id == old.job_id,
Execution.state.not_in({"exited", "results_ready"}),
)
.limit(1)
)
previous_job = await s.get(Job, old.job_id)
if active or (
previous_job
and previous_job.state == "needs_attention"
and not (previous_job.error_json or {}).get("safe_to_retry")
):
fail(409, "cleanup_pending", "候选执行尚未确认清理,不能重复派发")
shot_model(d, old.shot_id)
await check_parent_capacity(s, runtime.settings, actor.id, "batch")
await check_story_candidate_capacity(s, runtime.settings, actor.id, 1)
c = ShotCandidate(
owner_id=d.owner_id,
draft_id=d.id,
shot_id=old.shot_id,
kind=old.kind,
source_kind=old.source_kind,
context_hash=old.context_hash,
generation_hash=old.generation_hash,
created_revision=old.created_revision,
plan_json={**old.plan_json, "parent_plan_id": sub.id},
)
s.add(c)
await s.flush()
refs = (
await s.scalars(
select(AssetReference).where(
AssetReference.ref_kind == "candidate", AssetReference.ref_id == old.id
)
)
).all()
for ref in refs:
await add_ref(s, d, ref.asset_id, "candidate", c.id)
candidates.append(c)
else:
from app.services.stories.candidates import capabilities
# 只在本次锁定草稿的事务内复用;大计划不会按每个候选重编译故事或重查上游能力。
prepared = {
"compiled": compiled,
"selections": latest,
"capabilities": await capabilities(runtime)
if body.kind == "frame" and getattr(body, "source_kind", "generated") == "generated"
else None,
}
for sid in body.shot_ids if batch else [body.shot_id]:
values = body.model_dump()
if "output_folder_id" not in body.model_fields_set:
values.pop("output_folder_id", None)
values.pop("shot_ids", None)
values["shot_id"] = sid
request = CandidateCreate.model_validate(values)
if request.source_kind == "manual" and request.count != 1:
fail(422, "manual_count", "人工素材只创建一个候选")
for index in range(body.count):
c = await make_candidate(
s, d, request, runtime, index, b.id if b else None, prepared=prepared
)
# 接纳组只用于父计划计数,不参与实际模型输入哈希,也不改变冻结输入。
c.plan_json = {**c.plan_json, "parent_plan_id": sub.id}
candidates.append(c)
if b:
s.add(
BatchItem(
batch_id=b.id,
item_index=len(candidates) - 1,
target_kind="candidate",
target_id=c.id,
spec_json={"candidate_id": c.id},
)
)
response = {
"story": await emit_story(s, d),
"candidates": [await candidate_dto(s, d, c, compiled, latest) for c in candidates],
}
if b:
response["batch_id"] = b.id
sub.resource_json = {
"draft_id": id,
"candidate_ids": [c.id for c in candidates],
"response": response,
}
await s.commit()
runtime.coordinator.wake()
return response
async def candidates_list(runtime, actor, id, shot_id, kind, page, page_size):
if page < 1 or not 1 <= page_size <= 100 or kind not in {None, "frame", "video", "end_frame"}:
fail(422, "invalid_page", "候选分页参数无效")
async with runtime.db.session() as s:
d = await story(s, id, actor.id)
q = select(ShotCandidate).where(
ShotCandidate.owner_id == actor.id,
ShotCandidate.draft_id == id,
ShotCandidate.deleted_at.is_(None),
)
if shot_id:
q = q.where(ShotCandidate.shot_id == shot_id)
if kind:
q = q.where(ShotCandidate.kind == kind)
total = await s.scalar(select(func.count()).select_from(q.subquery()))
rows = (
await s.scalars(
q.order_by(ShotCandidate.created_at.desc(), ShotCandidate.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
).all()
for c in rows:
# 镜头删除后候选保留审计,但异步结果不会恢复已删除的镜头。
if any(x["id"] == c.shot_id for x in d.spec["shots"]):
await refresh_candidate(s, d, c, runtime.settings)
items = [await candidate_dto(s, d, c) for c in rows]
await s.commit()
return dict(items=items, total=total, page=page, page_size=page_size)
async def select_candidate(runtime, actor, id, body, key, clear=False):
require_writable(runtime.settings)
async with runtime.db.session() as s:
d = await story(s, id, actor.id)
sub, replay = await command(
s, d, actor, "selection.clear" if clear else "selection.confirm", key, body
)
if replay is not None:
return replay
shot = shot_model(d, body.shot_id)
if body.kind == "end_frame" and d.spec.get("schema_version") not in (4, 5):
fail(422, "invalid_endpoint", "尾帧需要 V4 故事")
h = await current_hash(s, d, body.shot_id, body.kind)
a, c = None, None
if not clear:
c = await s.scalar(
select(ShotCandidate)
.where(
ShotCandidate.id == body.candidate_id,
ShotCandidate.owner_id == actor.id,
ShotCandidate.draft_id == id,
ShotCandidate.shot_id == body.shot_id,
ShotCandidate.kind == body.kind,
ShotCandidate.deleted_at.is_(None),
)
.with_for_update()
)
if not c:
fail(404, "candidate_not_found", "候选不属于此故事镜头")
await refresh_candidate(s, d, c, runtime.settings)
if c.state != "ready" or not c.asset_id:
fail(409, "candidate_not_ready", "候选尚未完成或未通过产物校验")
h = await current_hash(
s,
d,
body.shot_id,
body.kind,
source_kind=c.source_kind,
source_sha256=c.asset_sha256,
)
if c.context_hash != h:
fail(409, "candidate_stale", "画面设定已改变,请重新生成或人工复核")
a = await private_asset(
s, c.asset_id, actor.id, "image" if body.kind in {"frame", "end_frame"} else "video"
)
if a.sha256 != c.asset_sha256:
fail(409, "asset_integrity_failed", "候选素材SHA已改变")
from app.services.workflows import verified_output
if not await verified_output(a, runtime.settings):
fail(409, "asset_integrity_failed", "素材字节或SHA已改变")
if body.kind == "video":
await validate_video(
a,
shot,
runtime.settings,
c.source_kind == "generated",
c.plan_json["parameters"],
)
latest = await selections(s, d)
previous = latest.get((shot.id, body.kind))
row = ShotSelection(
owner_id=actor.id,
draft_id=id,
shot_id=shot.id,
kind=body.kind,
candidate_id=c.id if c else None,
asset_id=a.id if a else None,
decision_json={
"asset_sha256": a.sha256 if a else None,
"approver_id": actor.id,
"generation_hash": c.generation_hash if c else None,
"source_kind": c.source_kind if c else None,
"compiler_version": "story-v4-v1"
if d.spec.get("schema_version") == 4
else "story-v3-v1",
},
context_hash=h,
version=previous.version + 1 if previous else 1,
)
s.add(row)
await s.flush()
# 旧选择只保留审计。当前选择和历史 Run 各自持有独立素材引用。
if previous:
await s.execute(
delete(AssetReference).where(
AssetReference.ref_kind == "selection", AssetReference.ref_id == previous.id
)
)
if a:
await add_ref(s, d, a.id, "selection", row.id)
from app.services.editor_modes import sync_manual_selection
await sync_manual_selection(s, d, row, a, c)
dto = await emit_story(s, d, True)
emit_asset(s, actor.id, "selection.updated", {"selection": await selection_dto(s, d, row)})
sub.resource_json = {"draft_id": id, "selection_id": row.id, "response": dto}
await s.commit()
return dto
async def render(runtime, actor, id, body, key):
require_writable(runtime.settings)
if (
body.execution_mode == "interactive"
and actor.auth_kind == "bearer"
and "interactive:write" not in actor.scopes
):
fail(403, "scope_required", "Interactive scope required.")
async with runtime.db.session() as s:
await s.scalar(select(User).where(User.id == actor.id).with_for_update())
d = await story(s, id, actor.id)
sub, replay = await command(s, d, actor, "render", key, body)
if replay is not None:
return replay
from app.services.editor_modes import manual_spec
render_spec = manual_spec(d, strict=True)
from app.services.quotas import check_parent_capacity, reserve_budget
await reserve_budget(s, actor.id, "story.render", units=0, settings=runtime.settings)
await check_parent_capacity(s, runtime.settings, actor.id, "run")
if body.execution_mode == "interactive":
from app.domain.tasks import RUN_TERMINAL
active = await s.scalar(
select(WorkflowRun.id)
.where(
WorkflowRun.owner_id == actor.id,
WorkflowRun.deleted_at.is_(None),
WorkflowRun.execution_mode == "interactive",
WorkflowRun.state.not_in(RUN_TERMINAL),
)
.limit(1)
)
if active:
fail(429, "quota_exceeded", "已有活动交互工作流")
status = await readiness(s, d)
if not status["ready"]:
fail(409, "story_not_ready", "请先确认所有镜头所需的素材选择")
latest, clips = await selections(s, d), []
for raw in render_spec["shots"]:
shot = shot_model(d, raw["id"])
selection = latest[(shot.id, "video")]
a = await private_asset(s, selection.asset_id, actor.id, "video")
if a.sha256 != selection.decision_json.get("asset_sha256"):
fail(409, "asset_integrity_failed", "选择确认的素材SHA已改变")
await validate_video(a, shot, runtime.settings)
clips.append(
dict(
shot_id=shot.id,
asset_id=a.id,
sha256=a.sha256,
selection_id=selection.id,
selection_version=selection.version,
start_frame=shot.edit.start_frame + getattr(shot.edit, "dedup_frames", 0),
duration_frames=shot.edit.duration_frames
- getattr(shot.edit, "dedup_frames", 0),
width=a.width,
height=a.height,
)
)
if getattr(runtime.settings, "inference_remote_files", False):
# 多片段解码期间持有事务锁,协调器无法续更策略;最终准入前直接核验上游。
try:
async with asyncio.timeout(3):
await runtime.provider.runtime_status()
except Exception:
fail(503, "runtime_policy_unavailable", "运行配置无效")
_, assets = await spec_assets(s, actor.id, render_spec, runtime.settings)
from app.services.workflows import verified_output
for a in assets.values():
if not await verified_output(a, runtime.settings):
fail(409, "asset_integrity_failed", "参考素材或音轨校验失败")
frozen_inputs = {"clips": clips, "canvas": list(canvas(render_spec["profile"])), "fps": 24}
frozen_inputs["selections"] = [
{
"id": x.id,
"shot_id": x.shot_id,
"kind": x.kind,
"version": x.version,
"candidate_id": x.candidate_id,
"asset_id": x.asset_id,
"asset_sha256": x.decision_json.get("asset_sha256"),
}
for x in latest.values()
if x.candidate_id and any(raw["id"] == x.shot_id for raw in render_spec["shots"])
]
audio = render_spec["render"]["audio"]
if audio:
frozen_inputs["audio"] = {
"asset_id": audio["asset_id"],
"sha256": assets[audio["asset_id"]].sha256,
}
snapshot = {**render_spec, "render_inputs": frozen_inputs}
output_folder_id = (
body.output_folder_id if "output_folder_id" in body.model_fields_set else d.folder_id
)
if output_folder_id:
from app.services.folders import owned_folder
await owned_folder(s, output_folder_id, actor.id, lock=True)
r = WorkflowRun(
folder_id=d.folder_id,
output_folder_id=output_folder_id,
owner_id=actor.id,
draft_id=id,
draft_revision=d.revision,
spec_snapshot=snapshot,
spec_hash=digest(snapshot),
execution_mode=body.execution_mode,
)
s.add(r)
await s.flush()
s.add(
WorkflowStep(
run_id=r.id,
step_key="compose",
kind="video.compose",
dependencies=[],
semantic_input_hash=digest(snapshot),
)
)
for aid in (
{c["asset_id"] for c in clips}
| set(assets)
| {x.asset_id for x in latest.values() if x.asset_id}
):
await add_ref(s, d, aid, "run", r.id)
d.current_run_id = r.id
d.version += 1
d.updated_at = utcnow()
await emit_story(s, d)
from app.services.workflows import emit_run
await emit_run(s, r, False)
response = await snapshot_run(s, actor.id, r.id)
sub.resource_json = {"draft_id": id, "run_id": r.id, "response": response}
await s.commit()
runtime.coordinator.wake()
return response
async def latest_film(runtime, actor, id):
async with runtime.db.session() as session:
visible = await session.scalar(
select(WorkflowDraft.id).where(
WorkflowDraft.id == id,
WorkflowDraft.owner_id == actor.id,
WorkflowDraft.kind == "story_v3",
WorkflowDraft.deleted_at.is_(None),
)
)
if not visible:
fail(404, "story_not_found", "故事不存在")
# 仅按正式输出编号找成片。一个自动工作流还可能含有数十个中间视频。
latest = (
select(WorkflowRun.draft_revision, Asset.id.label("asset_id"))
.join(Asset, Asset.id == WorkflowRun.current_output_asset_id)
.where(
WorkflowRun.owner_id == actor.id,
WorkflowRun.draft_id == id,
WorkflowRun.state == "succeeded",
WorkflowRun.output_goal == "film",
WorkflowRun.deleted_at.is_(None),
Asset.owner_id == actor.id,
Asset.ready.is_(True),
Asset.library_scope == "private",
Asset.kind == "video",
Asset.deleted_at.is_(None),
)
.order_by(WorkflowRun.created_at.desc(), WorkflowRun.id.desc())
.limit(1)
.subquery()
)
row = (
await session.execute(
select(Asset, latest.c.draft_revision).join(latest, Asset.id == latest.c.asset_id)
)
).one_or_none()
return {"asset": asset_dto(row[0]), "draft_revision": row[1]} if row else None
async def runs(runtime, actor, id, page, page_size):
if page < 1 or not 1 <= page_size <= 100:
fail(422, "invalid_page", "分页参数无效")
async with runtime.db.session() as s:
await story(s, id, actor.id)
return await run_history_page(s, actor.id, page, page_size, WorkflowRun.draft_id == id)