cmvr-visual/backend/app/services/orchestration/editor_engine.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

966 lines
38 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.

"""编辑器 typed DAG;仅冻结配方及派发 Job,不执行模型。"""
from copy import deepcopy
from types import SimpleNamespace
import secrets
import math
from sqlalchemy import select
from fastapi import HTTPException
from app.models import (
Asset,
AssetReference,
Job,
WorkflowRun,
WorkflowStep,
User,
Execution,
utcnow,
)
from app.core.errors import fail
from app.domain.errors import MediaError
from app.domain.tasks import TERMINAL
from app.domain.stories import compile_story, ordered_reference_ids, canvas
from app.services.workflows import digest, verified_output, emit_run
def build_recipes(manifest, reusable, body, settings, story_compiled=None):
spec = manifest["spec"]
force = set(body.get("force", []))
recipes = []
lookup = {}
portrait = spec.get("profile") == "portrait_1080_v1"
width, height = (704, 1280) if portrait else (1280, 704)
compiled = {x["shot_id"]: x for x in (story_compiled or {}).get("shots", [])}
audio = manifest.get("audio", {})
segments = audio.get("segments", [])
needs_script = (
audio.get("mode") == "generated_narration"
or manifest.get("captions", {}).get("mode") == "ai_script"
) and any(not s.get("text", "").strip() for s in segments)
if "script" in force:
needs_script = True
def add(key, kind, unit, binding=None, deps=(), inputs=None, parameters=None, context=None):
reuse = reusable.get(binding) if binding and binding not in force else None
if (
reuse
and (reuse.get("source") == "generated" or reuse.get("context_hash") is not None)
and reuse.get("context_hash") != context
):
reuse = None
# seed是选中变体;源帧数仅决定是否足长,其余实际参数不得漂移。
if reuse and reuse.get("generation_parameters") and reuse.get("source") != "manual":
actual = reuse["generation_parameters"]
excluded = {"seed", "num_frames"} if kind == "video.generate" else {"seed"}
if {k: v for k, v in actual.items() if k not in excluded} != {
k: v for k, v in (parameters or {}).items() if k not in excluded
}:
reuse = None
item = dict(
key=key,
kind=kind,
unit_id=unit,
binding_key=binding,
dependencies=[] if reuse else list(deps),
input=inputs or {},
parameters=parameters or {},
context_hash=context,
reuse=deepcopy(reuse),
forced=(binding in force or key in force),
)
original = manifest.get("bindings", {}).get(binding) or reusable.get(binding) or {}
if original.get("locked") and not reuse and binding not in force:
item["issue"] = {
"code": "locked_dependency_changed",
"unit_id": unit,
"binding_key": binding,
"message": "锁定素材已失效或不再匹配当前生成输入,请解锁或明确强制重生成",
}
recipes.append(item)
if binding:
lookup[binding] = key
lookup[key] = key
return item
if needs_script:
add(
"script",
"text.script.generate",
"script",
inputs={
"shots": [
dict(
shot_id=sid,
name=s.get("name", ""),
visual_prompt=s.get("visual_prompt", s.get("prompt", "")),
motion_prompt=s.get("motion_prompt", ""),
duration_frames=_frames(s),
)
for sid, s in zip(manifest["shot_ids"], spec["shots"])
],
"context": spec.get("context", {}),
},
parameters={"model": getattr(settings, "qwen_model", "Qwen3.5-27B")},
)
speech_by_shot = {}
if audio.get("mode") == "generated_narration":
for i, seg in enumerate(segments, 1):
params = {
"voice": seg.get("voice")
or audio.get("voice")
or (getattr(settings, "tts_voices", ()) or ("",))[0],
"speed": seg.get("speed") or audio.get("speed", 1.0),
"model": getattr(settings, "tts_model", ""),
}
context = digest({"segment": seg, "parameters": params}) if seg.get("text") else None
item = add(
f"speech_{i:04d}",
"audio.speech",
seg["id"],
"audio:" + seg["id"],
["script"] if needs_script and not seg.get("text") else [],
{"prompt": seg.get("text", "")},
params,
context,
)
speech_by_shot.setdefault(seg["shot_id"], []).append(item["key"])
for i, (sid, shot) in enumerate(zip(manifest["shot_ids"], spec["shots"]), 1):
frame = f"frame_{i:04d}"
video = f"video_{i:04d}"
item = compiled.get(sid, {})
refs = ordered_reference_ids(item.get("references", []))
fp = shot.get("frame_parameters", {})
seed = fp.get("seed", shot.get("parameters", {}).get("seed", 42))
context = digest(
{
"visual": item.get("context_hash", shot.get("prompt")),
"seed": seed,
"profile": spec.get("profile"),
}
)
fi = {
"prompt": item.get("frame_prompt", shot.get("visual_prompt", shot.get("prompt", ""))),
"negative_prompt": item.get("effective_settings", {}).get("negative_prompt", ""),
}
if refs:
fi["reference_asset_ids"] = refs
params = dict(
width=width,
height=height,
seed=seed,
num_inference_steps=40 if refs else 50,
guidance_scale=1.0 if refs else 4.0,
)
if refs:
params.update(
profile=getattr(
settings, "reference_generation_profile", "qwen-image-edit-2511-v1"
),
true_cfg_scale=4.0,
)
context = digest({"visual_context": context, "requested_parameters": params})
add(
frame,
"image.reference.generate" if refs else "image.generate",
sid,
"frame:" + sid,
inputs=fi,
parameters=params,
context=context,
)
vp = shot.get("video_parameters", {})
source_seconds = vp.get("source_seconds", (_frames(shot) + 23) // 24)
params = dict(
width=width,
height=height,
num_frames=4 * ((source_seconds * 24 + 3) // 4) + 1,
fps=24,
upscale=vp.get("upscale", True),
upscale_width=1056 if portrait else 1920,
upscale_height=1920 if portrait else 1056,
seed=vp.get("seed", shot.get("parameters", {}).get("seed", 42)),
num_inference_steps=vp.get("num_inference_steps", 50),
guidance_scale=vp.get("guidance_scale", 5.0),
tile_size=128,
)
# trim和请求源长不使已足长的真实源失效;其余生成意图仍参与上下文。
vc = digest(
{
"frame_context": context,
"motion": shot.get("motion_prompt", shot.get("prompt", "")),
"profile": spec.get("profile"),
"seed": params["seed"],
"steps": params["num_inference_steps"],
"guidance_scale": params["guidance_scale"],
"upscale": params["upscale"],
}
)
base_vc = vc
if reusable.get("frame:" + sid):
vc = digest({"context": base_vc, "frame_sha256": reusable["frame:" + sid]["sha256"]})
if "frame:" + sid in force:
reusable = {k: v for k, v in reusable.items() if k != "video:" + sid}
add(
video,
"video.generate",
sid,
"video:" + sid,
[frame] + speech_by_shot.get(sid, []),
{
"prompt": shot.get("motion_prompt", shot.get("prompt", ""))
or "静态镜头,保持画面主体和外观一致"
},
params,
vc,
)
recipes[-1]["base_context_hash"] = base_vc
if audio.get("mode") == "generated_narration":
add(
"assemble",
"audio.assemble",
"audio",
deps=[k for v in speech_by_shot.values() for k in v],
parameters={"fps": 24},
)
if manifest.get("captions", {}).get("mode") not in {"none", None}:
add(
"captions",
"captions.compile",
"captions",
deps=(["script"] if needs_script else [])
+ [k for v in speech_by_shot.values() for k in v],
)
add(
"compose",
"video.compose",
"film",
deps=[f"video_{i:04d}" for i in range(1, len(spec["shots"]) + 1)]
+ (["assemble"] if audio.get("mode") == "generated_narration" else [])
+ (["captions"] if "captions" in lookup else []),
)
bykey = {r["key"]: r for r in recipes}
targets = (
["compose"]
if body.get("output_goal", "film") == "film"
else body.get("targets") or ["video:" + x for x in manifest["shot_ids"]]
)
wanted = set()
def include(key):
if key not in bykey:
fail(422, "invalid_target", "执行目标不存在")
if key in wanted:
return
wanted.add(key)
for dep in bykey[key]["dependencies"]:
include(dep)
for target in targets:
include(lookup.get(target, target))
for target in force:
if target not in lookup:
fail(422, "invalid_target", "强制生成目标不存在")
# 显式强制节点也是执行目标,即使静音/关闭字幕不再依赖文案。
include(lookup[target])
chosen = [r for r in recipes if r["key"] in wanted]
for r in chosen:
if (
r["key"].startswith("frame_")
and r["reuse"]
and any(r["key"] in other["dependencies"] for other in chosen)
):
b = r["reuse"]
if (b.get("_width", width), b.get("_height", height)) != (width, height):
if b.get("locked") and r["binding_key"] not in force:
r["issue"] = {
"code": "locked_dependency_changed",
"unit_id": r["unit_id"],
"binding_key": r["binding_key"],
"message": "锁定首帧需要调整尺寸,请解锁或明确强制重生成",
}
r.update(
kind="image.prepare_frame",
reuse=None,
input={"image_asset_id": b["asset_id"]},
parameters={
"width": width,
"height": height,
"fit": spec["render"].get("fit", "contain"),
},
)
if r["reuse"]:
r["reuse"] = {k: v for k, v in r["reuse"].items() if not k.startswith("_")}
return chosen
def _frames(shot):
return shot.get("edit", {}).get("duration_frames", shot.get("duration_frames", 120))
async def _asset(session, owner, binding, settings, kind=None, minimum_frames=None):
a = await session.get(Asset, binding.get("asset_id"))
if (
not a
or a.owner_id != owner
or a.deleted_at
or not a.ready
or a.library_scope != "private"
or a.sha256 != binding.get("sha256")
or (kind and a.kind != kind)
):
return None
if minimum_frames and (
a.duration_seconds is None or round(a.duration_seconds * 24) < minimum_frames
):
return None
if not await verified_output(a, settings):
return None
if a.kind == "video":
from app.services.stories.candidates import validate_video
shot = SimpleNamespace(
edit=SimpleNamespace(start_frame=0, duration_frames=minimum_frames or 0)
)
try:
await validate_video(a, shot, settings)
except Exception:
return None
return a
async def plan_editor(session, draft, manifest, body, settings):
body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body
from app.services.editors import editor_issues
issues = editor_issues(manifest)
if manifest.get("captions", {}).get("mode") == "none":
cue_ids = {c["id"] for c in manifest["captions"].get("cues", [])}
issues = [i for i in issues if i.get("unit_id") not in cue_ids]
reusable = {}
spec = manifest["spec"]
for key, binding in manifest.get("bindings", {}).items():
minimum = None
if key.startswith("video:") and key[6:] in manifest["shot_ids"]:
shot = spec["shots"][manifest["shot_ids"].index(key[6:])]
minimum = shot.get("edit", {}).get("start_frame", 0) + _frames(shot)
a = await _asset(session, draft.owner_id, binding, settings, binding.get("kind"), minimum)
if a:
reusable[key] = deepcopy(binding)
reusable[key].update(_width=a.width, _height=a.height)
if a.duration_seconds is not None:
reusable[key].update(
duration_seconds=a.duration_seconds,
duration_frames=math.ceil(a.duration_seconds * 24)
if a.kind == "audio"
else round(a.duration_seconds * 24),
)
for sid, shot in zip(manifest["shot_ids"], spec["shots"]):
if (
shot.get("image_asset_id")
and "frame:" + sid not in reusable
and not manifest.get("bindings", {}).get("frame:" + sid, {}).get("locked")
):
a = await session.get(Asset, shot["image_asset_id"])
if a:
binding = {
"asset_id": a.id,
"sha256": a.sha256,
"kind": "image",
"source": "manual",
"_width": a.width,
"_height": a.height,
}
if await _asset(session, draft.owner_id, binding, settings, "image"):
reusable["frame:" + sid] = binding
compiled_issues = []
compiled = None
if spec.get("schema_version") == 3:
from app.services.stories.common import spec_assets
model, assets = await spec_assets(session, draft.owner_id, spec, settings)
compiled = compile_story(model, assets)
compiled_issues = [
dict(e, unit_id=x["shot_id"]) for x in compiled["shots"] for e in x["errors"]
]
recipes = build_recipes(manifest, reusable, body, settings, compiled)
# 仅在实际目标祖先闭包内报告锁定冲突;独立素材任务不被无关锁定阻挡。
issues.extend(r["issue"] for r in recipes if r.get("issue"))
generating_frames = {
r["unit_id"]
for r in recipes
if r["kind"] in {"image.generate", "image.reference.generate"} and not r["reuse"]
}
issues.extend(i for i in compiled_issues if i["unit_id"] in generating_frames)
if any(
r["kind"] == "audio.speech"
and not r["reuse"]
and (
not getattr(settings, "tts_base_url", None)
or not getattr(settings, "tts_model", None)
or r["parameters"]["voice"] not in (getattr(settings, "tts_voices", ()) or ())
)
for r in recipes
):
issues.append({"code": "speech_unavailable", "message": "尚未配置真实配音服务"})
from app.services.editors import collect_manifest_asset_ids
frozen_hashes = {}
for aid in collect_manifest_asset_ids(manifest):
a = await session.get(Asset, aid)
if a and a.owner_id == draft.owner_id and a.ready and a.deleted_at is None:
frozen_hashes[aid] = a.sha256
result = {
"asset_sha256": frozen_hashes,
"output_goal": body.get("output_goal", "film"),
"source_version": draft.version,
"issues": issues,
"steps": [
{
**r,
"status": "reuse"
if r["reuse"]
else "pending_dependency"
if r["dependencies"]
else "generate",
}
for r in recipes
],
}
result["plan_hash"] = digest(
{
"manifest": manifest,
"version": draft.version,
"plan": result,
"execution_mode": body.get("execution_mode", "interactive"),
"output_folder_id": body.get("output_folder_id"),
}
)
return result
async def start_editor_run(session, draft, manifest, body, settings):
body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body
plan = await plan_editor(session, draft, manifest, body, settings)
if body.get("expected_version") != draft.version:
fail(409, "draft_version_conflict", "草稿已更新")
if body.get("expected_plan_hash") != plan["plan_hash"]:
fail(409, "plan_changed", "执行计划已改变")
if any(
i["code"] in {"speech_unavailable", "locked_dependency_changed"} for i in plan["issues"]
) or (plan["issues"] and plan["output_goal"] == "film"):
fail(422, "editor_issues", "请先处理编辑问题")
from app.services.quotas import check_parent_capacity
await check_parent_capacity(session, settings, draft.owner_id, "run")
from app.services.folders import owned_folder
folder = body.get("output_folder_id", draft.folder_id)
if folder:
await owned_folder(session, folder, draft.owner_id, lock=True)
frozen = deepcopy(manifest)
recipes = deepcopy(plan["steps"])
for recipe in recipes:
# 保留作者请求参数与接纳后实际参数两层,force变体后续可直接复用。
recipe["requested_parameters"] = deepcopy(recipe["parameters"])
if recipe["forced"] and "seed" in recipe["parameters"]:
prior = manifest.get("bindings", {}).get(recipe.get("binding_key"), {})
used = {
recipe["parameters"]["seed"],
(prior.get("generation_parameters") or {}).get("seed"),
}
seed = secrets.randbits(32)
while seed in used:
seed = (seed + 1) % 2**32
recipe["parameters"]["seed"] = seed
if recipe["reuse"] and recipe["binding_key"]:
frozen["bindings"][recipe["binding_key"]] = deepcopy(recipe["reuse"])
r = WorkflowRun(
owner_id=draft.owner_id,
draft_id=draft.id,
draft_revision=draft.revision,
folder_id=draft.folder_id,
output_folder_id=folder,
run_kind="story_auto" if manifest["source_kind"] == "story" else "workflow_auto",
output_goal=plan["output_goal"],
source_draft_version=draft.version,
base_run_id=manifest.get("base_run_id"),
spec_snapshot=deepcopy(manifest["spec"]),
spec_hash=digest(manifest["spec"]),
plan_snapshot={
"manifest": deepcopy(manifest),
"asset_sha256": plan["asset_sha256"],
"steps": recipes,
"plan_hash": plan["plan_hash"],
},
result_manifest=frozen,
execution_mode=body.get("execution_mode", "interactive"),
apply_state="pending",
)
session.add(r)
await session.flush()
refids = set()
for recipe in recipes:
result = recipe["reuse"]
session.add(
WorkflowStep(
run_id=r.id,
step_key=recipe["key"],
kind=recipe["kind"],
dependencies=recipe["dependencies"],
semantic_input_hash=digest(recipe),
recipe_json=recipe,
state="succeeded" if result else "waiting",
result_json=deepcopy(result),
)
)
if result:
refids.add(result["asset_id"])
# 冻结源也必须持有独立引用,归档草稿不得回收运行依赖。
from app.services.editors import collect_manifest_asset_ids
refids.update(collect_manifest_asset_ids(frozen))
for aid in refids:
session.add(AssetReference(owner_id=r.owner_id, asset_id=aid, ref_kind="run", ref_id=r.id))
await session.flush()
await emit_run(session, r, False)
return r
async def _add_ref(session, r, asset):
existing = await session.scalar(
select(AssetReference.id).where(
AssetReference.asset_id == asset.id,
AssetReference.ref_kind == "run",
AssetReference.ref_id == r.id,
)
)
if not existing:
session.add(
AssetReference(owner_id=r.owner_id, asset_id=asset.id, ref_kind="run", ref_id=r.id)
)
async def _resolve(session, r, step, settings):
manifest = deepcopy(r.result_manifest)
recipe = step.recipe_json
inputs = deepcopy(recipe["input"])
params = deepcopy(recipe["parameters"])
bindings = manifest["bindings"]
spec = manifest["spec"]
if step.kind == "audio.speech":
seg = next(s for s in manifest["audio"]["segments"] if s["id"] == recipe["unit_id"])
inputs["prompt"] = seg["text"]
if step.kind == "video.generate":
binding = bindings.get("frame:" + recipe["unit_id"], {})
if not await _asset(session, r.owner_id, binding, settings, "image"):
fail(409, "dependency_changed", "首帧不可用")
inputs["image_asset_id"] = binding["asset_id"]
shot = next(
s for sid, s in zip(manifest["shot_ids"], spec["shots"]) if sid == recipe["unit_id"]
)
duration = sum(
bindings.get("audio:" + s["id"], {}).get("duration_frames", 0)
for s in manifest["audio"]["segments"]
if s["shot_id"] == recipe["unit_id"]
)
if duration > _frames(shot):
fail(409, "invalid_timeline", "配音超出镜头时长")
if shot.get("edit", {}).get("start_frame", 0) + _frames(shot) > params["num_frames"]:
fail(409, "generation_source_too_short", "选用区间超出生成源长度")
if step.kind == "audio.assemble":
offsets = {}
ends = {}
offset = 0
for sid, shot in zip(manifest["shot_ids"], spec["shots"]):
offsets[sid] = offset
offset += _frames(shot)
ends[sid] = offset
segments = []
for s in manifest["audio"]["segments"]:
b = bindings["audio:" + s["id"]]
segments.append({"asset_id": b["asset_id"], "offset_frame": offsets[s["shot_id"]]})
offsets[s["shot_id"]] += b["duration_frames"]
if offsets[s["shot_id"]] > ends[s["shot_id"]]:
fail(409, "invalid_timeline", "配音超出镜头时长")
inputs = {"segments": segments, "total_frames": offset}
if step.kind in {"video.compose", "captions.compile"}:
from app.services.editor_media import compile_captions, materialize_cues
subtitles = compile_captions(manifest, bindings)
if step.kind == "captions.compile":
return {
"input": {},
"parameters": {},
"input_sha256": {},
"captions": subtitles,
"editable_cues": materialize_cues(manifest, bindings),
}
frozen = deepcopy(spec)
frozen["render"]["subtitles"] = subtitles
frozen["render"]["audio"] = (
manifest.get("audio", {}).get("track")
if manifest.get("audio", {}).get("mode") != "silent"
else None
)
clips = []
for sid, shot in zip(manifest["shot_ids"], spec["shots"]):
b = bindings.get("video:" + sid, {})
start = shot.get("edit", {}).get("start_frame", 0)
frames = _frames(shot)
a = await _asset(session, r.owner_id, b, settings, "video", start + frames)
if not a:
fail(409, "dependency_changed", "视频源不可用")
from app.adapters.media import inspect_video_track
from app.adapters.storage import confined
track = await inspect_video_track(
confined(settings.asset_root, a.storage_key, exists=True), settings
)
clips.append(
{
"shot_id": sid,
"asset_id": a.id,
"sha256": a.sha256,
"width": track["width"],
"height": track["height"],
"fps": track["fps"],
"source_frames": track["frames"],
"start_frame": start,
"duration_frames": frames,
}
)
inputs = {"asset_ids": [c["asset_id"] for c in clips]}
if frozen["render"].get("audio"):
inputs["audio_asset_id"] = frozen["render"]["audio"]["asset_id"]
params = {"clips": [{"asset_id": c["asset_id"]} for c in clips]}
if spec.get("schema_version") == 3:
params.update(
story_spec=frozen,
render_inputs={"clips": clips, "fps": 24, "canvas": list(canvas(spec["profile"]))},
)
else:
params["workflow_spec"] = frozen
ids = set(inputs.get("asset_ids", []) + inputs.get("reference_asset_ids", []))
ids.update(inputs[k] for k in ("image_asset_id", "audio_asset_id") if inputs.get(k))
ids.update(s["asset_id"] for s in inputs.get("segments", []))
hashes = {}
for aid in ids:
a = await session.get(Asset, aid)
if not a or not await _asset(
session,
r.owner_id,
{
"asset_id": aid,
"sha256": (r.plan_snapshot or {}).get("asset_sha256", {}).get(aid, a.sha256),
},
settings,
):
fail(409, "dependency_changed", "依赖素材已改变")
hashes[aid] = a.sha256
if step.kind == "video.compose" and "render_inputs" in params and inputs.get("audio_asset_id"):
aid = inputs["audio_asset_id"]
params["render_inputs"]["audio"] = {"asset_id": aid, "sha256": hashes[aid]}
return {"input": inputs, "parameters": params, "input_sha256": hashes}
async def create_editor_child(session, r, step, settings):
from app.services.jobs import create_jobs
from app.services.events import emit_job
from app.schemas.jobs import Submit
if step.resolved_input_json is None:
step.resolved_input_json = await _resolve(session, r, step, settings)
step.semantic_input_hash = digest(step.resolved_input_json)
resolved = step.resolved_input_json
if step.kind == "captions.compile":
step.result_json = {"cues": resolved["captions"]}
step.state = "succeeded"
manifest = deepcopy(r.result_manifest)
manifest["captions"]["cues"] = resolved["editable_cues"]
r.result_manifest = manifest
return None
# retry也必须验证冻结依赖的字节,绝不把新素材偷偷套入旧输入。
for aid, sha in resolved["input_sha256"].items():
if not await _asset(session, r.owner_id, {"asset_id": aid, "sha256": sha}, settings):
fail(409, "dependency_changed", "冻结依赖已改变")
step.explicit_attempt += 1
jobs = await create_jobs(
session,
Submit(
task_type=step.kind,
input=resolved["input"],
parameters=resolved["parameters"],
execution_mode=r.execution_mode,
folder_id=r.folder_id,
output_folder_id=r.output_folder_id,
),
SimpleNamespace(id=r.owner_id, auth_kind="session", scopes=[]),
settings,
key=f"run:{r.id}:{step.step_key}:{step.explicit_attempt}",
internal=True,
frozen_workflow=True,
)
j = jobs[0]
j.run_id = r.id
j.step_key = step.step_key
j.explicit_attempt = step.explicit_attempt
j.desired_state = r.desired_state
j.hold_reasons = list(r.hold_reasons or [])
step.selected_job_id = j.id
step.state = "ready"
step.version += 1
await emit_job(session, j)
return j
async def _collect(session, r, step, job, settings):
kind = {
"text.script.generate": "json",
"audio.speech": "audio",
"audio.assemble": "audio",
"video.compose": "video",
"video.generate": "video",
}.get(step.kind, "image")
a = await session.scalar(
select(Asset)
.where(
Asset.source_job_id == job.id,
Asset.owner_id == r.owner_id,
Asset.library_scope == "private",
Asset.ready.is_(True),
Asset.deleted_at.is_(None),
Asset.kind == kind,
)
.order_by(Asset.source_output_index)
)
if not a or not await verified_output(a, settings):
fail(409, "invalid_output", "生成产物不可用")
manifest = deepcopy(r.result_manifest)
if step.kind == "text.script.generate":
texts = {x["shot_id"]: x["text"] for x in (job.result_json or {}).get("segments", [])}
if set(texts) != set(manifest["shot_ids"]):
fail(409, "invalid_output", "旁白镜头不完整")
for seg in manifest["audio"]["segments"]:
if not seg.get("text"):
seg["text"] = texts[seg["shot_id"]]
result = {
"asset_id": a.id,
"sha256": a.sha256,
"kind": a.kind,
"segments": deepcopy(manifest["audio"]["segments"]),
}
else:
if kind == "video":
from app.services.stories.candidates import validate_video
await validate_video(
a,
None,
settings,
generated=step.kind == "video.generate",
parameters=step.recipe_json["parameters"],
)
if not a.width or not a.height or a.duration_seconds is None:
fail(409, "invalid_output", "视频元数据不完整")
if (
step.kind == "video.generate"
and round(a.duration_seconds * 24)
< step.recipe_json["parameters"]["num_frames"] - 1
):
fail(409, "invalid_output", "生成视频帧数不足")
if kind == "image" and (
a.width != step.recipe_json["parameters"]["width"]
or a.height != step.recipe_json["parameters"]["height"]
):
fail(409, "invalid_output", "首帧尺寸不匹配")
if kind == "audio" and (a.duration_seconds is None or a.duration_seconds <= 0):
fail(409, "invalid_output", "音频时长无效")
context = step.recipe_json.get("context_hash")
if step.kind == "audio.speech":
seg = next(
s for s in manifest["audio"]["segments"] if s["id"] == step.recipe_json["unit_id"]
)
context = digest({"segment": seg, "parameters": step.recipe_json["parameters"]})
if step.kind == "video.generate":
context = digest(
{
"context": step.recipe_json["base_context_hash"],
"frame_sha256": manifest["bindings"]["frame:" + step.recipe_json["unit_id"]][
"sha256"
],
}
)
result = {
"asset_id": a.id,
"sha256": a.sha256,
"kind": a.kind,
"source": "manual" if step.kind == "image.prepare_frame" else "generated",
"source_run_id": r.id,
"source_job_id": job.id,
"input_hash": step.semantic_input_hash,
"context_hash": context,
"generation_parameters": deepcopy(step.resolved_input_json["parameters"]),
}
if a.duration_seconds is not None:
result.update(
duration_seconds=a.duration_seconds,
duration_frames=math.ceil(a.duration_seconds * 24)
if kind == "audio"
else round(a.duration_seconds * 24),
)
if kind == "audio" and isinstance((job.result_json or {}).get("sample_count"), int):
samples = job.result_json["sample_count"]
if samples <= 0 or job.result_json.get("sample_rate", 48000) != 48000:
fail(409, "invalid_output", "音频采样元数据无效")
result.update(sample_count=samples, duration_frames=(samples + 1999) // 2000)
key = step.recipe_json.get("binding_key")
if key:
manifest["bindings"][key] = result
if step.kind == "audio.assemble":
manifest["audio"]["track"] = {
"asset_id": a.id,
"source_start_ms": 0,
"source_end_ms": math.floor(a.duration_seconds * 1000),
"offset_frame": 0,
"short_policy": "silence",
}
if step.kind == "video.compose":
r.current_output_asset_id = a.id
step.result_json = result
step.state = "succeeded"
step.version += 1
r.result_manifest = manifest
await _add_ref(session, r, a)
async def advance_editor_run(session, r, settings):
from app.services.orchestration.workflow_engine import child_capacity
from app.core.maintenance import maintenance_active
if r.state in {"succeeded", "cancelled", "failed"}:
return
steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == r.id))).all()
bykey = {s.step_key: s for s in steps}
before = digest(
{
"state": r.state,
"output": r.current_output_asset_id,
"error": r.error_json,
"holds": r.hold_reasons,
"steps": [(s.step_key, s.state, s.version) for s in steps],
}
)
r.hold_reasons = sorted(set(r.hold_reasons or []) - {"quota", "storage"})
if (r.error_json or {}).get("admission_pending"):
r.error_json = None
selected = []
for step in steps:
if not step.selected_job_id or step.state == "succeeded":
continue
j = await session.get(Job, step.selected_job_id)
if (
not j
or j.run_id != r.id
or j.step_key != step.step_key
or j.explicit_attempt != step.explicit_attempt
):
continue
selected.append(j)
if j.state == "succeeded":
try:
await _collect(session, r, step, j, settings)
except (HTTPException, ValueError, MediaError):
step.state = "blocked"
r.error_json = {"code": "invalid_output", "step_key": step.step_key}
elif j.state in {"failed", "timed_out", "needs_attention"}:
step.state = "blocked"
elif j.state == "cancelled":
step.state = "cancelled"
else:
step.state = "running" if j.state in {"running", "collecting"} else "ready"
if r.desired_state == "cancel":
active = await session.scalar(
select(Execution.id)
.join(Job, Job.id == Execution.job_id)
.where(Job.run_id == r.id, Execution.state.not_in({"exited", "results_ready"}))
)
r.state = (
"cancelled"
if not active and all(j.state in TERMINAL for j in selected)
else "cancelling"
)
if r.state == "cancelled":
r.finished_at = utcnow()
elif any(s.state in {"blocked", "cancelled"} for s in steps):
r.state = "blocked"
if not r.error_json:
r.error_json = {
"code": "step_failed",
"step_key": next(s.step_key for s in steps if s.state in {"blocked", "cancelled"}),
}
elif r.desired_state == "pause" or r.hold_reasons:
r.state = "paused"
elif all(s.state == "succeeded" for s in steps):
r.state = "succeeded"
r.finished_at = utcnow()
from app.services.editors import apply_run_result
try:
async with session.begin_nested():
await apply_run_result(session, r, settings)
except HTTPException:
# 成果已经生成;晚编辑或无关旧绑定失效只阻止自动应用。
await session.refresh(r)
r.apply_state = "conflict"
else:
owner = await session.get(User, r.owner_id)
if not owner or owner.disabled:
r.state = "paused"
r.hold_reasons = sorted(set(r.hold_reasons or []) | {"admin_suspend"})
else:
r.state = "running"
r.started_at = r.started_at or utcnow()
admitted = 0
for recipe in r.plan_snapshot["steps"]:
step = bykey[recipe["key"]]
if (
step.state == "succeeded"
or step.selected_job_id
or not all(bykey[d].state == "succeeded" for d in step.dependencies)
):
continue
if admitted >= 8 or maintenance_active(settings):
break
if not await child_capacity(session, r, step, settings):
r.hold_reasons = ["quota"]
break
try:
async with session.begin_nested():
await create_editor_child(session, r, step, settings)
except (HTTPException, ValueError, MediaError) as exc:
await session.refresh(step)
code = (
exc.detail.get("code")
if isinstance(exc, HTTPException) and isinstance(exc.detail, dict)
else "invalid_timeline"
)
if code in {"quota_exceeded", "storage_insufficient"}:
r.hold_reasons = ["quota" if code == "quota_exceeded" else "storage"]
break
step.state = "blocked"
r.state = "blocked"
r.error_json = {"code": code, "step_key": step.step_key}
break
admitted += 1
after = digest(
{
"state": r.state,
"output": r.current_output_asset_id,
"error": r.error_json,
"holds": r.hold_reasons,
"steps": [(s.step_key, s.state, s.version) for s in steps],
}
)
if before != after:
await emit_run(session, r)