338 lines
12 KiB
Python
338 lines
12 KiB
Python
|
|
"""Owner 隔离、编译、DTO 与当前追加选择视图。"""
|
|||
|
|
|
|||
|
|
from sqlalchemy import select
|
|||
|
|
from app.models import Asset, AssetReference, WorkflowDraft, ShotCandidate, ShotSelection, utcnow
|
|||
|
|
from app.core.errors import fail
|
|||
|
|
from app.domain.stories import StorySpecV3, StoryShot, compile_story, digest
|
|||
|
|
from app.services.snapshots import asset_dto, iso, owned
|
|||
|
|
from app.services.events import emit_asset
|
|||
|
|
from app.core.runtime_policy import read_runtime_policy
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def story(session, id, owner):
|
|||
|
|
row = await owned(session, WorkflowDraft, id, owner)
|
|||
|
|
if row.kind != "story_v3":
|
|||
|
|
fail(404, "resource_not_found", "故事不存在")
|
|||
|
|
return row
|
|||
|
|
|
|||
|
|
|
|||
|
|
def cas(d, version):
|
|||
|
|
if d.version != version:
|
|||
|
|
fail(409, "draft_version_conflict", "故事已更新,请刷新版本")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def shot_model(d, shot_id):
|
|||
|
|
shot = next((s for s in d.spec["shots"] if s["id"] == shot_id), None)
|
|||
|
|
if shot is None:
|
|||
|
|
fail(404, "shot_not_found", "镜头已删除或不存在")
|
|||
|
|
# 整体引用关系已在草稿写入时验证;读取单镜头不重复解析全部千镜头故事。
|
|||
|
|
return StoryShot.model_validate(shot)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def private_asset(s, id, owner, kind=None):
|
|||
|
|
a = await s.scalar(
|
|||
|
|
select(Asset)
|
|||
|
|
.where(
|
|||
|
|
Asset.id == id,
|
|||
|
|
Asset.owner_id == owner,
|
|||
|
|
Asset.library_scope == "private",
|
|||
|
|
Asset.ready.is_(True),
|
|||
|
|
Asset.deleted_at.is_(None),
|
|||
|
|
)
|
|||
|
|
.with_for_update()
|
|||
|
|
)
|
|||
|
|
if not a:
|
|||
|
|
fail(404, "asset_not_found", "素材不存在或不可访问")
|
|||
|
|
if kind and a.kind != kind:
|
|||
|
|
fail(422, "wrong_asset_kind", "素材类型不正确")
|
|||
|
|
if not a.sha256:
|
|||
|
|
fail(409, "asset_not_ready", "素材尚未校验")
|
|||
|
|
return a
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def spec_assets(s, owner, spec, settings=None):
|
|||
|
|
model = spec if isinstance(spec, StorySpecV3) else StorySpecV3.model_validate(spec)
|
|||
|
|
if settings:
|
|||
|
|
policy = read_runtime_policy(settings)
|
|||
|
|
if policy.get("configuration_error"):
|
|||
|
|
fail(503, "runtime_policy_unavailable", "运行配置无效")
|
|||
|
|
if len(model.shots) > policy["workflow_max_shots"]:
|
|||
|
|
fail(422, "workflow_shot_limit", "镜头数量超过当前限制")
|
|||
|
|
ids = []
|
|||
|
|
for item in [*model.scenes, *model.entities]:
|
|||
|
|
ids.extend(item.reference_asset_ids)
|
|||
|
|
for variant in getattr(item, "forms", []) + getattr(item, "appearances", []):
|
|||
|
|
ids.extend(variant.reference_asset_ids)
|
|||
|
|
assets = {id: await private_asset(s, id, owner, "image") for id in sorted(set(ids))}
|
|||
|
|
if model.render.audio:
|
|||
|
|
audio = await private_asset(s, model.render.audio.asset_id, owner, "audio")
|
|||
|
|
if audio.duration_seconds is None or model.render.audio.source_end_ms > round(
|
|||
|
|
audio.duration_seconds * 1000
|
|||
|
|
):
|
|||
|
|
fail(422, "invalid_timeline", "音轨选择超出源素材")
|
|||
|
|
assets[audio.id] = audio
|
|||
|
|
return model, assets
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def preview(s, d):
|
|||
|
|
model, assets = await spec_assets(s, d.owner_id, d.spec)
|
|||
|
|
return compile_story(model, assets)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def selections(s, d):
|
|||
|
|
rows = (
|
|||
|
|
await s.scalars(
|
|||
|
|
select(ShotSelection)
|
|||
|
|
.where(ShotSelection.draft_id == d.id, ShotSelection.owner_id == d.owner_id)
|
|||
|
|
.order_by(ShotSelection.version.desc(), ShotSelection.id)
|
|||
|
|
)
|
|||
|
|
).all()
|
|||
|
|
latest = {}
|
|||
|
|
for row in rows:
|
|||
|
|
latest.setdefault((row.shot_id, row.kind), row)
|
|||
|
|
return latest
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def current_hash(
|
|||
|
|
s, d, shot_id, kind, compiled=None, latest=None, *, source_kind="generated", source_sha256=None
|
|||
|
|
):
|
|||
|
|
compiled = compiled or await preview(s, d)
|
|||
|
|
item = next(x for x in compiled["shots"] if x["shot_id"] == shot_id)
|
|||
|
|
if kind == "frame":
|
|||
|
|
return item["context_hash"]
|
|||
|
|
shot = shot_model(d, shot_id)
|
|||
|
|
if source_kind == "manual":
|
|||
|
|
# 人工视频不曾读取首帧或Wan生成长度,过期判断只绑定实际来源与画面/运动意图。
|
|||
|
|
return digest(
|
|||
|
|
{
|
|||
|
|
"visual": item["context_hash"],
|
|||
|
|
"motion": shot.motion_prompt,
|
|||
|
|
"source_kind": "manual",
|
|||
|
|
"video_sha256": source_sha256,
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
latest = latest if latest is not None else await selections(s, d)
|
|||
|
|
frame = latest.get((shot_id, "frame"))
|
|||
|
|
a = await s.get(Asset, frame.asset_id) if frame and frame.asset_id else None
|
|||
|
|
return digest(
|
|||
|
|
{
|
|||
|
|
"visual": item["context_hash"],
|
|||
|
|
"frame_sha256": a.sha256 if a else None,
|
|||
|
|
"motion": shot.motion_prompt,
|
|||
|
|
"source_seconds": shot.video_parameters.source_seconds,
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def selection_source_kind(s, row):
|
|||
|
|
if row.decision_json.get("source_kind"):
|
|||
|
|
return row.decision_json["source_kind"]
|
|||
|
|
# 早期v3确认记录没有source_kind,候选审计仍保留,可读取真实来源而非猜测。
|
|||
|
|
candidate = await s.get(ShotCandidate, row.candidate_id) if row.candidate_id else None
|
|||
|
|
return candidate.source_kind if candidate else "generated"
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def selection_dto(s, d, row, compiled=None, latest=None):
|
|||
|
|
a = await s.get(Asset, row.asset_id) if row.asset_id else None
|
|||
|
|
valid = (
|
|||
|
|
a
|
|||
|
|
and a.owner_id == d.owner_id
|
|||
|
|
and a.deleted_at is None
|
|||
|
|
and a.ready
|
|||
|
|
and a.sha256 == row.decision_json.get("asset_sha256")
|
|||
|
|
)
|
|||
|
|
exists = any(x["id"] == row.shot_id for x in d.spec["shots"])
|
|||
|
|
source_kind = await selection_source_kind(s, row) if row.kind == "video" else "generated"
|
|||
|
|
stale = (
|
|||
|
|
not exists
|
|||
|
|
or row.context_hash
|
|||
|
|
!= await current_hash(
|
|||
|
|
s,
|
|||
|
|
d,
|
|||
|
|
row.shot_id,
|
|||
|
|
row.kind,
|
|||
|
|
compiled,
|
|||
|
|
latest,
|
|||
|
|
source_kind=source_kind,
|
|||
|
|
source_sha256=row.decision_json.get("asset_sha256"),
|
|||
|
|
)
|
|||
|
|
if exists
|
|||
|
|
else True
|
|||
|
|
)
|
|||
|
|
return dict(
|
|||
|
|
id=row.id,
|
|||
|
|
draft_id=d.id,
|
|||
|
|
shot_id=row.shot_id,
|
|||
|
|
kind=row.kind,
|
|||
|
|
candidate_id=row.candidate_id,
|
|||
|
|
asset=asset_dto(a) if valid else None,
|
|||
|
|
context_hash=row.context_hash,
|
|||
|
|
version=row.version,
|
|||
|
|
created_at=iso(row.created_at),
|
|||
|
|
stale=stale,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def candidate_dto(s, d, c, compiled=None, latest=None):
|
|||
|
|
a = await s.get(Asset, c.asset_id) if c.asset_id else None
|
|||
|
|
exists = any(x["id"] == c.shot_id for x in d.spec["shots"])
|
|||
|
|
stale = (
|
|||
|
|
not exists
|
|||
|
|
or c.context_hash
|
|||
|
|
!= await current_hash(
|
|||
|
|
s,
|
|||
|
|
d,
|
|||
|
|
c.shot_id,
|
|||
|
|
c.kind,
|
|||
|
|
compiled,
|
|||
|
|
latest,
|
|||
|
|
source_kind=c.source_kind,
|
|||
|
|
source_sha256=c.asset_sha256,
|
|||
|
|
)
|
|||
|
|
if exists
|
|||
|
|
else True
|
|||
|
|
)
|
|||
|
|
result = dict(
|
|||
|
|
id=c.id,
|
|||
|
|
draft_id=c.draft_id,
|
|||
|
|
shot_id=c.shot_id,
|
|||
|
|
kind=c.kind,
|
|||
|
|
source_kind=c.source_kind,
|
|||
|
|
job_id=c.job_id,
|
|||
|
|
asset=asset_dto(a) if a and a.deleted_at is None and a.ready else None,
|
|||
|
|
state=c.state,
|
|||
|
|
context_hash=c.context_hash,
|
|||
|
|
generation_hash=c.generation_hash,
|
|||
|
|
created_revision=c.created_revision,
|
|||
|
|
version=c.version,
|
|||
|
|
created_at=iso(c.created_at),
|
|||
|
|
stale=stale,
|
|||
|
|
)
|
|||
|
|
plan = c.plan_json
|
|||
|
|
snapshot = plan.get("input_snapshot", {})
|
|||
|
|
result["input_summary"] = {
|
|||
|
|
"reference_mode": snapshot.get(
|
|||
|
|
"reference_mode", "manual" if c.source_kind == "manual" else "text"
|
|||
|
|
),
|
|||
|
|
"actual_reference_asset_ids": snapshot.get("actual_image_refs", []),
|
|||
|
|
"model_profile": plan.get("parameters", {}).get("profile", plan.get("task_type")),
|
|||
|
|
"seed": plan.get("parameters", {}).get("seed"),
|
|||
|
|
"prompt": plan.get("input", {}).get("prompt"),
|
|||
|
|
"first_frame_asset_id": plan.get("input", {}).get("image_asset_id"),
|
|||
|
|
}
|
|||
|
|
if c.error_json:
|
|||
|
|
result["error"] = c.error_json
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def readiness(s, d, compiled=None, latest=None):
|
|||
|
|
compiled = compiled or await preview(s, d)
|
|||
|
|
latest = latest if latest is not None else await selections(s, d)
|
|||
|
|
issues, shots = [], []
|
|||
|
|
for item in compiled["shots"]:
|
|||
|
|
sid = item["shot_id"]
|
|||
|
|
video = latest.get((sid, "video"))
|
|||
|
|
# 冻结素材合成不运行文生图;已有视频不能被未使用的生成提示词门槛阻挡。
|
|||
|
|
own = [
|
|||
|
|
{"shot_id": sid, **e}
|
|||
|
|
for e in item["errors"]
|
|||
|
|
if not (
|
|||
|
|
video and video.candidate_id and e["code"] in {"prompt_required", "prompt_too_long"}
|
|||
|
|
)
|
|||
|
|
]
|
|||
|
|
needs_frame = (
|
|||
|
|
video and video.candidate_id and await selection_source_kind(s, video) == "generated"
|
|||
|
|
)
|
|||
|
|
for kind in ("frame", "video") if needs_frame else ("video",):
|
|||
|
|
row = latest.get((sid, kind))
|
|||
|
|
dto = await selection_dto(s, d, row, compiled, latest) if row else None
|
|||
|
|
if not dto or not dto["asset"] or not dto["candidate_id"]:
|
|||
|
|
own.append(
|
|||
|
|
dict(
|
|||
|
|
shot_id=sid,
|
|||
|
|
code=f"{kind}_selection_required",
|
|||
|
|
message="请确认首帧" if kind == "frame" else "请选择视频",
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
elif dto["stale"]:
|
|||
|
|
own.append(
|
|||
|
|
dict(
|
|||
|
|
shot_id=sid,
|
|||
|
|
code=f"{kind}_selection_stale",
|
|||
|
|
message="选择已过期,请重新确认",
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
elif kind == "video":
|
|||
|
|
shot = shot_model(d, sid)
|
|||
|
|
duration = dto["asset"].get("duration_seconds")
|
|||
|
|
if duration is None or shot.edit.start_frame + shot.edit.duration_frames > round(
|
|||
|
|
duration * 24
|
|||
|
|
):
|
|||
|
|
own.append(
|
|||
|
|
dict(
|
|||
|
|
shot_id=sid,
|
|||
|
|
code="video_trim_exceeds_source",
|
|||
|
|
message="选用区间超出当前视频源",
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
issues.extend(own)
|
|||
|
|
shots.append({"shot_id": sid, "ready": not own, "issues": own})
|
|||
|
|
return {"ready": not issues, "issues": issues, "shots": shots}
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def story_dto(s, d):
|
|||
|
|
from app.domain.editors import editing_mode
|
|||
|
|
from app.services.editor_modes import manual_spec
|
|||
|
|
|
|||
|
|
compiled, latest = await preview(s, d), await selections(s, d)
|
|||
|
|
return dict(
|
|||
|
|
editor_manifest=d.editor_manifest,
|
|||
|
|
editing_mode=editing_mode(d),
|
|||
|
|
capabilities={"mode_switch": True, "manual": True, "auto": True, "name_edit": True},
|
|||
|
|
id=d.id,
|
|||
|
|
name=d.name,
|
|||
|
|
kind=d.kind,
|
|||
|
|
folder_id=d.folder_id,
|
|||
|
|
spec=manual_spec(d),
|
|||
|
|
revision=d.revision,
|
|||
|
|
version=d.version,
|
|||
|
|
created_at=iso(d.created_at),
|
|||
|
|
updated_at=iso(d.updated_at),
|
|||
|
|
selections=[await selection_dto(s, d, row, compiled, latest) for row in latest.values()],
|
|||
|
|
readiness=await readiness(s, d, compiled, latest),
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def add_ref(s, d, asset_id, kind, id, *, add_to_folder=True):
|
|||
|
|
exists = await s.scalar(
|
|||
|
|
select(AssetReference.id).where(
|
|||
|
|
AssetReference.asset_id == asset_id,
|
|||
|
|
AssetReference.ref_kind == kind,
|
|||
|
|
AssetReference.ref_id == id,
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if not exists:
|
|||
|
|
if add_to_folder and d.folder_id and kind in {"draft", "candidate", "selection"}:
|
|||
|
|
from app.services.folders import add_asset_folder
|
|||
|
|
from app.models import Asset
|
|||
|
|
|
|||
|
|
asset = await s.get(Asset, asset_id)
|
|||
|
|
if asset is not None:
|
|||
|
|
before = set(asset.folder_ids)
|
|||
|
|
await add_asset_folder(s, asset, d.folder_id, allow_missing=True)
|
|||
|
|
# 已发布素材的归属变化必须通知其他会话;未发布结果仍由收集器统一发布。
|
|||
|
|
if asset.ready and before != set(asset.folder_ids):
|
|||
|
|
emit_asset(s, d.owner_id, "asset.updated", {"asset": asset_dto(asset)})
|
|||
|
|
s.add(AssetReference(owner_id=d.owner_id, asset_id=asset_id, ref_kind=kind, ref_id=id))
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def emit_story(s, d, increment=False):
|
|||
|
|
if increment:
|
|||
|
|
d.version += 1
|
|||
|
|
d.revision += 1
|
|||
|
|
d.updated_at = utcnow()
|
|||
|
|
await s.flush()
|
|||
|
|
dto = await story_dto(s, d)
|
|||
|
|
emit_asset(s, d.owner_id, "story.updated", {"story": dto})
|
|||
|
|
return dto
|