2026-11-14 14:07:26 +08:00
|
|
|
|
"""GPU 任务准备、幂等提交与远端控制。"""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
|
import os
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
import re
|
|
|
|
|
|
import time
|
|
|
|
|
|
import uuid
|
|
|
|
|
|
|
|
|
|
|
|
from app.adapters.media import input_options, inspect_media, run_process
|
|
|
|
|
|
from app.domain.execution import enter_phase
|
|
|
|
|
|
from app.domain.errors import MediaError as ProviderError
|
|
|
|
|
|
from .contracts import _invalid, _keys, _int, _float, _string
|
|
|
|
|
|
from .contracts import GPU_TASKS, LANGUAGES, capabilities, validate_arguments
|
2026-11-26 21:06:27 +08:00
|
|
|
|
from .contracts import h3_tp2_available, H3_TP2_CERTIFICATION_REASON
|
2026-11-14 14:07:26 +08:00
|
|
|
|
from .transport import _url
|
2026-11-26 21:06:27 +08:00
|
|
|
|
from app.domain import video_generation as video_profiles
|
|
|
|
|
|
from .video_generation import normalize as normalize_video
|
2026-11-14 14:07:26 +08:00
|
|
|
|
|
|
|
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
|
|
from .client import Provider
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-26 21:06:27 +08:00
|
|
|
|
H3_VIDEO_TIMEOUT_SECONDS = 21600
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-14 14:07:26 +08:00
|
|
|
|
async def prepare_gpu_payload(
|
|
|
|
|
|
provider: Provider, task_type, inputs, parameters, assets, work_dir, *, analysis_binding=None
|
|
|
|
|
|
):
|
|
|
|
|
|
validate_arguments(task_type, inputs, parameters, provider.settings)
|
|
|
|
|
|
work = provider._work(work_dir)
|
|
|
|
|
|
if task_type not in GPU_TASKS:
|
|
|
|
|
|
raise _invalid("不支持此模型任务类型。")
|
|
|
|
|
|
if task_type in {"video.people.analyze", "video.replace"}:
|
|
|
|
|
|
from .video_editing import prepare_video
|
|
|
|
|
|
|
|
|
|
|
|
return await prepare_video(
|
|
|
|
|
|
provider, task_type, inputs, parameters, assets, analysis_binding
|
|
|
|
|
|
)
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if task_type == "video.generate":
|
|
|
|
|
|
p = normalize_video(parameters, inputs)
|
|
|
|
|
|
if p.get("profile") == video_profiles.H3_TP2_PROFILE and not await h3_tp2_available(
|
|
|
|
|
|
provider, provider.settings
|
|
|
|
|
|
):
|
|
|
|
|
|
raise ProviderError("capability_unavailable", H3_TP2_CERTIFICATION_REASON)
|
|
|
|
|
|
out = {"prompt": inputs["prompt"]}
|
|
|
|
|
|
if video_profiles.profile_name(p) not in video_profiles.H3_PROFILES:
|
|
|
|
|
|
out["negative_prompt"] = p.pop("negative_prompt", inputs.get("negative_prompt", ""))
|
|
|
|
|
|
for field, target in (
|
|
|
|
|
|
("image_asset_id", "image_path"),
|
|
|
|
|
|
("first_frame_asset_id", "image_path"),
|
|
|
|
|
|
("last_frame_asset_id", "last_image_path"),
|
|
|
|
|
|
):
|
|
|
|
|
|
if field not in inputs:
|
|
|
|
|
|
continue
|
|
|
|
|
|
source = provider._asset(inputs[field], assets)
|
|
|
|
|
|
if (await inspect_media(source, provider.settings))["kind"] != "image":
|
|
|
|
|
|
raise _invalid("参考素材必须是图片。")
|
|
|
|
|
|
out[target] = (
|
|
|
|
|
|
await provider._upload_input(Path(source))
|
|
|
|
|
|
if getattr(provider.settings, "inference_remote_files", False)
|
|
|
|
|
|
else str(source)
|
|
|
|
|
|
)
|
|
|
|
|
|
# 官方BF16卸载运行较慢;仅新编译的显式H3请求使用六小时预算。
|
|
|
|
|
|
timeout = (
|
|
|
|
|
|
H3_VIDEO_TIMEOUT_SECONDS if p.get("profile") in video_profiles.H3_PROFILES else 3600
|
|
|
|
|
|
)
|
|
|
|
|
|
return {"task_type": task_type, "input": out, "parameters": p, "timeout_seconds": timeout}
|
2026-11-14 14:07:26 +08:00
|
|
|
|
if task_type == "image.reference.generate":
|
|
|
|
|
|
defaults = next(
|
|
|
|
|
|
item["defaults"]
|
|
|
|
|
|
for item in capabilities(provider.settings)
|
|
|
|
|
|
if item["task_type"] == task_type
|
|
|
|
|
|
)
|
|
|
|
|
|
upstream = (await provider.upstream_capabilities()).get("reference_generation", {})
|
|
|
|
|
|
maximum = upstream.get("max_reference_images")
|
|
|
|
|
|
if (
|
|
|
|
|
|
upstream.get("available") is not True
|
|
|
|
|
|
or upstream.get("profile") != defaults["profile"]
|
|
|
|
|
|
or type(maximum) is not int
|
|
|
|
|
|
or maximum < 1
|
|
|
|
|
|
):
|
|
|
|
|
|
raise ProviderError("capability_unavailable", "上游多图生成尚未认证或模型版本不匹配。")
|
|
|
|
|
|
if len(inputs["reference_asset_ids"]) > maximum:
|
|
|
|
|
|
raise _invalid("参考图片数量超出上游已认证范围。")
|
|
|
|
|
|
# 先逐张解码确认全部可用,再上传;不能在中途缺图时退回文生图。
|
|
|
|
|
|
paths = []
|
|
|
|
|
|
for asset_id in inputs["reference_asset_ids"]:
|
|
|
|
|
|
source = provider._asset(asset_id, assets)
|
|
|
|
|
|
if (await inspect_media(source, provider.settings))["kind"] != "image":
|
|
|
|
|
|
raise _invalid("全部参考素材必须是有效图片。")
|
|
|
|
|
|
paths.append(str(source))
|
|
|
|
|
|
if getattr(provider.settings, "inference_remote_files", False):
|
|
|
|
|
|
paths = [await provider._upload_input(Path(path)) for path in paths]
|
|
|
|
|
|
return {
|
|
|
|
|
|
"task_type": task_type,
|
|
|
|
|
|
"input": {
|
|
|
|
|
|
"prompt": inputs["prompt"],
|
|
|
|
|
|
"negative_prompt": inputs.get("negative_prompt", ""),
|
|
|
|
|
|
"image_paths": paths,
|
|
|
|
|
|
},
|
|
|
|
|
|
"parameters": {**defaults, **parameters},
|
|
|
|
|
|
"timeout_seconds": 3600,
|
|
|
|
|
|
}
|
|
|
|
|
|
p = dict(parameters) if isinstance(parameters, dict) else parameters
|
|
|
|
|
|
allowed_input = (
|
|
|
|
|
|
{"audio_asset_id", "asset_id"}
|
|
|
|
|
|
if task_type == "audio.transcribe"
|
|
|
|
|
|
else {"prompt", "negative_prompt"}
|
|
|
|
|
|
)
|
|
|
|
|
|
if task_type in {"video.generate", "defect.generate"}:
|
|
|
|
|
|
allowed_input.add("image_asset_id")
|
|
|
|
|
|
_keys(inputs, allowed_input)
|
|
|
|
|
|
defaults = next(
|
|
|
|
|
|
item["defaults"]
|
|
|
|
|
|
for item in capabilities(provider.settings)
|
|
|
|
|
|
if item["task_type"] == task_type
|
|
|
|
|
|
)
|
|
|
|
|
|
_keys(p, set(defaults) | ({"negative_prompt"} if task_type != "audio.transcribe" else set()))
|
|
|
|
|
|
normalized = {**defaults, **p}
|
|
|
|
|
|
out = {}
|
|
|
|
|
|
if task_type == "audio.transcribe":
|
|
|
|
|
|
asset_id = inputs.get("audio_asset_id") or inputs.get("asset_id")
|
|
|
|
|
|
if (
|
|
|
|
|
|
inputs.get("audio_asset_id")
|
|
|
|
|
|
and inputs.get("asset_id")
|
|
|
|
|
|
and inputs["audio_asset_id"] != inputs["asset_id"]
|
|
|
|
|
|
):
|
|
|
|
|
|
raise _invalid("请仅选择一个转写素材。")
|
|
|
|
|
|
source = provider._asset(asset_id, assets)
|
|
|
|
|
|
info = await inspect_media(source, provider.settings)
|
|
|
|
|
|
if normalized["language"] not in LANGUAGES:
|
|
|
|
|
|
raise _invalid("不支持此转写语言。")
|
|
|
|
|
|
_int(normalized["max_audio_seconds"], 1, 1800)
|
|
|
|
|
|
if (
|
|
|
|
|
|
info["kind"] not in {"audio", "video"}
|
|
|
|
|
|
or info["duration_seconds"] > normalized["max_audio_seconds"]
|
|
|
|
|
|
):
|
|
|
|
|
|
raise _invalid("请选择时长受限的音频或有声视频。")
|
|
|
|
|
|
if info["kind"] == "video":
|
|
|
|
|
|
await enter_phase("extract_audio", "cpu_media")
|
|
|
|
|
|
target = work / "asr-input.wav"
|
|
|
|
|
|
temporary = work / ("asr-" + uuid.uuid4().hex + ".wav")
|
|
|
|
|
|
try:
|
|
|
|
|
|
await run_process(
|
|
|
|
|
|
[
|
|
|
|
|
|
provider.settings.ffmpeg_bin,
|
|
|
|
|
|
"-v",
|
|
|
|
|
|
"error",
|
|
|
|
|
|
"-nostdin",
|
|
|
|
|
|
*input_options(),
|
|
|
|
|
|
"-i",
|
|
|
|
|
|
str(source),
|
|
|
|
|
|
"-map",
|
|
|
|
|
|
"0:a:0",
|
|
|
|
|
|
"-vn",
|
|
|
|
|
|
"-ac",
|
|
|
|
|
|
"1",
|
|
|
|
|
|
"-ar",
|
|
|
|
|
|
"16000",
|
|
|
|
|
|
"-c:a",
|
|
|
|
|
|
"pcm_s16le",
|
|
|
|
|
|
"-t",
|
|
|
|
|
|
str(normalized["max_audio_seconds"]),
|
|
|
|
|
|
"-threads",
|
|
|
|
|
|
"2",
|
|
|
|
|
|
str(temporary),
|
|
|
|
|
|
],
|
|
|
|
|
|
timeout=300,
|
|
|
|
|
|
)
|
|
|
|
|
|
if not temporary.is_file() or not temporary.stat().st_size:
|
|
|
|
|
|
raise _invalid("视频没有可转写的音轨。")
|
|
|
|
|
|
os.replace(temporary, target)
|
|
|
|
|
|
finally:
|
|
|
|
|
|
temporary.unlink(missing_ok=True)
|
|
|
|
|
|
source = target
|
|
|
|
|
|
await enter_phase("transcribe", "new_gpu")
|
|
|
|
|
|
out["audio_path"] = str(source)
|
|
|
|
|
|
else:
|
|
|
|
|
|
out["prompt"] = _string(inputs.get("prompt"))
|
|
|
|
|
|
out["negative_prompt"] = _string(
|
|
|
|
|
|
normalized.pop("negative_prompt", inputs.get("negative_prompt", "")), required=False
|
|
|
|
|
|
)
|
|
|
|
|
|
video = task_type == "video.generate"
|
|
|
|
|
|
for key in ("width", "height"):
|
|
|
|
|
|
_int(normalized[key], 256, 1280 if video else 2048, 32 if video else 16)
|
|
|
|
|
|
if normalized["width"] * normalized["height"] > (1280 * 704 if video else 2048 * 2048):
|
|
|
|
|
|
raise _invalid("画面像素总数超出服务限制。")
|
|
|
|
|
|
_int(normalized["num_inference_steps"], 1, 100)
|
|
|
|
|
|
_int(normalized["seed"], 0, 2**32 - 1)
|
|
|
|
|
|
normalized["guidance_scale"] = _float(normalized["guidance_scale"], 1, 20)
|
|
|
|
|
|
if "image_asset_id" in inputs:
|
|
|
|
|
|
source = provider._asset(inputs["image_asset_id"], assets)
|
|
|
|
|
|
if (await inspect_media(source, provider.settings))["kind"] != "image":
|
|
|
|
|
|
raise _invalid("参考素材必须是图片。")
|
|
|
|
|
|
out["image_path"] = str(source)
|
|
|
|
|
|
if task_type == "defect.generate":
|
|
|
|
|
|
if "image_path" not in out:
|
|
|
|
|
|
raise _invalid("条件样本任务需要参考图片。")
|
|
|
|
|
|
normalized["controlnet_conditioning_scale"] = _float(
|
|
|
|
|
|
normalized["controlnet_conditioning_scale"], 0, 2
|
|
|
|
|
|
)
|
|
|
|
|
|
_int(normalized["canny_low"], 0, 255)
|
|
|
|
|
|
_int(normalized["canny_high"], 0, 255)
|
|
|
|
|
|
if normalized["canny_low"] >= normalized["canny_high"]:
|
|
|
|
|
|
raise _invalid("Canny低阈值必须小于高阈值。")
|
|
|
|
|
|
if video:
|
|
|
|
|
|
_int(normalized["num_frames"], 5, 361)
|
|
|
|
|
|
if (
|
|
|
|
|
|
normalized["num_frames"] % 4 != 1
|
|
|
|
|
|
or type(normalized["fps"]) is not int
|
|
|
|
|
|
or normalized["fps"] != 24
|
|
|
|
|
|
):
|
|
|
|
|
|
raise _invalid("视频仅支持4n+1帧、最多361帧和24fps。")
|
|
|
|
|
|
if type(normalized["upscale"]) is not bool:
|
|
|
|
|
|
raise _invalid("增强开关必须为布尔值。")
|
|
|
|
|
|
_int(normalized["upscale_width"], 256, 3840, 2)
|
|
|
|
|
|
_int(normalized["upscale_height"], 256, 2160, 2)
|
|
|
|
|
|
_int(normalized["tile_size"], 64, 256, 16)
|
|
|
|
|
|
if getattr(provider.settings, "inference_remote_files", False):
|
|
|
|
|
|
for key in ("image_path", "audio_path"):
|
|
|
|
|
|
if key in out:
|
|
|
|
|
|
out[key] = await provider._upload_input(Path(out[key]))
|
|
|
|
|
|
return {"task_type": task_type, "input": out, "parameters": normalized, "timeout_seconds": 3600}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def submit(provider: Provider, payload, idempotency_key):
|
|
|
|
|
|
# 响应丢失后的恢复必须使用相同请求体与幂等键,不能隐式创建第二个模型任务。
|
2026-11-26 21:06:27 +08:00
|
|
|
|
if (
|
|
|
|
|
|
payload.get("task_type") == "video.generate"
|
|
|
|
|
|
and payload.get("parameters", {}).get("profile") == video_profiles.H3_TP2_PROFILE
|
|
|
|
|
|
and not await h3_tp2_available(provider, provider.settings)
|
|
|
|
|
|
):
|
|
|
|
|
|
raise ProviderError("capability_unavailable", H3_TP2_CERTIFICATION_REASON)
|
2026-11-14 14:07:26 +08:00
|
|
|
|
_string(idempotency_key, 128)
|
|
|
|
|
|
if any(not 33 <= ord(char) <= 126 for char in idempotency_key):
|
|
|
|
|
|
raise _invalid("幂等请求标识无效。")
|
|
|
|
|
|
return provider._sanitize_job(
|
|
|
|
|
|
await provider._json(
|
|
|
|
|
|
"POST",
|
|
|
|
|
|
_url(provider.settings.inference_base_url, "/jobs"),
|
|
|
|
|
|
payload=payload,
|
|
|
|
|
|
headers={**provider._headers(), "Idempotency-Key": idempotency_key},
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _job_id(value):
|
|
|
|
|
|
if not isinstance(value, str) or re.fullmatch(r"[0-9a-f]{32}", value) is None:
|
|
|
|
|
|
raise _invalid("模型任务标识无效。")
|
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _sanitize_job(value):
|
|
|
|
|
|
if value.get("error"):
|
|
|
|
|
|
value["error"] = "模型任务执行失败,请检查任务输入或联系管理员。"
|
|
|
|
|
|
if value.get("last_preempted_reason"):
|
|
|
|
|
|
value["last_preempted_reason"] = "GPU资源已让出,任务重新排队。"
|
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def query(provider: Provider, upstream_id):
|
|
|
|
|
|
return provider._sanitize_job(
|
|
|
|
|
|
await provider._json(
|
|
|
|
|
|
"GET",
|
|
|
|
|
|
_url(provider.settings.inference_base_url, "/jobs/" + provider._job_id(upstream_id)),
|
|
|
|
|
|
headers=provider._headers(),
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def upstream_capabilities(provider: Provider):
|
|
|
|
|
|
cached = getattr(provider, "_capabilities_cache", None)
|
|
|
|
|
|
if cached and time.monotonic() - cached[0] < 30:
|
|
|
|
|
|
return json.loads(json.dumps(cached[1]))
|
|
|
|
|
|
value = await provider._json(
|
|
|
|
|
|
"GET",
|
|
|
|
|
|
_url(provider.settings.inference_base_url, "/capabilities"),
|
|
|
|
|
|
headers=provider._headers(),
|
|
|
|
|
|
)
|
|
|
|
|
|
features = value.get("features", {})
|
|
|
|
|
|
value["admission_policy"] = bool(
|
|
|
|
|
|
value.get("admission_policy")
|
|
|
|
|
|
or (features.get("scheduling") and features.get("admission_pause"))
|
|
|
|
|
|
)
|
|
|
|
|
|
provider._capabilities_cache = (time.monotonic(), value)
|
|
|
|
|
|
return json.loads(json.dumps(value))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def control(
|
|
|
|
|
|
provider: Provider,
|
|
|
|
|
|
upstream_id,
|
|
|
|
|
|
desired_state,
|
|
|
|
|
|
command_id,
|
|
|
|
|
|
expected_version=None,
|
|
|
|
|
|
expected_execution_id=None,
|
|
|
|
|
|
):
|
|
|
|
|
|
if desired_state not in {"run", "pause", "cancel"}:
|
|
|
|
|
|
raise _invalid("Invalid control intention.")
|
|
|
|
|
|
_string(command_id, 128)
|
|
|
|
|
|
payload = {"desired_state": desired_state, "command_id": command_id}
|
|
|
|
|
|
if expected_version is not None:
|
|
|
|
|
|
payload["expected_version"] = _int(expected_version, 0, 2**63 - 1)
|
|
|
|
|
|
if expected_execution_id is not None:
|
|
|
|
|
|
payload["expected_execution_id"] = _string(expected_execution_id, 64)
|
|
|
|
|
|
return provider._sanitize_job(
|
|
|
|
|
|
await provider._json(
|
|
|
|
|
|
"PUT",
|
|
|
|
|
|
_url(
|
|
|
|
|
|
provider.settings.inference_base_url,
|
|
|
|
|
|
"/jobs/" + provider._job_id(upstream_id) + "/control",
|
|
|
|
|
|
),
|
|
|
|
|
|
payload=payload,
|
|
|
|
|
|
headers=provider._headers(),
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def cancel(provider: Provider, upstream_id):
|
|
|
|
|
|
return provider._sanitize_job(
|
|
|
|
|
|
await provider._json(
|
|
|
|
|
|
"POST",
|
|
|
|
|
|
_url(
|
|
|
|
|
|
provider.settings.inference_base_url,
|
|
|
|
|
|
"/jobs/" + provider._job_id(upstream_id) + "/cancel",
|
|
|
|
|
|
),
|
|
|
|
|
|
headers=provider._headers(),
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|