2026-11-14 14:07:26 +08:00
|
|
|
|
from datetime import timezone
|
|
|
|
|
|
from app.domain.tasks import GPU_TYPES, CPU_TYPES, TERMINAL
|
|
|
|
|
|
import hashlib
|
|
|
|
|
|
import json
|
|
|
|
|
|
from sqlalchemy import func, select
|
|
|
|
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
|
|
from app.services.assets import owned_asset
|
|
|
|
|
|
from app.core.security import Actor
|
|
|
|
|
|
from app.services.snapshots import job_dto
|
|
|
|
|
|
from app.core.errors import fail
|
|
|
|
|
|
from app.services.events import emit_job
|
|
|
|
|
|
from app.models import Event, Job, JobAsset, new_id, utcnow
|
|
|
|
|
|
from app.schemas.jobs import Submit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def owned_job(session, job_id, owner_id):
|
|
|
|
|
|
job = await session.scalar(
|
|
|
|
|
|
select(Job)
|
|
|
|
|
|
.where(Job.id == job_id, Job.owner_id == owner_id, Job.deleted_at.is_(None))
|
|
|
|
|
|
.with_for_update()
|
|
|
|
|
|
)
|
|
|
|
|
|
if job is None:
|
|
|
|
|
|
fail(404, "job_not_found", "任务不存在")
|
|
|
|
|
|
return job
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def input_ids(inputs, parameters):
|
|
|
|
|
|
result = []
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if inputs.get("spec"):
|
|
|
|
|
|
from app.domain.editors import collect_manifest_asset_ids
|
|
|
|
|
|
|
|
|
|
|
|
result.extend(sorted(collect_manifest_asset_ids(inputs["spec"])))
|
|
|
|
|
|
for field in (
|
|
|
|
|
|
"first_frame_asset_id",
|
|
|
|
|
|
"last_frame_asset_id",
|
|
|
|
|
|
"image_asset_id",
|
|
|
|
|
|
"audio_asset_id",
|
|
|
|
|
|
"asset_id",
|
|
|
|
|
|
"video_asset_id",
|
|
|
|
|
|
"previous_video_asset_id",
|
|
|
|
|
|
):
|
2026-11-14 14:07:26 +08:00
|
|
|
|
if inputs.get(field):
|
|
|
|
|
|
result.append(inputs[field])
|
|
|
|
|
|
if inputs.get("asset_ids"):
|
|
|
|
|
|
if not isinstance(inputs["asset_ids"], list):
|
|
|
|
|
|
fail(422, "invalid_assets", "asset_ids 必须为素材编号列表")
|
|
|
|
|
|
result.extend(inputs["asset_ids"])
|
|
|
|
|
|
if "reference_asset_ids" in inputs:
|
|
|
|
|
|
if not isinstance(inputs["reference_asset_ids"], list):
|
|
|
|
|
|
fail(422, "invalid_assets", "参考图必须为素材编号列表")
|
|
|
|
|
|
result.extend(inputs["reference_asset_ids"])
|
|
|
|
|
|
for replacement in inputs.get("replacements", []):
|
|
|
|
|
|
if not isinstance(replacement, dict) or not isinstance(
|
|
|
|
|
|
replacement.get("reference_asset_id"), str
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(422, "invalid_assets", "替换人物需要参考图编号")
|
|
|
|
|
|
result.append(replacement["reference_asset_id"])
|
|
|
|
|
|
for segment in inputs.get("segments", []):
|
|
|
|
|
|
if not isinstance(segment, dict) or not isinstance(segment.get("asset_id"), str):
|
|
|
|
|
|
fail(422, "invalid_assets", "音频段需要素材编号")
|
|
|
|
|
|
result.append(segment["asset_id"])
|
|
|
|
|
|
for clip in parameters.get("clips", []):
|
|
|
|
|
|
if not isinstance(clip, dict) or not isinstance(clip.get("asset_id"), str):
|
|
|
|
|
|
fail(422, "invalid_clip", "每个片段需要素材编号")
|
|
|
|
|
|
result.append(clip["asset_id"])
|
|
|
|
|
|
if parameters.get("audio_asset_id"):
|
|
|
|
|
|
result.append(parameters["audio_asset_id"])
|
|
|
|
|
|
if any((not isinstance(value, str) or len(value) > 64 for value in result)):
|
|
|
|
|
|
fail(422, "invalid_assets", "素材编号格式不正确")
|
|
|
|
|
|
return list(dict.fromkeys(result))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def validate_submission(session, body, owner_id, settings, *, frozen_workflow=False):
|
|
|
|
|
|
if body.task_type not in GPU_TYPES | CPU_TYPES:
|
|
|
|
|
|
fail(422, "unsupported_task", "不支持此任务类型")
|
|
|
|
|
|
allowed = {
|
|
|
|
|
|
"prompt",
|
|
|
|
|
|
"negative_prompt",
|
|
|
|
|
|
"image_asset_id",
|
|
|
|
|
|
"audio_asset_id",
|
|
|
|
|
|
"asset_id",
|
|
|
|
|
|
"asset_ids",
|
|
|
|
|
|
"reference_asset_ids",
|
|
|
|
|
|
"video_asset_id",
|
|
|
|
|
|
"analysis_job_id",
|
|
|
|
|
|
"replacements",
|
|
|
|
|
|
}
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if body.task_type == "video.generate":
|
|
|
|
|
|
allowed |= {"first_frame_asset_id", "last_frame_asset_id"}
|
2026-11-14 14:07:26 +08:00
|
|
|
|
if body.task_type == "text.script.generate":
|
|
|
|
|
|
allowed |= {"shots", "context"}
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if body.task_type == "text.story.plan":
|
|
|
|
|
|
allowed |= {"spec"}
|
|
|
|
|
|
if body.task_type in {"audio.assemble", "audio.mix"}:
|
2026-11-14 14:07:26 +08:00
|
|
|
|
allowed |= {"segments", "total_frames"}
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if body.task_type == "video.continuity.inspect":
|
|
|
|
|
|
allowed |= {"previous_video_asset_id", "expected"}
|
2026-11-14 14:07:26 +08:00
|
|
|
|
if set(body.input) - allowed:
|
|
|
|
|
|
fail(422, "invalid_input", "只允许提示词与素材编号,不接受服务器路径或 URL")
|
|
|
|
|
|
if body.count > 1 and body.task_type not in {
|
|
|
|
|
|
"image.generate",
|
|
|
|
|
|
"image.reference.generate",
|
|
|
|
|
|
"defect.generate",
|
|
|
|
|
|
}:
|
|
|
|
|
|
fail(422, "batch_not_supported", "此任务类型不支持批量生成")
|
|
|
|
|
|
if body.task_type == "audio.speech" and (not settings.tts_base_url):
|
|
|
|
|
|
fail(422, "speech_unavailable", "尚未配置真实配音服务")
|
|
|
|
|
|
from app.adapters.provider.client import ProviderError, validate_arguments
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
validate_arguments(body.task_type, body.input, body.parameters, settings)
|
|
|
|
|
|
except ProviderError as exc:
|
|
|
|
|
|
fail(400, exc.code, exc.message)
|
|
|
|
|
|
prompt = body.input.get("prompt", "")
|
|
|
|
|
|
if not isinstance(prompt, str) or len(prompt) > 8000:
|
|
|
|
|
|
fail(422, "invalid_prompt", "提示词须为不超过 8000 字符的文本")
|
|
|
|
|
|
if body.task_type in {
|
|
|
|
|
|
"image.generate",
|
|
|
|
|
|
"video.generate",
|
|
|
|
|
|
"defect.generate",
|
|
|
|
|
|
"math.solve",
|
|
|
|
|
|
"audio.speech",
|
|
|
|
|
|
"image.reference.generate",
|
|
|
|
|
|
} and (not prompt.strip()):
|
|
|
|
|
|
fail(422, "prompt_required", "请输入提示词或文本")
|
|
|
|
|
|
ids = input_ids(body.input, body.parameters)
|
|
|
|
|
|
assets = {asset_id: await owned_asset(session, asset_id, owner_id) for asset_id in ids}
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if "first_frame_asset_id" in body.input:
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
from app.adapters.storage import confined
|
|
|
|
|
|
from app.services.artifacts import digest_file
|
|
|
|
|
|
|
|
|
|
|
|
for asset_id in ids:
|
|
|
|
|
|
asset = assets[asset_id]
|
|
|
|
|
|
path = confined(settings.asset_root, asset.storage_key, exists=True)
|
|
|
|
|
|
if await asyncio.to_thread(digest_file, path) != asset.sha256:
|
|
|
|
|
|
fail(422, "endpoint_hash_mismatch", "首尾帧素材内容与入库摘要不一致")
|
|
|
|
|
|
if body.task_type in {"audio.assemble", "audio.normalize", "audio.mix"} and any(
|
|
|
|
|
|
a.kind != "audio" for a in assets.values()
|
|
|
|
|
|
):
|
2026-11-14 14:07:26 +08:00
|
|
|
|
fail(422, "wrong_asset_kind", "旁白装配只接受音频素材")
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if body.task_type == "video.continuity.inspect" and any(
|
|
|
|
|
|
a.kind != "video" for a in assets.values()
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "连续性质检只接受视频素材")
|
2026-11-14 14:07:26 +08:00
|
|
|
|
for asset_id in body.input.get("reference_asset_ids", []):
|
|
|
|
|
|
if assets[asset_id].kind != "image":
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "参考图必须为图片素材")
|
|
|
|
|
|
if body.task_type in {"video.people.analyze", "video.replace"}:
|
|
|
|
|
|
if assets[body.input["video_asset_id"]].kind != "video":
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "源素材必须是视频")
|
|
|
|
|
|
from app.adapters.media import inspect_video_timeline
|
|
|
|
|
|
from app.adapters.storage import confined
|
|
|
|
|
|
|
|
|
|
|
|
source = assets[body.input["video_asset_id"]]
|
|
|
|
|
|
try:
|
|
|
|
|
|
duration = await inspect_video_timeline(
|
|
|
|
|
|
confined(settings.asset_root, source.storage_key, exists=True), settings
|
|
|
|
|
|
)
|
|
|
|
|
|
except ProviderError as exc:
|
|
|
|
|
|
fail(422, exc.code, exc.message)
|
|
|
|
|
|
if duration > settings.video_edit_max_seconds + 0.001:
|
|
|
|
|
|
fail(422, "video_too_long", "源视频超过当前时长限制")
|
|
|
|
|
|
for row in body.input.get("replacements", []):
|
|
|
|
|
|
if assets[row["reference_asset_id"]].kind != "image":
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "人物参考素材必须是图片")
|
|
|
|
|
|
if body.task_type == "video.replace":
|
|
|
|
|
|
await resolve_analysis_binding(session, body.input, body.parameters, owner_id, settings)
|
|
|
|
|
|
required = {
|
|
|
|
|
|
"defect.generate": "image_asset_id",
|
|
|
|
|
|
"audio.transcribe": "audio_asset_id",
|
|
|
|
|
|
"media.structure": "asset_id",
|
|
|
|
|
|
}
|
|
|
|
|
|
if body.task_type in required:
|
|
|
|
|
|
key = required[body.task_type]
|
|
|
|
|
|
value = body.input.get(key) or (
|
|
|
|
|
|
body.input.get("asset_id") if key == "audio_asset_id" else None
|
|
|
|
|
|
)
|
|
|
|
|
|
if not value:
|
|
|
|
|
|
fail(422, "asset_required", "此任务需要输入素材")
|
2026-11-26 21:06:27 +08:00
|
|
|
|
for key, kinds in (
|
|
|
|
|
|
("first_frame_asset_id", {"image"}),
|
|
|
|
|
|
("last_frame_asset_id", {"image"}),
|
|
|
|
|
|
("image_asset_id", {"image"}),
|
|
|
|
|
|
("audio_asset_id", {"audio", "video"}),
|
|
|
|
|
|
):
|
2026-11-14 14:07:26 +08:00
|
|
|
|
if body.input.get(key) and assets[body.input[key]].kind not in kinds:
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "输入素材类型不正确")
|
|
|
|
|
|
if body.task_type == "media.structure" and assets[body.input["asset_id"]].kind not in {
|
|
|
|
|
|
"image",
|
|
|
|
|
|
"video",
|
|
|
|
|
|
}:
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "素材理解需要图片或视频")
|
|
|
|
|
|
if body.task_type == "audio.transcribe":
|
|
|
|
|
|
source_id = body.input.get("audio_asset_id") or body.input.get("asset_id")
|
|
|
|
|
|
if assets[source_id].kind not in {"audio", "video"}:
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "转写需要音频或视频素材")
|
|
|
|
|
|
if body.task_type == "video.compose" and (not ids):
|
|
|
|
|
|
fail(422, "clips_required", "请添加待合成片段")
|
|
|
|
|
|
if body.task_type == "video.compose":
|
|
|
|
|
|
if not frozen_workflow:
|
|
|
|
|
|
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(body.parameters.get("clips", [])) > policy["workflow_max_shots"]:
|
|
|
|
|
|
fail(
|
|
|
|
|
|
422,
|
|
|
|
|
|
"workflow_shot_limit",
|
|
|
|
|
|
f"当前配置最多允许{policy['workflow_max_shots']}个视频片段",
|
|
|
|
|
|
)
|
|
|
|
|
|
if any(
|
|
|
|
|
|
(assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", []))
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "编排片段必须为视频素材")
|
|
|
|
|
|
audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id")
|
|
|
|
|
|
if audio_id and assets[audio_id].kind != "audio":
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "成片音轨必须为音频素材")
|
|
|
|
|
|
if body.scheduled_at is not None and body.scheduled_at.tzinfo is None:
|
|
|
|
|
|
fail(422, "timezone_required", "定时任务时间须包含时区")
|
|
|
|
|
|
return ids
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 调用方统一提交:幂等记录、任务、素材引用和事件必须同生共死,不能在内部单独 commit。
|
|
|
|
|
|
async def create_jobs(
|
|
|
|
|
|
session, body, actor, settings, key=None, internal=False, *, frozen_workflow=False
|
|
|
|
|
|
):
|
|
|
|
|
|
if key is not None and (not 1 <= len(key) <= 128):
|
|
|
|
|
|
fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128")
|
|
|
|
|
|
from app.services.submissions import request_payload
|
|
|
|
|
|
|
|
|
|
|
|
payload = request_payload(body)
|
|
|
|
|
|
if body.execution_mode == "interactive":
|
|
|
|
|
|
payload.pop("execution_mode", None)
|
|
|
|
|
|
try:
|
|
|
|
|
|
fingerprint = hashlib.sha256(
|
|
|
|
|
|
json.dumps(payload, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
|
|
|
|
|
|
).hexdigest()
|
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
|
fail(422, "invalid_json", "任务参数必须为有限数值和合法 JSON")
|
|
|
|
|
|
if key:
|
|
|
|
|
|
existing = (
|
|
|
|
|
|
await session.scalars(
|
|
|
|
|
|
select(Job)
|
|
|
|
|
|
.where(Job.owner_id == actor.id, Job.request_key == key)
|
|
|
|
|
|
.order_by(Job.batch_index)
|
|
|
|
|
|
)
|
|
|
|
|
|
).all()
|
|
|
|
|
|
if existing:
|
|
|
|
|
|
if existing[0].request_hash != fingerprint:
|
|
|
|
|
|
fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数")
|
|
|
|
|
|
if any((job.deleted_at is not None for job in existing)):
|
|
|
|
|
|
fail(410, "resource_purged", "此幂等键对应的任务已删除")
|
|
|
|
|
|
from app.services.submissions import accept_submission
|
|
|
|
|
|
|
|
|
|
|
|
saved = await accept_submission(
|
|
|
|
|
|
session, actor.id, "jobs.create", key, 2, request_payload(body)
|
|
|
|
|
|
)
|
|
|
|
|
|
saved.resource_json = {"job_ids": [job.id for job in existing]}
|
|
|
|
|
|
return existing
|
|
|
|
|
|
from app.services.submissions import accept_submission
|
|
|
|
|
|
|
|
|
|
|
|
record = (
|
|
|
|
|
|
await accept_submission(session, actor.id, "jobs.create", key, 2, request_payload(body))
|
|
|
|
|
|
if key
|
|
|
|
|
|
else None
|
|
|
|
|
|
)
|
|
|
|
|
|
from app.services.quotas import reserve_budget
|
|
|
|
|
|
|
|
|
|
|
|
await reserve_budget(
|
|
|
|
|
|
session,
|
|
|
|
|
|
actor.id,
|
|
|
|
|
|
"workflow.child" if internal else "jobs.create",
|
|
|
|
|
|
units=body.count,
|
|
|
|
|
|
settings=settings,
|
|
|
|
|
|
)
|
|
|
|
|
|
from app.core.maintenance import require_writable
|
|
|
|
|
|
|
|
|
|
|
|
require_writable(settings)
|
|
|
|
|
|
if (
|
|
|
|
|
|
actor.auth_kind == "bearer"
|
|
|
|
|
|
and body.execution_mode == "interactive"
|
|
|
|
|
|
and ("interactive:write" not in actor.scopes)
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(403, "scope_required", "Machine tokens require interactive:write for interactive jobs")
|
|
|
|
|
|
from app.services.quotas import check_storage_budget
|
|
|
|
|
|
|
|
|
|
|
|
await check_storage_budget(session, settings, actor.id, new_jobs=body.count)
|
|
|
|
|
|
if (
|
|
|
|
|
|
settings.max_interactive_gpu_jobs > 0
|
|
|
|
|
|
and body.execution_mode == "interactive"
|
|
|
|
|
|
and (body.task_type in GPU_TYPES)
|
|
|
|
|
|
):
|
|
|
|
|
|
active = await session.scalar(
|
|
|
|
|
|
select(func.count())
|
|
|
|
|
|
.select_from(Job)
|
|
|
|
|
|
.where(
|
|
|
|
|
|
Job.owner_id == actor.id,
|
|
|
|
|
|
Job.execution_mode == "interactive",
|
|
|
|
|
|
Job.task_type.in_(GPU_TYPES),
|
|
|
|
|
|
Job.state.notin_(TERMINAL),
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
if active + body.count > settings.max_interactive_gpu_jobs:
|
|
|
|
|
|
fail(429, "quota_exceeded", "Interactive GPU queue limit reached")
|
|
|
|
|
|
ids = await validate_submission(
|
|
|
|
|
|
session, body, actor.id, settings, frozen_workflow=frozen_workflow
|
|
|
|
|
|
)
|
|
|
|
|
|
scheduled = (
|
|
|
|
|
|
body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None)
|
|
|
|
|
|
if body.scheduled_at
|
|
|
|
|
|
else None
|
|
|
|
|
|
)
|
|
|
|
|
|
from app.services.folders import owned_folder
|
|
|
|
|
|
|
|
|
|
|
|
folder_id = body.folder_id
|
|
|
|
|
|
output_folder_id = (
|
|
|
|
|
|
body.output_folder_id if "output_folder_id" in body.model_fields_set else folder_id
|
|
|
|
|
|
)
|
|
|
|
|
|
for target in {folder_id, output_folder_id} - {None}:
|
|
|
|
|
|
await owned_folder(session, target, actor.id, lock=True)
|
|
|
|
|
|
jobs = []
|
|
|
|
|
|
for index in range(body.count):
|
|
|
|
|
|
job_id = new_id()
|
|
|
|
|
|
future = scheduled and scheduled > utcnow()
|
|
|
|
|
|
parameters = dict(body.parameters)
|
|
|
|
|
|
if body.task_type == "video.replace":
|
|
|
|
|
|
parameters["_video_edit_binding"] = await resolve_analysis_binding(
|
|
|
|
|
|
session, body.input, parameters, actor.id, settings
|
|
|
|
|
|
)
|
|
|
|
|
|
if body.count > 1:
|
|
|
|
|
|
parameters["seed"] = (parameters.get("seed", 42) + index) % 2**32
|
|
|
|
|
|
job = Job(
|
|
|
|
|
|
id=job_id,
|
|
|
|
|
|
owner_id=actor.id,
|
|
|
|
|
|
folder_id=folder_id,
|
|
|
|
|
|
output_folder_id=output_folder_id,
|
|
|
|
|
|
task_type=body.task_type,
|
|
|
|
|
|
state="scheduled" if future else "submitting",
|
|
|
|
|
|
phase="scheduled" if future else "waiting_dispatch",
|
|
|
|
|
|
execution_mode=body.execution_mode,
|
|
|
|
|
|
version=1,
|
|
|
|
|
|
input_json=body.input,
|
|
|
|
|
|
parameters=parameters,
|
|
|
|
|
|
request_key=key,
|
|
|
|
|
|
request_hash=fingerprint,
|
|
|
|
|
|
batch_index=index,
|
|
|
|
|
|
upstream_key="cmvr-visual:" + job_id,
|
|
|
|
|
|
scheduled_at=scheduled,
|
|
|
|
|
|
next_action_at=scheduled if future else utcnow(),
|
|
|
|
|
|
attempt_count=0,
|
|
|
|
|
|
work_attempt=0,
|
|
|
|
|
|
preemptions=0,
|
|
|
|
|
|
cancel_requested=False,
|
|
|
|
|
|
)
|
|
|
|
|
|
session.add(job)
|
|
|
|
|
|
await session.flush()
|
|
|
|
|
|
session.add_all((JobAsset(job_id=job.id, asset_id=asset_id) for asset_id in ids))
|
|
|
|
|
|
await emit_job(session, job, increment=False)
|
|
|
|
|
|
jobs.append(job)
|
|
|
|
|
|
if record is not None:
|
|
|
|
|
|
record.resource_json = {"job_ids": [job.id for job in jobs]}
|
|
|
|
|
|
return jobs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def wake(runtime):
|
|
|
|
|
|
runtime.coordinator.wake()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def submit(body: Submit, runtime, idempotency_key: str | None = None, actor: Actor = None):
|
|
|
|
|
|
recovering = False
|
|
|
|
|
|
if idempotency_key:
|
|
|
|
|
|
async with runtime.db.session() as session:
|
|
|
|
|
|
recovering = bool(
|
|
|
|
|
|
await session.scalar(
|
|
|
|
|
|
select(Job.id)
|
|
|
|
|
|
.where(Job.owner_id == actor.id, Job.request_key == idempotency_key)
|
|
|
|
|
|
.limit(1)
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
2026-11-26 21:06:27 +08:00
|
|
|
|
from app.domain.video_generation import H3_TP2_PROFILE
|
|
|
|
|
|
from app.adapters.provider.contracts import h3_tp2_available, H3_TP2_CERTIFICATION_REASON
|
|
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
|
not recovering
|
|
|
|
|
|
and body.task_type == "video.generate"
|
|
|
|
|
|
and body.parameters.get("profile") == H3_TP2_PROFILE
|
|
|
|
|
|
and not await h3_tp2_available(runtime.provider, runtime.settings)
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(503, "capability_unavailable", H3_TP2_CERTIFICATION_REASON)
|
2026-11-14 14:07:26 +08:00
|
|
|
|
if body.execution_mode == "batch" and body.task_type in GPU_TYPES and (not recovering):
|
|
|
|
|
|
provider = runtime.provider
|
|
|
|
|
|
capabilities = (
|
|
|
|
|
|
await provider.upstream_capabilities()
|
|
|
|
|
|
if hasattr(provider, "upstream_capabilities")
|
|
|
|
|
|
else {}
|
|
|
|
|
|
)
|
|
|
|
|
|
if capabilities.get("protocol_version", 0) < 2 or not capabilities.get(
|
|
|
|
|
|
"admission_policy", False
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(503, "upstream_protocol_incompatible", "Batch requires scheduling protocol v2")
|
|
|
|
|
|
async with runtime.db.session() as session:
|
|
|
|
|
|
try:
|
|
|
|
|
|
jobs = await create_jobs(session, body, actor, runtime.settings, idempotency_key)
|
|
|
|
|
|
await session.commit()
|
|
|
|
|
|
except IntegrityError:
|
|
|
|
|
|
await session.rollback()
|
|
|
|
|
|
jobs = await create_jobs(session, body, actor, runtime.settings, idempotency_key)
|
|
|
|
|
|
await session.commit()
|
|
|
|
|
|
result = {"jobs": [await job_dto(session, job) for job in jobs]}
|
|
|
|
|
|
wake(runtime)
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def list_jobs(
|
|
|
|
|
|
runtime,
|
|
|
|
|
|
page: int = 1,
|
|
|
|
|
|
page_size: int = 24,
|
|
|
|
|
|
task_type: str = "",
|
|
|
|
|
|
state: str = "",
|
|
|
|
|
|
root_only: bool = False,
|
|
|
|
|
|
actor: Actor = None,
|
|
|
|
|
|
folder_id: str = "",
|
|
|
|
|
|
):
|
|
|
|
|
|
if page < 1 or not 1 <= page_size <= 100:
|
|
|
|
|
|
fail(422, "invalid_page", "分页参数无效")
|
|
|
|
|
|
async with runtime.db.session() as session:
|
|
|
|
|
|
query = select(Job).where(Job.owner_id == actor.id, Job.deleted_at.is_(None))
|
|
|
|
|
|
from app.services.folders import folder_filter
|
|
|
|
|
|
|
|
|
|
|
|
query = query.where(await folder_filter(session, Job, actor.id, folder_id))
|
|
|
|
|
|
if root_only:
|
|
|
|
|
|
query = query.where(Job.run_id.is_(None))
|
|
|
|
|
|
if task_type:
|
|
|
|
|
|
query = query.where(Job.task_type == task_type)
|
|
|
|
|
|
if state:
|
|
|
|
|
|
query = query.where(Job.state == state)
|
|
|
|
|
|
total = await session.scalar(select(func.count()).select_from(query.subquery()))
|
|
|
|
|
|
jobs = (
|
|
|
|
|
|
await session.scalars(
|
|
|
|
|
|
query.order_by(Job.created_at.desc(), Job.id.desc())
|
|
|
|
|
|
.offset((page - 1) * page_size)
|
|
|
|
|
|
.limit(page_size)
|
|
|
|
|
|
)
|
|
|
|
|
|
).all()
|
|
|
|
|
|
cursor = (
|
|
|
|
|
|
await session.scalar(select(func.max(Event.id)).where(Event.owner_id == actor.id)) or 0
|
|
|
|
|
|
)
|
|
|
|
|
|
return {
|
|
|
|
|
|
"items": [await job_dto(session, job) for job in jobs],
|
|
|
|
|
|
"total": total,
|
|
|
|
|
|
"page": page,
|
|
|
|
|
|
"page_size": page_size,
|
|
|
|
|
|
"cursor": cursor,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def get_job(job_id: str, runtime, actor: Actor = None):
|
|
|
|
|
|
async with runtime.db.session() as session:
|
|
|
|
|
|
return await job_dto(session, await owned_job(session, job_id, actor.id))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def delete_job(job_id: str, runtime, if_match: str | None = None, actor: Actor = None):
|
|
|
|
|
|
from app.services.deletions import archive_records
|
|
|
|
|
|
|
|
|
|
|
|
async with runtime.db.session() as session:
|
|
|
|
|
|
result = await archive_records(session, Job, job_id, actor.id, if_match)
|
|
|
|
|
|
await session.commit()
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def cancel(job_id: str, runtime, actor: Actor = None):
|
|
|
|
|
|
async with runtime.db.session() as session:
|
|
|
|
|
|
job = await owned_job(session, job_id, actor.id)
|
|
|
|
|
|
if job.state not in TERMINAL and job.state != "collecting":
|
|
|
|
|
|
job.cancel_requested = True
|
|
|
|
|
|
if (
|
|
|
|
|
|
job.upstream_id is None
|
|
|
|
|
|
and job.upstream_payload is None
|
|
|
|
|
|
and (job.phase not in {"cpu_running", "preparing"})
|
|
|
|
|
|
):
|
|
|
|
|
|
job.state, job.phase, job.finished_at = ("cancelled", "cancelled", utcnow())
|
|
|
|
|
|
else:
|
|
|
|
|
|
job.state, job.phase = ("cancelling", "cancellation_pending")
|
|
|
|
|
|
await emit_job(session, job)
|
|
|
|
|
|
await session.commit()
|
|
|
|
|
|
result = await job_dto(session, job)
|
|
|
|
|
|
wake(runtime)
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def retry(job_id: str, runtime, idempotency_key: str | None = None, actor: Actor = None):
|
|
|
|
|
|
async with runtime.db.session() as session:
|
|
|
|
|
|
old = await owned_job(session, job_id, actor.id)
|
|
|
|
|
|
if old.state not in TERMINAL:
|
|
|
|
|
|
fail(409, "job_not_finished", "请先等待或取消当前任务")
|
|
|
|
|
|
if old.run_id:
|
|
|
|
|
|
fail(409, "workflow_child", "Use workflow step retry")
|
|
|
|
|
|
if old.batch_id:
|
|
|
|
|
|
fail(409, "parent_control_required", "Batch members require parent control")
|
|
|
|
|
|
from app.services.submissions import accept_submission
|
|
|
|
|
|
|
|
|
|
|
|
record = (
|
|
|
|
|
|
await accept_submission(
|
|
|
|
|
|
session, actor.id, "jobs.retry", idempotency_key, 2, {"job_id": job_id}
|
|
|
|
|
|
)
|
|
|
|
|
|
if idempotency_key
|
|
|
|
|
|
else None
|
|
|
|
|
|
)
|
|
|
|
|
|
if record and record.resource_json.get("job_ids"):
|
|
|
|
|
|
jobs = list(
|
|
|
|
|
|
(
|
|
|
|
|
|
await session.scalars(
|
|
|
|
|
|
select(Job).where(
|
|
|
|
|
|
Job.owner_id == actor.id,
|
|
|
|
|
|
Job.id.in_(record.resource_json["job_ids"]),
|
|
|
|
|
|
Job.deleted_at.is_(None),
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
).all()
|
|
|
|
|
|
)
|
|
|
|
|
|
if len(jobs) != len(record.resource_json["job_ids"]):
|
|
|
|
|
|
fail(410, "resource_purged", "重试任务已删除")
|
|
|
|
|
|
return {"jobs": [await job_dto(session, job) for job in jobs]}
|
|
|
|
|
|
from app.models import Execution
|
|
|
|
|
|
|
|
|
|
|
|
unsafe = await session.scalar(
|
|
|
|
|
|
select(Execution.id)
|
|
|
|
|
|
.where(
|
|
|
|
|
|
Execution.job_id == old.id,
|
|
|
|
|
|
Execution.state.in_(["allocated", "running", "stopping", "unknown"]),
|
|
|
|
|
|
)
|
|
|
|
|
|
.limit(1)
|
|
|
|
|
|
)
|
|
|
|
|
|
if unsafe:
|
|
|
|
|
|
fail(409, "cleanup_pending", "Previous execution has not confirmed cleanup")
|
|
|
|
|
|
body = Submit(
|
|
|
|
|
|
folder_id=old.folder_id,
|
|
|
|
|
|
output_folder_id=old.output_folder_id,
|
|
|
|
|
|
task_type=old.task_type,
|
|
|
|
|
|
input=old.input_json,
|
|
|
|
|
|
parameters={k: v for k, v in old.parameters.items() if k != "_video_edit_binding"},
|
|
|
|
|
|
execution_mode=old.execution_mode,
|
|
|
|
|
|
)
|
|
|
|
|
|
jobs = await create_jobs(session, body, actor, runtime.settings)
|
|
|
|
|
|
if record:
|
|
|
|
|
|
record.resource_json = {"job_ids": [j.id for j in jobs]}
|
|
|
|
|
|
await session.commit()
|
|
|
|
|
|
result = {"jobs": [await job_dto(session, job) for job in jobs]}
|
|
|
|
|
|
wake(runtime)
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def resolve_analysis_binding(session, inputs, parameters, owner_id, settings):
|
|
|
|
|
|
from app.domain.video_editing import safe_analysis, video_defaults
|
|
|
|
|
|
from app.domain.errors import MediaError
|
|
|
|
|
|
|
|
|
|
|
|
analysis = await owned_job(session, inputs["analysis_job_id"], owner_id)
|
|
|
|
|
|
if (
|
|
|
|
|
|
analysis.task_type != "video.people.analyze"
|
|
|
|
|
|
or analysis.state != "succeeded"
|
|
|
|
|
|
or not analysis.upstream_id
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(422, "invalid_analysis", "请选择已成功的人物分析任务")
|
|
|
|
|
|
source = await owned_asset(session, inputs["video_asset_id"], owner_id)
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = safe_analysis(analysis.result_json, settings)
|
|
|
|
|
|
except MediaError as exc:
|
|
|
|
|
|
fail(422, exc.code, exc.message)
|
|
|
|
|
|
p = video_defaults("video.replace", settings) | parameters
|
|
|
|
|
|
a = video_defaults("video.people.analyze", settings) | analysis.parameters
|
|
|
|
|
|
if (
|
|
|
|
|
|
analysis.input_json.get("video_asset_id") != source.id
|
|
|
|
|
|
or result["source_sha256"] != source.sha256
|
|
|
|
|
|
or any(a[k] != p[k] for k in ("profile", "max_pixels", "fps"))
|
|
|
|
|
|
or result["video"]["width"] * result["video"]["height"] > p["max_pixels"]
|
|
|
|
|
|
or any(result["video"][key] % 16 for key in ("width", "height"))
|
|
|
|
|
|
):
|
|
|
|
|
|
fail(422, "analysis_source_mismatch", "人物分析与源视频或画面规格不一致,请重新分析")
|
|
|
|
|
|
people = {row["id"] for row in result["people"]}
|
|
|
|
|
|
if any(row["person_id"] not in people for row in inputs["replacements"]):
|
|
|
|
|
|
fail(422, "unknown_person", "所选人物不属于此视频分析")
|
|
|
|
|
|
from app.adapters.media import inspect_media
|
|
|
|
|
|
from app.adapters.storage import confined
|
|
|
|
|
|
from app.services.artifacts import digest_file
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
|
|
|
|
path = confined(settings.asset_root, source.storage_key, exists=True)
|
|
|
|
|
|
if await asyncio.to_thread(digest_file, path) != source.sha256:
|
|
|
|
|
|
fail(422, "analysis_source_mismatch", "源视频字节已变更")
|
|
|
|
|
|
from app.adapters.media import inspect_video_timeline
|
|
|
|
|
|
|
|
|
|
|
|
duration = await inspect_video_timeline(path, settings)
|
|
|
|
|
|
if abs(result["video"]["duration_seconds"] - duration) > 1 / 24 + 0.05:
|
|
|
|
|
|
fail(422, "analysis_source_mismatch", "人物分析与源视频时间轴不一致")
|
|
|
|
|
|
info = await inspect_media(path, settings)
|
|
|
|
|
|
from app.services.video_editing import audio_duration
|
|
|
|
|
|
|
|
|
|
|
|
source_audio_duration = (
|
|
|
|
|
|
await audio_duration(path, settings, fallback=info["duration_seconds"])
|
|
|
|
|
|
if info.get("has_audio")
|
|
|
|
|
|
else None
|
|
|
|
|
|
)
|
|
|
|
|
|
references = {}
|
|
|
|
|
|
for row in inputs["replacements"]:
|
|
|
|
|
|
image = await owned_asset(session, row["reference_asset_id"], owner_id)
|
|
|
|
|
|
if image.kind != "image":
|
|
|
|
|
|
fail(422, "wrong_asset_kind", "人物参考素材必须为图片")
|
|
|
|
|
|
references[image.id] = image.sha256
|
|
|
|
|
|
return {
|
|
|
|
|
|
"source_has_audio": bool(info.get("has_audio")),
|
|
|
|
|
|
"source_audio_duration": source_audio_duration,
|
|
|
|
|
|
"source_video_duration": duration,
|
|
|
|
|
|
"reference_sha256": references,
|
|
|
|
|
|
"analysis_id": analysis.upstream_id,
|
|
|
|
|
|
"analysis_token": result["analysis_token"],
|
|
|
|
|
|
"source_sha256": source.sha256,
|
|
|
|
|
|
"profile": result["profile"],
|
|
|
|
|
|
"video": result["video"],
|
|
|
|
|
|
"owner_id": owner_id,
|
|
|
|
|
|
}
|