574 lines
24 KiB
Python
574 lines
24 KiB
Python
"""持久候选计划与有界补队;人工等待永远不占模型执行槽。"""
|
||
|
||
from types import SimpleNamespace
|
||
from fastapi import HTTPException
|
||
from sqlalchemy import select
|
||
from app.models import Asset, Job, ShotCandidate, Batch, BatchItem, WorkflowDraft, User, utcnow
|
||
from app.domain.stories import digest, ordered_reference_ids, text_frame_prompt
|
||
from app.domain.video_generation import (
|
||
H3_PROFILES,
|
||
H3_TP2_PROFILE,
|
||
recipe_parameters,
|
||
required_output_frames,
|
||
)
|
||
from app.core.errors import fail
|
||
from app.adapters.provider.contracts import capabilities as provider_capabilities
|
||
from app.adapters.provider.contracts import h3_tp2_available, H3_TP2_CERTIFICATION_REASON
|
||
from app.schemas.jobs import Submit
|
||
from app.services.jobs import create_jobs
|
||
from app.services.events import emit_asset
|
||
from app.services.stories.common import (
|
||
preview,
|
||
shot_model,
|
||
current_hash,
|
||
continue_anchor,
|
||
selections,
|
||
selection_dto,
|
||
private_asset,
|
||
candidate_dto,
|
||
add_ref,
|
||
)
|
||
|
||
|
||
async def capabilities(runtime):
|
||
from app.core.runtime_policy import read_runtime_policy
|
||
|
||
entries = {x["task_type"]: x for x in provider_capabilities(runtime.settings)}
|
||
ref = entries.get("image.reference.generate", {})
|
||
available = bool(ref.get("available"))
|
||
maximum = getattr(runtime.settings, "reference_max_images", 3)
|
||
reason = None if available else "多图参考模型尚未通过真实通道认证"
|
||
if available:
|
||
method = getattr(runtime.provider, "upstream_capabilities", None)
|
||
try:
|
||
remote = await method() if method else {}
|
||
upstream = remote.get("reference_generation", {})
|
||
available = upstream.get("available") is True and upstream.get("profile") == getattr(
|
||
runtime.settings, "reference_generation_profile", "qwen-image-edit-2511-v1"
|
||
)
|
||
if (
|
||
type(upstream.get("max_reference_images")) is int
|
||
and upstream["max_reference_images"] > 0
|
||
):
|
||
maximum = min(maximum, upstream["max_reference_images"])
|
||
else:
|
||
available = False
|
||
except Exception:
|
||
available = False
|
||
if not available:
|
||
reason = "上游多图参考能力不可用"
|
||
return dict(
|
||
enabled=getattr(runtime.settings, "story_studio_enabled", True),
|
||
reference_generation=dict(
|
||
available=available,
|
||
task_type="image.reference.generate",
|
||
max_reference_images=maximum,
|
||
model=ref.get("model", "Qwen-Image-Edit-2511"),
|
||
reason=reason,
|
||
),
|
||
frame_text_generation={
|
||
"available": bool(entries.get("image.generate", {}).get("available"))
|
||
},
|
||
max_shots=read_runtime_policy(runtime.settings)["workflow_max_shots"],
|
||
)
|
||
|
||
|
||
async def make_candidate(s, d, body, runtime, seed_offset=0, batch_id=None, *, prepared=None):
|
||
shot = shot_model(d, body.shot_id)
|
||
if (
|
||
body.kind == "video"
|
||
and body.source_kind == "generated"
|
||
and shot.video_parameters.profile == H3_TP2_PROFILE
|
||
and not await h3_tp2_available(runtime.provider, runtime.settings)
|
||
):
|
||
fail(503, "capability_unavailable", H3_TP2_CERTIFICATION_REASON)
|
||
if body.kind == "end_frame" and (
|
||
d.spec.get("schema_version") != 4 or body.source_kind != "manual"
|
||
):
|
||
fail(422, "invalid_endpoint", "尾帧需要 V4 人工图片")
|
||
compiled = prepared["compiled"] if prepared else await preview(s, d)
|
||
latest = prepared["selections"] if prepared else None
|
||
item = next(x for x in compiled["shots"] if x["shot_id"] == shot.id)
|
||
refs = ordered_reference_ids(item["references"])
|
||
reference_mode = body.reference_mode or ("reference" if refs else "text")
|
||
prompt = item["frame_prompt"] if reference_mode == "reference" else text_frame_prompt(item)
|
||
needs_text_prompt = body.kind == "frame" and body.source_kind == "generated"
|
||
errors = [e for e in item["errors"] if e["code"] not in {"prompt_required", "prompt_too_long"}]
|
||
if needs_text_prompt and (not prompt.strip() or len(prompt) > 8000):
|
||
errors.append({"code": "invalid_prompt"})
|
||
if errors:
|
||
fail(422, "invalid_story_shot", "镜头编译失败,请检查提示词和引用")
|
||
width, height = (704, 1280) if d.spec["profile"] == "portrait_1080_v1" else (1280, 704)
|
||
inputs, parameters = {}, {}
|
||
source = None
|
||
target = None
|
||
mode = body.execution_mode
|
||
if body.source_kind == "manual":
|
||
if not body.asset_id:
|
||
fail(422, "asset_required", "请选择人工素材")
|
||
source = await private_asset(
|
||
s,
|
||
body.asset_id,
|
||
d.owner_id,
|
||
"image" if body.kind in {"frame", "end_frame"} else "video",
|
||
)
|
||
task_type = "image.prepare_frame" if body.kind in {"frame", "end_frame"} else None
|
||
inputs = {"image_asset_id": source.id} if task_type else {}
|
||
parameters = (
|
||
{"width": width, "height": height, "fit": d.spec["render"]["fit"]} if task_type else {}
|
||
)
|
||
elif body.kind == "frame":
|
||
caps = prepared["capabilities"] if prepared else await capabilities(runtime)
|
||
if reference_mode == "reference":
|
||
if not caps["reference_generation"]["available"]:
|
||
fail(
|
||
503, "reference_generation_unavailable", caps["reference_generation"]["reason"]
|
||
)
|
||
if not refs or len(refs) > caps["reference_generation"]["max_reference_images"]:
|
||
fail(422, "reference_count", "参考图数量超出当前模型限制")
|
||
task_type = "image.reference.generate"
|
||
inputs = {
|
||
"prompt": prompt,
|
||
"negative_prompt": item["effective_settings"]["negative_prompt"],
|
||
"reference_asset_ids": refs,
|
||
}
|
||
parameters = dict(
|
||
profile=getattr(
|
||
runtime.settings, "reference_generation_profile", "qwen-image-edit-2511-v1"
|
||
),
|
||
width=width,
|
||
height=height,
|
||
seed=(shot.frame_parameters.seed + seed_offset) % 2**32,
|
||
num_inference_steps=40,
|
||
guidance_scale=1.0,
|
||
true_cfg_scale=4.0,
|
||
)
|
||
else:
|
||
if not caps["frame_text_generation"]["available"]:
|
||
fail(503, "frame_text_generation_unavailable", "文生图服务不可用")
|
||
task_type = "image.generate"
|
||
inputs = {
|
||
"prompt": prompt,
|
||
"negative_prompt": item["effective_settings"]["negative_prompt"],
|
||
}
|
||
parameters = dict(
|
||
width=width,
|
||
height=height,
|
||
seed=(shot.frame_parameters.seed + seed_offset) % 2**32,
|
||
num_inference_steps=50,
|
||
guidance_scale=4.0,
|
||
)
|
||
else:
|
||
if shot.edit.start_frame + shot.edit.duration_frames > (
|
||
shot.video_parameters.source_frames
|
||
if hasattr(shot.video_parameters, "source_frames")
|
||
else shot.video_parameters.source_seconds * 24
|
||
):
|
||
fail(
|
||
422,
|
||
"generation_source_too_short",
|
||
"选用区间超出本次生成源长度,请增加源时长或缩短选用区间",
|
||
)
|
||
latest = latest if latest is not None else await selections(s, d)
|
||
if hasattr(shot, "continuity") and shot.continuity.transition == "continue":
|
||
source = await continue_anchor(s, d, shot, latest)
|
||
if source is None:
|
||
fail(409, "join_anchor_required", "请先完成前一镜头当前选段的末帧质量检查")
|
||
else:
|
||
frame = latest.get((shot.id, "frame"))
|
||
dto = await selection_dto(s, d, frame, compiled, latest) if frame else None
|
||
if not dto or dto["stale"] or not dto["asset"]:
|
||
fail(409, "frame_selection_required", "请先确认当前首帧")
|
||
source = await private_asset(s, frame.asset_id, d.owner_id, "image")
|
||
task_type = "video.generate"
|
||
inputs = {
|
||
"prompt": shot.motion_prompt or "静态镜头,保持画面主体和外观一致",
|
||
"image_asset_id": source.id,
|
||
}
|
||
v = shot.video_parameters
|
||
parameters = dict(
|
||
width=width,
|
||
height=height,
|
||
num_frames=v.source_frames
|
||
if hasattr(v, "source_frames")
|
||
else 4 * ((v.source_seconds * 24 + 3) // 4) + 1,
|
||
fps=24,
|
||
upscale=v.upscale,
|
||
upscale_width=1056 if width == 704 else 1920,
|
||
upscale_height=1920 if width == 704 else 1056,
|
||
seed=(v.seed + seed_offset) % 2**32,
|
||
num_inference_steps=v.num_inference_steps,
|
||
guidance_scale=getattr(v, "guidance_scale", 5.0),
|
||
tile_size=128,
|
||
)
|
||
if hasattr(v, "source_frames"):
|
||
inputs["first_frame_asset_id"] = inputs.pop("image_asset_id")
|
||
parameters["conditioning_mode"] = shot.continuity.endpoint_mode
|
||
if parameters["conditioning_mode"] == "first_last_frame":
|
||
end = latest.get((shot.id, "end_frame"))
|
||
endpoint = await selection_dto(s, d, end, compiled, latest) if end else None
|
||
if not endpoint or endpoint["stale"] or not endpoint["asset"]:
|
||
fail(409, "end_frame_required", "请先确认目标尾帧")
|
||
target = await private_asset(s, end.asset_id, d.owner_id, "image")
|
||
inputs["last_frame_asset_id"] = target.id
|
||
try:
|
||
parameters = recipe_parameters(parameters, v.profile, portrait=width == 704)
|
||
except ValueError as exc:
|
||
fail(422, "invalid_video_profile", str(exc))
|
||
plan = {
|
||
"task_type": task_type,
|
||
"input": inputs,
|
||
"parameters": parameters,
|
||
"execution_mode": mode,
|
||
"input_sha256": {a.id: a.sha256 for a in [source, target] if a},
|
||
"references": item["references"],
|
||
"adapter_version": "story-v4-candidate-v1"
|
||
if d.spec.get("schema_version") == 4
|
||
else "story-candidate-v1",
|
||
"input_snapshot": {
|
||
"reference_mode": "reference"
|
||
if task_type == "image.reference.generate"
|
||
else "text"
|
||
if task_type == "image.generate"
|
||
else "manual"
|
||
if body.source_kind == "manual"
|
||
else "approved_frame",
|
||
"actual_image_refs": inputs.get(
|
||
"reference_asset_ids",
|
||
[
|
||
inputs[k]
|
||
for k in ("image_asset_id", "first_frame_asset_id", "last_frame_asset_id")
|
||
if k in inputs
|
||
],
|
||
),
|
||
},
|
||
}
|
||
generation_hash = digest(plan)
|
||
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, d.owner_id, lock=True)
|
||
plan = {**plan, "folder_id": d.folder_id, "output_folder_id": output_folder_id}
|
||
c = ShotCandidate(
|
||
owner_id=d.owner_id,
|
||
draft_id=d.id,
|
||
shot_id=shot.id,
|
||
kind=body.kind,
|
||
source_kind=body.source_kind,
|
||
context_hash=await current_hash(
|
||
s,
|
||
d,
|
||
shot.id,
|
||
body.kind,
|
||
compiled,
|
||
latest,
|
||
source_kind=body.source_kind,
|
||
source_sha256=source.sha256 if source else None,
|
||
),
|
||
generation_hash=generation_hash,
|
||
created_revision=d.revision,
|
||
plan_json=plan,
|
||
batch_id=batch_id,
|
||
)
|
||
s.add(c)
|
||
await s.flush()
|
||
for id in set(refs) | set(plan["input_sha256"]):
|
||
await add_ref(s, d, id, "candidate", c.id)
|
||
if source and body.kind == "video" and body.source_kind == "manual":
|
||
await validate_video(source, shot, runtime.settings, generated=False)
|
||
c.asset_id, c.asset_sha256, c.state = source.id, source.sha256, "ready"
|
||
emit_asset(
|
||
s,
|
||
d.owner_id,
|
||
"candidate.updated",
|
||
{"candidate": await candidate_dto(s, d, c, compiled, latest)},
|
||
)
|
||
return c
|
||
|
||
|
||
async def validate_video(asset, shot, settings, generated=False, parameters=None):
|
||
from app.services.workflows import verified_output
|
||
from app.adapters.storage import confined
|
||
from app.adapters.media import inspect_video_track
|
||
|
||
if not await verified_output(asset, settings):
|
||
fail(409, "asset_integrity_failed", "素材字节或SHA已改变")
|
||
track = await inspect_video_track(
|
||
confined(settings.asset_root, asset.storage_key, exists=True), settings
|
||
)
|
||
required = shot.edit.start_frame + shot.edit.duration_frames if shot else 0
|
||
if generated:
|
||
required = max(required, required_output_frames(parameters))
|
||
dims = (
|
||
(parameters["upscale_width"], parameters["upscale_height"])
|
||
if parameters.get("upscale")
|
||
else (parameters["width"], parameters["height"])
|
||
)
|
||
if (track["width"], track["height"]) != dims:
|
||
fail(409, "invalid_video_profile", "视频产物画幅不符合冻结配置")
|
||
if (
|
||
track["fps"] != 24
|
||
or track["frames"] < required
|
||
or (
|
||
generated
|
||
and parameters.get("profile") in H3_PROFILES
|
||
and track["frames"] != parameters["num_frames"]
|
||
)
|
||
):
|
||
fail(409, "invalid_video_frames", "视频帧率或解码帧数不满足选用区间")
|
||
|
||
|
||
async def refresh_candidate(s, d, c, settings):
|
||
if not c.job_id or c.deleted_at is not None:
|
||
return
|
||
if c.state == "ready":
|
||
return
|
||
j = await s.get(Job, c.job_id)
|
||
if not j or j.deleted_at is not None:
|
||
state, error = "failed", {"code": "job_deleted", "message": "候选任务已删除"}
|
||
a = None
|
||
else:
|
||
state = (
|
||
"failed"
|
||
if j.state in {"failed", "timed_out", "needs_attention", "cancelled"}
|
||
else j.state
|
||
)
|
||
error, a = j.error_json, None
|
||
if j.state == "succeeded":
|
||
outputs = (
|
||
await s.scalars(
|
||
select(Asset)
|
||
.where(
|
||
Asset.source_job_id == j.id,
|
||
Asset.owner_id == d.owner_id,
|
||
Asset.ready.is_(True),
|
||
Asset.deleted_at.is_(None),
|
||
Asset.kind == ("image" if c.kind in {"frame", "end_frame"} else "video"),
|
||
)
|
||
.order_by(Asset.source_output_index.desc())
|
||
)
|
||
).all()
|
||
# 最终增强片优先;仅将匹配实际 profile 的终态产物变为可确认候选。
|
||
for candidate in outputs:
|
||
try:
|
||
if c.kind == "video":
|
||
await validate_video(
|
||
candidate,
|
||
None,
|
||
settings,
|
||
generated=True,
|
||
parameters=j.parameters,
|
||
)
|
||
else:
|
||
from app.services.workflows import verified_output
|
||
|
||
if (candidate.width, candidate.height) != (
|
||
j.parameters["width"],
|
||
j.parameters["height"],
|
||
) or not await verified_output(candidate, settings):
|
||
continue
|
||
a = candidate
|
||
break
|
||
except (HTTPException, ValueError):
|
||
continue
|
||
state = "ready" if a else "failed"
|
||
error = (
|
||
None
|
||
if a
|
||
else {
|
||
"code": "invalid_candidate_output",
|
||
"message": "任务无满足冻结帧数和画幅的最终产物",
|
||
}
|
||
)
|
||
before = (c.state, c.asset_id, c.error_json)
|
||
c.state, c.error_json = state, error
|
||
if a:
|
||
c.asset_id = a.id
|
||
c.asset_sha256 = a.sha256
|
||
await add_ref(s, d, a.id, "candidate", c.id, add_to_folder=False)
|
||
if before != (c.state, c.asset_id, c.error_json):
|
||
c.version += 1
|
||
emit_asset(s, d.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)})
|
||
|
||
|
||
async def feed_candidates(s, settings):
|
||
from app.services.orchestration.workflow_engine import child_capacity
|
||
from app.core.maintenance import maintenance_active
|
||
|
||
# 禁用期间保留候选原状态;启用后继续同一持久计划,避免将权限等待记成业务失败。
|
||
rows = (
|
||
await s.scalars(
|
||
select(ShotCandidate)
|
||
.join(User, User.id == ShotCandidate.owner_id)
|
||
.where(
|
||
User.disabled.is_(False),
|
||
ShotCandidate.deleted_at.is_(None),
|
||
ShotCandidate.state.not_in({"ready", "failed"}),
|
||
)
|
||
.order_by(ShotCandidate.created_at, ShotCandidate.id)
|
||
.with_for_update()
|
||
)
|
||
).all()
|
||
admitted = 0
|
||
for c in rows:
|
||
d = await s.get(WorkflowDraft, c.draft_id)
|
||
if not d or d.deleted_at is not None:
|
||
continue
|
||
if not any(x["id"] == c.shot_id for x in d.spec["shots"]):
|
||
if c.job_id:
|
||
from app.services.orchestration.executions import request_control
|
||
|
||
await request_control(s, c.job_id, "cancel")
|
||
c.state, c.error_json = "failed", {"code": "shot_deleted", "message": "镜头已删除"}
|
||
c.version += 1
|
||
emit_asset(
|
||
s, c.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)}
|
||
)
|
||
continue
|
||
if c.job_id:
|
||
await refresh_candidate(s, d, c, settings)
|
||
continue
|
||
if admitted >= 8 or maintenance_active(settings):
|
||
continue
|
||
plan = c.plan_json
|
||
b = await s.get(Batch, c.batch_id) if c.batch_id else None
|
||
# 管理员禁用与手动暂停只冻结补队,不能把持久计划消耗成失败候选。
|
||
if b and (b.deleted_at is not None or b.desired_state != "run" or b.hold_reasons):
|
||
continue
|
||
parent = SimpleNamespace(owner_id=c.owner_id, execution_mode=plan["execution_mode"])
|
||
if not await child_capacity(s, parent, SimpleNamespace(kind=plan["task_type"]), settings):
|
||
continue
|
||
try:
|
||
async with s.begin_nested():
|
||
from app.services.workflows import verified_output
|
||
|
||
expected_sources = dict(plan.get("input_sha256", {}))
|
||
actual_refs = plan.get("input_snapshot", {}).get("actual_image_refs", [])
|
||
for ref in plan.get("references", []):
|
||
if ref["asset_id"] in actual_refs:
|
||
expected_sources[ref["asset_id"]] = ref["sha256"]
|
||
for source_id, sha in expected_sources.items():
|
||
asset = await private_asset(s, source_id, c.owner_id, "image")
|
||
if asset.sha256 != sha or not await verified_output(asset, settings):
|
||
fail(409, "dependency_changed", "候选冻结输入图片已改变或不可用")
|
||
from app.models import Folder
|
||
|
||
# JSON快照没有外键;补队前把已删除目标降为未分类。
|
||
targets = {}
|
||
for field in ("folder_id", "output_folder_id"):
|
||
target = plan.get(field)
|
||
targets[field] = (
|
||
await s.scalar(
|
||
select(Folder.id)
|
||
.where(Folder.id == target, Folder.owner_id == c.owner_id)
|
||
.with_for_update()
|
||
)
|
||
if target
|
||
else None
|
||
)
|
||
jobs = await create_jobs(
|
||
s,
|
||
Submit(
|
||
task_type=plan["task_type"],
|
||
input=plan["input"],
|
||
parameters=plan["parameters"],
|
||
execution_mode=plan["execution_mode"],
|
||
folder_id=targets["folder_id"],
|
||
output_folder_id=targets["output_folder_id"],
|
||
),
|
||
SimpleNamespace(id=c.owner_id, auth_kind="session", scopes=[]),
|
||
settings,
|
||
key=f"candidate:{c.id}",
|
||
internal=True,
|
||
)
|
||
j = jobs[0]
|
||
j.batch_id = c.batch_id
|
||
c.job_id = j.id
|
||
c.version += 1
|
||
if c.batch_id:
|
||
bi = await s.scalar(
|
||
select(BatchItem).where(
|
||
BatchItem.batch_id == c.batch_id, BatchItem.target_id == c.id
|
||
)
|
||
)
|
||
j.batch_item_index = bi.item_index if bi else None
|
||
emit_asset(
|
||
s, c.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)}
|
||
)
|
||
admitted += 1
|
||
except HTTPException as exc:
|
||
await s.refresh(c)
|
||
if exc.detail.get("code") not in {
|
||
"quota_exceeded",
|
||
"storage_insufficient",
|
||
"owner_disabled",
|
||
}:
|
||
c.state, c.error_json = "failed", exc.detail
|
||
c.version += 1
|
||
emit_asset(
|
||
s, c.owner_id, "candidate.updated", {"candidate": await candidate_dto(s, d, c)}
|
||
)
|
||
await advance_candidate_batches(s, settings)
|
||
|
||
|
||
async def advance_candidate_batches(s, settings):
|
||
batches = (
|
||
await s.scalars(
|
||
select(Batch).where(
|
||
Batch.deleted_at.is_(None),
|
||
Batch.state.not_in({"succeeded", "cancelled", "completed_with_errors"}),
|
||
)
|
||
)
|
||
).all()
|
||
for b in batches:
|
||
if b.spec_snapshot.get("kind") != "story_candidates":
|
||
continue
|
||
members = (
|
||
await s.scalars(select(ShotCandidate).where(ShotCandidate.batch_id == b.id))
|
||
).all()
|
||
items = (
|
||
await s.scalars(
|
||
select(BatchItem).where(BatchItem.batch_id == b.id).order_by(BatchItem.item_index)
|
||
)
|
||
).all()
|
||
before = (b.state, tuple((item.id, item.state) for item in items))
|
||
if b.desired_state == "cancel":
|
||
for c in members:
|
||
if not c.job_id and c.state not in {"ready", "failed"}:
|
||
c.state = "failed"
|
||
c.error_json = {"code": "cancelled", "message": "候选批次已取消"}
|
||
c.version += 1
|
||
d = await s.get(WorkflowDraft, c.draft_id)
|
||
emit_asset(
|
||
s,
|
||
c.owner_id,
|
||
"candidate.updated",
|
||
{"candidate": await candidate_dto(s, d, c)},
|
||
)
|
||
b.state = "cancelling"
|
||
elif b.desired_state == "pause" or b.hold_reasons:
|
||
b.state = "paused"
|
||
else:
|
||
b.state = "running" if any(c.job_id for c in members) else "queued"
|
||
if members and all(c.state in {"ready", "failed"} or c.deleted_at for c in members):
|
||
b.state = (
|
||
"cancelled"
|
||
if b.desired_state == "cancel"
|
||
else "succeeded"
|
||
if all(c.state == "ready" for c in members)
|
||
else "completed_with_errors"
|
||
)
|
||
b.finished_at = utcnow()
|
||
by_id = {c.id: c for c in members}
|
||
for item in items:
|
||
c = by_id.get(item.target_id)
|
||
if c:
|
||
item.state = "succeeded" if c.state == "ready" else c.state
|
||
if before != (b.state, tuple((item.id, item.state) for item in items)):
|
||
from app.services.batches import emit_batch
|
||
|
||
await emit_batch(s, b)
|