895 lines
50 KiB
Python
895 lines
50 KiB
Python
r"""ComfyUI 适配器:把「ComfyUI 工作流」接成平台统一的视频生成契约。
|
||
|
||
适用场景:自建 ComfyUI(如 MiniMax H3 / Wan / Hunyuan 等本地大模型)已通过
|
||
ComfyUI 暴露 /prompt、/history、/view、/upload/image 接口。
|
||
|
||
与通用 HTTP 适配器的区别:ComfyUI 的「一次生成」是一段节点图(graph),
|
||
所以这里做的事是——按请求把参数注入节点图 → 提交 /prompt → 轮询 /history →
|
||
用 /view 下载产物。图2 的「调用视频模型 → 下载并保存视频」两个节点因此仍然
|
||
由平台统一编排(重试、限流、心跳、成本留痕都在调度中心,不在这里)。
|
||
|
||
config_json(模型注册表里可视化编辑,全部可省略走默认值):
|
||
{
|
||
"base_url": "http://10.100.53.199:9200",
|
||
"workflow": "minimax_h3", # 内置图模板,见 WORKFLOW_TEMPLATES
|
||
"models": { # 各槽位的模型文件名(不同机器不一样)
|
||
"unet": "MiniMax-H3-REF2VA-Q4_K_M.gguf",
|
||
"clip": "qwen3vl-32B-MiniMax-H3-Q4_K_M.gguf",
|
||
"clip_type": "minimax",
|
||
"video_vae": "minimax_h3_video_vae_fp16.safetensors",
|
||
"audio_vae": "minimax_h3_audio_vae_fp32.safetensors"
|
||
},
|
||
"steps": 20, "sampler": "res_multistep", "scheduler": "simple", "denoise": 1.0,
|
||
"fps": 24, "megapixels": 0.98, "multiple": 32, "max_edge": 1344,
|
||
"resolution_policy": "config", # config=完全照 megapixels(默认)/ tier=档位作下限 / budget=档位作上限
|
||
"lora": "minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors",
|
||
"lora_ref2v": "", "lora_i2v": "", # 按节点分别指定;留空回落到 lora
|
||
"ref_image_size": "match", # max 会把参考图按 2048 短边编码,慢数倍
|
||
"input_subfolder": "nex_animation", # 关键帧上传到 ComfyUI 的 input 子目录
|
||
"filename_prefix": "nex/shot", # 产物写到 ComfyUI output 的子目录,便于清理
|
||
"poll_interval": 5, "timeout": 5400,
|
||
"use_reference_images": true, # 是否把定妆图/三视图/场景图喂给 r2v 节点
|
||
"reference_mode": "auto" # auto=关键帧与人物定妆图一起进参考图节点(默认)
|
||
# frame_only=旧行为:有关键帧就只按关键帧生成,丢弃定妆图
|
||
}
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import mimetypes
|
||
import threading
|
||
import time
|
||
from pathlib import Path
|
||
from typing import Any, Callable
|
||
from urllib.parse import urlencode
|
||
|
||
import httpx
|
||
|
||
from app.config import settings
|
||
from app.constants import RESOLUTIONS
|
||
from app.providers.base import (Capabilities, DurationGrid, FatalProviderError, ProviderError,
|
||
RateLimitedError, RetryableProviderError, VideoGenRequest,
|
||
VideoGenResult, VideoProviderAdapter)
|
||
from app.providers.comfy_common import client as comfy_client
|
||
from app.providers.comfy_common import diagnosis_message, is_network_error
|
||
from app.providers.comfy_common import (OutageTracker, gpu_slot, network_guard, require_reachable,
|
||
tolerant_json)
|
||
from app.services import ffmpeg as ff
|
||
|
||
DEFAULT_MODELS = {
|
||
"unet": "MiniMax-H3-REF2VA-Q4_K_M.gguf",
|
||
"clip": "qwen3vl-32B-MiniMax-H3-Q4_K_M.gguf",
|
||
"clip_type": "minimax",
|
||
"video_vae": "minimax_h3_video_vae_fp16.safetensors",
|
||
"audio_vae": "minimax_h3_audio_vae_fp32.safetensors",
|
||
}
|
||
|
||
# 每种模板声明:节点名 + 时长换算所需的帧率/分块粒度
|
||
WORKFLOW_TEMPLATES = {
|
||
"minimax_h3": {
|
||
"i2v_node": "MiniMaxH3ImageToVideo", # 首帧 / 首尾帧(t2v 时不连首帧即可)
|
||
"r2v_node": "MiniMaxH3ReferenceToVideo", # 参考图(定妆图/三视图/场景图)
|
||
"frame_fps": 24, "frame_step": 17, "frame_offset": 5, "frame_min": 5,
|
||
# 节点参数允许 min=5,但模型只在 124~362 帧上训练过(节点 tooltip 明示)。
|
||
"frame_min_trained": 124, "frame_max_trained": 362,
|
||
# **带台词镜头另设下限 73 帧(3.04s)**,比训练区间低一档。
|
||
# 理由不是「训练下限不算数」,而是两种代价不对称:
|
||
# 多留时间 ⇒ 音轨照样铺满 ⇒ 模型**必然**从 caption 里挑一段画面描述念出来
|
||
# (124 帧装 15 字台词,实测开头多出 1.5s「都市清新风格」);
|
||
# 少留时间 ⇒ 模型自己把语速从 3.7 字/秒提到 5.3 字/秒,实测字字清晰。
|
||
# 「精简提示词」这条路已用 2×2 实验证伪:删掉「都市清新风格」,
|
||
# 模型改念「医院诊室内」——它填的是空档,不是某个特定短语。
|
||
# 90/107/124 帧均已直提 ComfyUI 实测可用;73 帧见 reports 第二十章。
|
||
"frame_min_joint": 73,
|
||
"supports_audio": True, "max_refs": 6,
|
||
# 参考音频(角色音色样本)只有 r2v 节点收:i2v 节点连 audio_vae 都没有。
|
||
# 节点 tooltip 明示 max=3,多出来的角色声线按出镜优先级截断。
|
||
"max_ref_audios": 3,
|
||
# 交付档位:H3 官方(ComfyCloud 节点 / Turbo LoRA 文件名)只到 768p,
|
||
# ComfyUI 本地节点不钳像素但 2MP 画布实测卡时 ×2.3、画质无保证,
|
||
# 官方口径就是「原生 768p + 超分交付」。所以 1080p 列为放大交付档:
|
||
# 模型仍按原生像素出片,合成端 lanczos 放大到 1080p,不额外花卡时。
|
||
"upscale_to": ("1080p",),
|
||
},
|
||
}
|
||
|
||
|
||
def _template_of(config: dict | None) -> dict:
|
||
"""从模型注册表配置里取工作流模板声明(缺省 minimax_h3)。"""
|
||
cfg = config or {}
|
||
return WORKFLOW_TEMPLATES.get(str(cfg.get("workflow") or "minimax_h3"),
|
||
WORKFLOW_TEMPLATES["minimax_h3"])
|
||
|
||
|
||
def _dedupe_paths(paths: list[str]) -> list[str]:
|
||
seen: set[str] = set()
|
||
result: list[str] = []
|
||
for path in paths:
|
||
value = str(path or "").strip()
|
||
if not value or value in seen:
|
||
continue
|
||
seen.add(value)
|
||
result.append(value)
|
||
return result
|
||
|
||
|
||
def reference_inputs(request: VideoGenRequest, first: str, max_refs: int, *,
|
||
last: str = "", mode: str = "auto") -> list[str]:
|
||
"""决定本次视频生成实际使用的参考图。
|
||
|
||
H3 的参考图节点(r2v)与首帧节点(i2v)互斥:走 r2v 时关键帧不再是「首帧」,
|
||
而是与定妆图同批的条件图。旧实现只要有关键帧就直接 ``return []``,于是
|
||
「人物库里的定妆图/三视图」在 i2v 镜头里**一张都没进模型**——用户给角色
|
||
精心准备的母版素材只剩提示词里的一行中文描述,跨镜头长相自然对不上。
|
||
|
||
默认(``auto``):只要有人物/场景参考图,就把关键帧放在第 1 张、定妆图与
|
||
场景图跟在后面,一起交给 r2v 节点,兼顾构图锚定与身份一致性。
|
||
``frame_only`` 保留旧行为(首帧严格驱动,例如必须复刻关键帧的镜头)。
|
||
首尾帧(fl)模式 r2v 节点没有对应输入,始终按 i2v 处理。
|
||
"""
|
||
all_refs = _dedupe_paths(request.reference_images or [])
|
||
explicit = _dedupe_paths(request.explicit_reference_images or [])
|
||
mode = str(mode or "auto").strip().lower()
|
||
if mode not in ("auto", "frame_only"):
|
||
mode = "auto"
|
||
if mode == "frame_only" or last:
|
||
if explicit:
|
||
automatic = [path for path in all_refs if path not in explicit]
|
||
return _dedupe_paths([*explicit, *([first] if first else []), *automatic])[:max_refs]
|
||
if first:
|
||
return []
|
||
return all_refs[:max_refs]
|
||
if not all_refs:
|
||
return []
|
||
prioritized = [first] if first else []
|
||
if explicit:
|
||
automatic = [path for path in all_refs if path not in explicit]
|
||
prioritized += [*explicit, *automatic]
|
||
else:
|
||
prioritized += all_refs
|
||
return _dedupe_paths(prioritized)[:max_refs]
|
||
|
||
|
||
def _resolution_floor_mp(resolution: str | None) -> float:
|
||
"""项目档位对应的像素预算下限(面积,带 5% 对齐余量)。
|
||
|
||
余量是给 32 倍对齐用的:1280x720 的面积刚好卡在两个对齐档位之间,
|
||
不加余量时 round 会把短边压到 704,反而低于声明档位。
|
||
"""
|
||
if not resolution:
|
||
return 0.0
|
||
base = RESOLUTIONS.get(str(resolution))
|
||
if not base:
|
||
return 0.0
|
||
return float(base[0]) * float(base[1]) * 1.05
|
||
|
||
|
||
class WorkflowBuilder:
|
||
"""把平台请求翻译成 ComfyUI 的 prompt 图(API 格式,非 UI 格式)。
|
||
|
||
单独成类是为了让「换模型/换模板」只改这里,不影响调度、重试、质检等上层逻辑。
|
||
"""
|
||
|
||
def __init__(self, config: dict, template: dict):
|
||
self.config = config
|
||
self.tpl = template
|
||
self.models = {**DEFAULT_MODELS, **(config.get("models") or {})}
|
||
self.fps = float(config.get("fps") or template.get("frame_fps") or 24)
|
||
|
||
# ---------- 画布与时长 ----------
|
||
def canvas(self, aspect_ratio: str, resolution: str | None = None) -> tuple[int, int]:
|
||
"""按画幅与目标像素数求 H3 原生画布(multiple 的倍数,短边优先)。
|
||
|
||
画布**只由配置决定**:megapixels 是谁写的、为什么这么写,适配器无从判断,
|
||
也不该判断 —— model_specs 由控制台和其它进程按机型/任务维护,
|
||
这里任何「善意修正」都是在静默覆盖别人的决定。所以档位只在显式声明策略时参与:
|
||
tier —— 档位作下限(预算低于档位时抬到档位,不静默降档);
|
||
budget —— 档位作上限(交付 480p 就不生成 720p 的像素);
|
||
config / 其它 —— 不钳制,配置与档位不一致时由预检提示
|
||
(preflight: resolution_effective_lower),出片仍照配置。
|
||
"""
|
||
multiple = int(self.config.get("multiple") or 32)
|
||
# 兜底走部署级硬件预算(COMFYUI_MEGAPIXELS),而不是写死值:
|
||
# 配置缺键时静默回到大显存档,等于在小钢炮上悄悄点开 2.5 倍的耗时。
|
||
mp = float(self.config.get("megapixels") or settings.comfyui_megapixels) * 1_000_000
|
||
tier = _resolution_floor_mp(resolution)
|
||
policy = str(self.config.get("resolution_policy")
|
||
or settings.comfyui_resolution_policy).strip().lower()
|
||
if tier and policy == "tier": # 档位作下限(显式 opt-in)
|
||
mp = max(mp, tier)
|
||
elif tier and policy == "budget": # 档位作上限(显式 opt-in)
|
||
mp = min(mp, tier)
|
||
ratios = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0, "4:3": 4 / 3, "3:4": 3 / 4, "21:9": 21 / 9,
|
||
"5:4": 5 / 4, "4:5": 4 / 5}
|
||
ratio = ratios.get(str(aspect_ratio or "16:9"), 16 / 9)
|
||
if ratio >= 1: # 横屏:固定比例下解出面积 = mp 的宽高
|
||
h = (mp / ratio) ** 0.5
|
||
w = h * ratio
|
||
else: # 竖屏:以宽度为基准
|
||
w = (mp * ratio) ** 0.5
|
||
h = w / ratio
|
||
|
||
def snap(value: float) -> int:
|
||
n = max(multiple, int(round(value / multiple)) * multiple)
|
||
return n
|
||
|
||
w, h = snap(w), snap(h)
|
||
# 官方口径:H3 原生画布短边 768,上限 1344x768。超了整体**等比**收缩,
|
||
# 不能宽高各自减一个 multiple:那样会把 16:9 拉成 2.6:1 的扁画面(1080p 尤其明显)。
|
||
cap = int(self.config.get("max_edge") or 1344)
|
||
while max(w, h) > cap:
|
||
scale = cap / float(max(w, h))
|
||
w = max(multiple, int(round(w * scale / multiple)) * multiple)
|
||
h = max(multiple, int(round(h * scale / multiple)) * multiple)
|
||
return w, h
|
||
|
||
def grid(self) -> DurationGrid:
|
||
"""本模板的合法帧数网格(供平台贴台词时长用)。"""
|
||
return DurationGrid(fps=int(self.tpl.get("frame_fps") or 24),
|
||
step=int(self.tpl.get("frame_step") or 1),
|
||
offset=int(self.tpl.get("frame_offset") or 0),
|
||
min_frames=int(self.tpl.get("frame_min") or 5))
|
||
|
||
def length(self, seconds: float) -> int:
|
||
"""时长 → 帧数,并对齐到模型要求的 (step*k + offset) 网格。"""
|
||
return self.grid().frames_of(seconds)
|
||
|
||
# ---------- 节点图 ----------
|
||
@staticmethod
|
||
def fold_negative(prompt: str, negative: str, config: dict) -> str:
|
||
"""H3 没有独立的反向提示词输入:官方模板是把禁忌写成提示词末尾的自然语言子句。
|
||
|
||
平台仍然在镜头上维护 negative_prompt(换供应商时可复用),这里只做投递形态转换。
|
||
|
||
**联合音视频模型(H3)一条都不下发**:它没有 negative 通道,那句「画面中不要
|
||
出现:……」会被原样拼在 caption 末尾,而 H3 把整段文字同时当画面脚本和声音脚本
|
||
——它本身就是可被念出来的台词(项目 11 开头乱语的来源之一)。
|
||
"""
|
||
text = (prompt or "").strip()
|
||
negative = (negative or "").strip()
|
||
if not negative or not bool(config.get("negative_as_prompt", True)):
|
||
return text
|
||
cfg = config or {}
|
||
joint = bool((cfg.get("capabilities") or {}).get(
|
||
"joint_av", bool(_template_of(cfg).get("supports_audio"))))
|
||
if joint:
|
||
# 联合音视频模型**没有 negative 通道**,「画面中不要出现:文字水印……」
|
||
# 会被原样拼在 caption 末尾,成为一句可被念出来的话(实测:开头乱语之一)。
|
||
# 负向词仍留在镜头上,换供应商时才用得上。
|
||
return text
|
||
items = ",".join(x.strip() for x in negative.replace(",", ",").replace("、", ",").split(",")
|
||
if x.strip())
|
||
if not items:
|
||
return text
|
||
return f"{text}\n\n画面中不要出现:{items}。"
|
||
|
||
def build(self, *, prompt: str, negative: str, seed: int, width: int, height: int,
|
||
length: int, first_frame: str = "", last_frame: str = "",
|
||
refs: list[str] | None = None, audios: list[str] | None = None) -> tuple[dict, str]:
|
||
cfg = self.config
|
||
prompt = self.fold_negative(prompt, negative, cfg)
|
||
graph: dict[str, dict] = {}
|
||
loader_unet = str(cfg.get("unet_loader") or "UnetLoaderGGUF")
|
||
loader_clip = str(cfg.get("clip_loader") or "CLIPLoaderGGUF")
|
||
if str(loader_unet).lower().endswith("gguf"):
|
||
graph["1"] = {"class_type": loader_unet, "inputs": {"unet_name": self.models["unet"]},
|
||
"_meta": {"title": "加载扩散模型 (UNET)"}}
|
||
else:
|
||
graph["1"] = {"class_type": "UNETLoader",
|
||
"inputs": {"unet_name": self.models["unet"],
|
||
"weight_dtype": str(cfg.get("weight_dtype") or "default")},
|
||
"_meta": {"title": "加载扩散模型 (UNET)"}}
|
||
if str(loader_clip).lower().endswith("gguf"):
|
||
graph["2"] = {"class_type": loader_clip,
|
||
"inputs": {"clip_name": self.models["clip"], "type": self.models["clip_type"]},
|
||
"_meta": {"title": "加载文本编码器 (CLIP)"}}
|
||
else:
|
||
graph["2"] = {"class_type": "CLIPLoader",
|
||
"inputs": {"clip_name": self.models["clip"], "type": self.models["clip_type"],
|
||
"device": str(cfg.get("clip_device") or "default")},
|
||
"_meta": {"title": "加载文本编码器 (CLIP)"}}
|
||
graph["3"] = {"class_type": "VAELoader", "inputs": {"vae_name": self.models["video_vae"]},
|
||
"_meta": {"title": "视频 VAE"}}
|
||
graph["4"] = {"class_type": "VAELoader", "inputs": {"vae_name": self.models["audio_vae"]},
|
||
"_meta": {"title": "音频 VAE"}}
|
||
|
||
refs = refs or []
|
||
if refs and self.tpl.get("r2v_node"):
|
||
node: dict[str, Any] = {"clip": ["2", 0], "prompt": prompt, "width": width, "height": height,
|
||
"length": length, "ref_image_size": str(cfg.get("ref_image_size") or "match")}
|
||
if self.tpl.get("supports_audio"):
|
||
node["vae"] = ["3", 0]
|
||
node["audio_vae"] = ["4", 0]
|
||
# ComfyUI 3.x 的 autogrow 动态输入在 API prompt 中使用以父输入为前缀的
|
||
# 扁平键(ref_images.ref_image_0),不能传嵌套字典,也不能省略父前缀。
|
||
# 嵌套写法会被静默解析为空参考集,导致生成结果与参考图无关。
|
||
for idx, ref in enumerate(refs[: int(self.tpl.get("max_refs") or 6)]):
|
||
node_id = f"5{idx}"
|
||
node[f"ref_images.ref_image_{idx}"] = [node_id, 0]
|
||
graph[node_id] = {"class_type": "LoadImage", "inputs": {"image": ref},
|
||
"_meta": {"title": f"参考图 {idx + 1}"}}
|
||
# 音色参考:把角色声线的样本音频交给模型,让它「用这个人的嗓子说话」。
|
||
# 这是 H3 直出人声能落地的关键——原声口型天然同步,唯一的短板就是
|
||
# 音色由模型即兴;喂了 ref_audio 之后,音色改由项目里的声线资产决定。
|
||
# 同样必须走 autogrow 的扁平前缀键(ref_audios.ref_audio_0)。
|
||
for idx, audio in enumerate((audios or [])[: int(self.tpl.get("max_ref_audios") or 3)]):
|
||
node_id = f"6{idx}"
|
||
node[f"ref_audios.ref_audio_{idx}"] = [node_id, 0]
|
||
graph[node_id] = {"class_type": "LoadAudio", "inputs": {"audio": audio},
|
||
"_meta": {"title": f"参考音色 {idx + 1}"}}
|
||
graph["10"] = {"class_type": self.tpl["r2v_node"], "inputs": node,
|
||
"_meta": {"title": f"{self.tpl['r2v_node']} (参考图)"}}
|
||
else:
|
||
inputs: dict[str, Any] = {"clip": ["2", 0], "prompt": prompt, "width": width, "height": height,
|
||
"length": length}
|
||
if self.tpl.get("supports_audio"):
|
||
inputs["vae"] = ["3", 0]
|
||
if first_frame:
|
||
graph["50"] = {"class_type": "LoadImage", "inputs": {"image": first_frame}}
|
||
inputs["first_frame"] = ["50", 0]
|
||
if last_frame:
|
||
graph["51"] = {"class_type": "LoadImage", "inputs": {"image": last_frame}}
|
||
inputs["last_frame"] = ["51", 0]
|
||
graph["10"] = {"class_type": self.tpl["i2v_node"], "inputs": inputs,
|
||
"_meta": {"title": self.tpl["i2v_node"]}}
|
||
|
||
# 可选 LoRA(例如官方 minimax_h3_ref2v_turbo_4step:20 步压到 4 步)。
|
||
# 只挂在模型链上,避免误改条件分支。
|
||
# LoRA 必须跟着任务走:H3 的两个 turbo LoRA 分别对应 fl2v(首帧/首尾帧)与
|
||
# ref2v(参考图)两种条件形态,共用一个基座权重。用 ref2v LoRA 跑首帧镜头
|
||
# 不报错,但起步帧贴合度与细节都会掉,而且画面上很难归因。
|
||
is_ref_task = graph["10"]["class_type"] == self.tpl.get("r2v_node")
|
||
model_src = ["1", 0]
|
||
lora_name = str(cfg.get("lora_ref2v" if is_ref_task else "lora_i2v")
|
||
or cfg.get("lora") or "").strip()
|
||
if lora_name:
|
||
graph["90"] = {"class_type": "LoraLoaderModelOnly",
|
||
"inputs": {"model": ["1", 0], "lora_name": lora_name,
|
||
"strength_model": float(cfg.get("lora_strength") or 1.0)},
|
||
"_meta": {"title": "LoRA (模型 only)"}}
|
||
model_src = ["90", 0]
|
||
|
||
graph["20"] = {"class_type": "RandomNoise", "inputs": {"noise_seed": int(seed)}}
|
||
graph["21"] = {"class_type": "BasicGuider",
|
||
"inputs": {"model": model_src, "conditioning": ["10", 0]}}
|
||
graph["22"] = {"class_type": "KSamplerSelect",
|
||
"inputs": {"sampler_name": str(cfg.get("sampler") or "res_multistep")}}
|
||
graph["23"] = {"class_type": "BasicScheduler",
|
||
"inputs": {"model": model_src, "scheduler": str(cfg.get("scheduler") or "simple"),
|
||
"steps": int(cfg.get("steps") or 20),
|
||
"denoise": float(cfg.get("denoise") or 1.0)}}
|
||
graph["24"] = {"class_type": "SamplerCustomAdvanced",
|
||
"inputs": {"noise": ["20", 0], "guider": ["21", 0], "sampler": ["22", 0],
|
||
"sigmas": ["23", 0], "latent_image": ["10", 1]}}
|
||
graph["30"] = {"class_type": "VAEDecode", "inputs": {"samples": ["24", 0], "vae": ["3", 0]}}
|
||
if self.tpl.get("supports_audio"):
|
||
graph["31"] = {"class_type": "VAEDecodeAudio",
|
||
"inputs": {"samples": ["24", 0], "vae": ["4", 0]}}
|
||
graph["40"] = {"class_type": "CreateVideo",
|
||
"inputs": {"images": ["30", 0], "audio": ["31", 0], "fps": self.fps}}
|
||
source = ["40", 0]
|
||
else:
|
||
source = ["30", 0]
|
||
graph["41"] = {"class_type": "SaveVideo",
|
||
"inputs": {"video": source,
|
||
"filename_prefix": str(cfg.get("filename_prefix") or "nex/shot"),
|
||
"format": str(cfg.get("format") or "auto")},
|
||
"_meta": {"title": "保存视频"}}
|
||
return graph, "41"
|
||
|
||
|
||
class ComfyVideoProvider(VideoProviderAdapter):
|
||
"""通过 ComfyUI HTTP 接口驱动的本地大模型视频适配器。"""
|
||
|
||
_name = "comfyui"
|
||
_probe_cache: dict[str, tuple[float, bool, str]] = {}
|
||
_probe_lock = threading.Lock()
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return self._name
|
||
|
||
# ------------------------------------------------------------------ 配置
|
||
def _base(self, config: dict) -> str:
|
||
base = str(config.get("base_url") or config.get("url") or settings.comfyui_base_url or "").rstrip("/")
|
||
if not base:
|
||
raise FatalProviderError("ComfyUI 适配器缺少 base_url(模型注册表 config 或 COMFYUI_BASE_URL)",
|
||
code="provider_not_configured")
|
||
return base
|
||
|
||
def _template(self, config: dict) -> dict:
|
||
key = str(config.get("workflow") or "minimax_h3")
|
||
tpl = WORKFLOW_TEMPLATES.get(key)
|
||
if tpl is None:
|
||
raise FatalProviderError(f"未知的 ComfyUI 工作流模板:{key}。"
|
||
f"可选:{', '.join(WORKFLOW_TEMPLATES)}", code="unknown_workflow")
|
||
return tpl
|
||
|
||
@staticmethod
|
||
def _seconds(tpl: dict, frames: int) -> float:
|
||
"""训练区间换算成对用户友好的整数秒。
|
||
|
||
向下取整(floor)而不是精确值:124 帧 / 24fps = 5.167s,但 5.0s 经 length()
|
||
对齐后同样落在 124 帧,所以 5s 才是既合法又符合直觉的口径。
|
||
真正的约束由下面的不变量保证——窗口两端对齐出的帧数必须落在训练区间内。
|
||
"""
|
||
fps = float(tpl.get("frame_fps") or 24)
|
||
return float(int(frames / fps))
|
||
|
||
def _min_seconds(self, tpl: dict) -> float:
|
||
return self._seconds(tpl, int(tpl.get("frame_min_trained") or 124))
|
||
|
||
def _max_seconds(self, tpl: dict) -> float:
|
||
return self._seconds(tpl, int(tpl.get("frame_max_trained") or 362))
|
||
|
||
def capabilities(self, config: dict | None = None) -> Capabilities:
|
||
cfg = config or {}
|
||
tpl = WORKFLOW_TEMPLATES.get(str(cfg.get("workflow") or "minimax_h3"), WORKFLOW_TEMPLATES["minimax_h3"])
|
||
caps = cfg.get("capabilities") or {}
|
||
modes = list(caps.get("modes") or (["t2v", "i2v", "fl"] if tpl.get("i2v_node") else ["t2v"]))
|
||
return Capabilities(
|
||
modes=tuple(modes),
|
||
resolutions=tuple(caps.get("resolutions") or ("480p", "720p")),
|
||
aspect_ratios=tuple(caps.get("aspect_ratios") or ("16:9", "9:16", "1:1", "4:3", "3:4", "21:9")),
|
||
# H3 只训练了 124~362 帧(24fps 下 ≈5.17s~15s)。低于 124 帧的时长
|
||
# 会被 length() 对齐到 17k+5 网格上的非法值(如 3s→73 帧),出图质量不可控,
|
||
# 因此下限取真实可生成的最短时长,让预检在花钱之前就把镜头挡下来。
|
||
min_duration=float(caps.get("min_duration") or self._min_seconds(tpl)),
|
||
max_duration=float(caps.get("max_duration") or self._max_seconds(tpl)),
|
||
# 台词镜头的真实可用下限(比 min_duration 低)+ 合法帧数网格:
|
||
# services/prompt.py 靠这两个值把镜头时长贴到台词上,不留可被念出来的空档。
|
||
duration_grid=WorkflowBuilder(cfg, tpl).grid(),
|
||
joint_min_duration=float(caps.get("joint_min_duration")
|
||
or self._seconds(tpl, int(tpl.get("frame_min_joint") or 124))),
|
||
max_reference_images=int(caps.get("max_reference_images") or tpl.get("max_refs") or 0),
|
||
# H3 的 r2v 节点有 ref_audios(最多 3 路):把角色声线样本喂进去,
|
||
# 模型直出的原声就会「照着这个嗓子说话」,口型天然对齐。
|
||
max_reference_audios=int(caps.get("max_reference_audios") or tpl.get("max_ref_audios") or 0),
|
||
needs_public_media=False,
|
||
# 工作流里有 audio_vae + VAEDecodeAudio + CreateVideo ⇒ 一次成片出音轨 = 联合音视频模型
|
||
joint_av=bool(caps.get("joint_av", bool(tpl.get("supports_audio")))),
|
||
# 放大交付档位可被模型配置覆盖({"capabilities": {"upscale_to": [...]}}),
|
||
# 没声明时用模板里的机型口径;空列表 = 明确关闭放大交付。
|
||
upscale_to=tuple(caps["upscale_to"] if "upscale_to" in caps
|
||
else (tpl.get("upscale_to") or ())),
|
||
notes=str(caps.get("notes") or f"ComfyUI 本地模型(模板 {cfg.get('workflow') or 'minimax_h3'}),"
|
||
"关键帧由平台上传到 ComfyUI 的 input 目录"),
|
||
)
|
||
|
||
def effective_canvas(self, config: dict | None = None,
|
||
aspect_ratio: str = "16:9",
|
||
resolution: str | None = None) -> tuple[int, int] | None:
|
||
cfg = config or {}
|
||
tpl = WORKFLOW_TEMPLATES.get(str(cfg.get("workflow") or "minimax_h3"), WORKFLOW_TEMPLATES["minimax_h3"])
|
||
try:
|
||
return WorkflowBuilder(cfg, tpl).canvas(aspect_ratio, resolution)
|
||
except Exception: # noqa: BLE001 - 配置残缺时不参与预检
|
||
return None
|
||
|
||
def is_available(self, config: dict | None = None) -> bool:
|
||
"""探测 ComfyUI 是否可达(带 30s 缓存,供模型注册表页面高频调用)。"""
|
||
cfg = config or {}
|
||
try:
|
||
base = self._base(cfg)
|
||
except FatalProviderError:
|
||
return False
|
||
now = time.time()
|
||
with self._probe_lock:
|
||
hit = self._probe_cache.get(base)
|
||
if hit and now - hit[0] < 30:
|
||
return hit[1]
|
||
try:
|
||
with comfy_client(timeout=float(cfg.get("probe_timeout", 5)), config=cfg) as http:
|
||
r = http.get(f"{base}/system_stats")
|
||
ok = r.status_code < 400
|
||
info = ""
|
||
if ok:
|
||
try:
|
||
sysinfo = (r.json() or {}).get("system") or {}
|
||
info = f"ComfyUI {sysinfo.get('comfyui_version', '?')}"
|
||
except Exception:
|
||
info = "ComfyUI"
|
||
else:
|
||
info = f"HTTP {r.status_code}"
|
||
except Exception as exc: # 探测绝不允许把模型注册表页面打挂
|
||
ok, info = False, f"{type(exc).__name__}: {exc}"
|
||
with self._probe_lock:
|
||
self._probe_cache[base] = (now, ok, info)
|
||
return ok
|
||
|
||
def last_probe(self, base: str) -> tuple[bool, str]:
|
||
with self._probe_lock:
|
||
hit = self._probe_cache.get(base)
|
||
return (hit[1], hit[2]) if hit else (False, "")
|
||
|
||
def availability_reason(self, config: dict | None = None) -> str:
|
||
"""is_available() 为假时补一句人话:没配地址 ≠ 配了但连不上(复用 30s 探测缓存,不再打网络)。"""
|
||
cfg = dict(config or {})
|
||
try:
|
||
base = self._base(cfg)
|
||
except FatalProviderError as exc:
|
||
return exc.message or "缺少 ComfyUI 服务地址"
|
||
if self.is_available(cfg): # 30s 缓存,重复调用不打网络
|
||
return ""
|
||
ok, info = self.last_probe(base)
|
||
if ok:
|
||
return ""
|
||
return f"服务地址 {base} 已配置,但当前探测不通({info or '尚无探测记录'})——ComfyUI 没起或端口不对"
|
||
|
||
# ------------------------------------------------------------------ 素材
|
||
def _upload(self, client: httpx.Client, base: str, local_path: str, subfolder: str,
|
||
tag: str = "关键帧") -> str:
|
||
src = Path(local_path)
|
||
if not src.exists():
|
||
raise FatalProviderError(f"{tag}文件不存在,无法上传给 ComfyUI:{local_path}", code="missing_media")
|
||
# 用内容哈希命名:同一张关键帧重复生成(重试/重做)不会在 ComfyUI 里堆副本
|
||
digest = hashlib.md5(src.read_bytes()).hexdigest()[:12]
|
||
name = f"{src.stem[:48]}-{digest}{src.suffix.lower() or '.png'}"
|
||
mime = mimetypes.guess_type(name)[0] or "image/png"
|
||
payload = {"name": name, "type": "input", "overwrite": "true"}
|
||
if subfolder:
|
||
payload["subfolder"] = subfolder
|
||
with src.open("rb") as fh:
|
||
with network_guard(base, f"上传{tag}"):
|
||
resp = client.post(f"{base}/upload/image", data=payload,
|
||
files={"image": (name, fh, mime)})
|
||
_raise_for(resp, context=f"上传{tag}")
|
||
data = resp.json()
|
||
full = str(data.get("name") or name)
|
||
sub = str(data.get("subfolder") or subfolder or "")
|
||
return f"{sub}/{full}" if sub else full
|
||
|
||
# ------------------------------------------------------------------ 生成
|
||
def generate(self, request: VideoGenRequest, config: dict | None = None,
|
||
on_progress: Callable[[float, str], None] | None = None) -> VideoGenResult:
|
||
cfg = dict(config or {})
|
||
base = self._base(cfg)
|
||
# 开工前先探活:服务没起时几秒内给出人话结论,而不是先把镜头排进 GPU 锁、
|
||
# 上传完关键帧才在 /prompt 上撞墙(地址整个写错时甚至一路重试到 timeout,
|
||
# 任务在页面上永远「进行中」)。缓存判定为「不通」时会强制实探一次,
|
||
# 刚把 ComfyUI 重启回来的那几十秒不会被过期缓存误杀。
|
||
require_reachable(base, stage='视频生成开工前')
|
||
# H3 与同机 Qwen-Image / IndexTTS 共用一张 GPU,整个生成周期串行持有资源锁。
|
||
with gpu_slot(cfg, base):
|
||
return self._generate_locked(request, cfg, base, on_progress)
|
||
|
||
def _generate_locked(self, request: VideoGenRequest, cfg: dict, base: str,
|
||
on_progress: Callable[[float, str], None] | None = None) -> VideoGenResult:
|
||
tpl = self._template(cfg)
|
||
builder = WorkflowBuilder(cfg, tpl)
|
||
out = Path(request.output_path or Path(settings.media_root) / "comfyui" / "out.mp4")
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
# 1) 关键帧 / 首尾帧 / 参考图:ComfyUI 只能读自己目录里的文件,先上传
|
||
sub = str(cfg.get("input_subfolder") or "nex_animation")
|
||
timeout = float(cfg.get("timeout", settings.video_poll_timeout_seconds or 5400))
|
||
interval = float(cfg.get("poll_interval", settings.video_poll_interval_seconds or 5))
|
||
upload_media = bool(cfg.get("upload_media", True))
|
||
first = last = ""
|
||
refs: list[str] = []
|
||
with comfy_client(timeout=float(cfg.get("request_timeout", 120)), config=cfg) as client:
|
||
if upload_media:
|
||
if request.first_frame:
|
||
first = self._upload(client, base, request.first_frame, sub, "关键帧")
|
||
if request.last_frame:
|
||
last = self._upload(client, base, request.last_frame, sub, "尾帧")
|
||
else:
|
||
# 预上传模式:调用方给出的已经是 ComfyUI input 内文件名。
|
||
first = str(request.first_frame or "")
|
||
last = str(request.last_frame or "")
|
||
mode = str(cfg.get("reference_mode") or "auto")
|
||
if bool(cfg.get("use_reference_images", True)):
|
||
sources = reference_inputs(request, first, int(tpl.get("max_refs") or 6),
|
||
last=last, mode=mode)
|
||
for idx, ref in enumerate(sources):
|
||
if ref == first:
|
||
refs.append(first)
|
||
elif upload_media:
|
||
refs.append(self._upload(client, base, ref, sub, f"参考图{idx + 1}"))
|
||
else:
|
||
refs.append(ref)
|
||
|
||
# 3) 参考音色:角色声线的样本音频。上传失败只降级成「模型自己挑嗓子」,
|
||
# 不值得让整镜重跑,所以逐条 try 而不是让它冒泡成任务失败。
|
||
audios: list[str] = []
|
||
voice_skips: list[str] = []
|
||
for idx, src in enumerate(_dedupe_paths(request.reference_audios or [])
|
||
[: int(tpl.get("max_ref_audios") or 3)]):
|
||
if not upload_media:
|
||
audios.append(src)
|
||
continue
|
||
try:
|
||
audios.append(self._upload(client, base, src, sub, f"参考音色{idx + 1}"))
|
||
except Exception as exc: # noqa: BLE001 - 音色是加分项,不是前置条件
|
||
voice_skips.append(Path(src).name)
|
||
# 槽位号是「第几条上传成功的音频」决定的,而 caption 里的
|
||
# ``<Audio n>`` 按**原始顺序**写的:一条传上去、一条失败,
|
||
# 后面那条就会被塞进前一个槽位,联合音视频模型照着标签让
|
||
# 甲用乙的嗓子说话。所以多人音色要么整套齐全,要么整镜都不用。
|
||
audios.clear()
|
||
break
|
||
if voice_skips and on_progress:
|
||
on_progress(0.04, f"参考音色上传失败({ '、'.join(voice_skips) }),"
|
||
f"本镜台词改由模型自行决定音色")
|
||
|
||
width, height = builder.canvas(request.aspect_ratio, getattr(request, "resolution", None))
|
||
length = builder.length(request.duration_seconds)
|
||
seed = derive_video_seed(request)
|
||
graph, _save_node = builder.build(prompt=request.prompt or "",
|
||
negative=request.negative_prompt or "",
|
||
seed=seed, width=width, height=height, length=length,
|
||
first_frame=first, last_frame=last, refs=refs,
|
||
audios=audios)
|
||
# MiniMaxH3ImageToVideo 没有任何音频条件输入:镜头只有首帧、没带上参考图时
|
||
# 会走到这个分支,刚上传的音色会被静默丢掉,台词音色退回模型即兴。
|
||
if audios and on_progress and not any(
|
||
node.get("class_type") == "LoadAudio" for node in graph.values()):
|
||
on_progress(0.05, "本镜走的是「首帧生视频」分支,该节点不接受参考音频,"
|
||
"台词音色由模型即兴(补一张人物定妆图作参考图即可用 r2v 锁定音色)")
|
||
body: dict[str, Any] = {"prompt": graph, "client_id": _client_id(request)}
|
||
if request.idempotency_key:
|
||
body["number"] = 0
|
||
body["front"] = False
|
||
with network_guard(base, "提交工作流"):
|
||
resp = client.post(f"{base}/prompt", json=body)
|
||
_raise_for(resp, context="提交 ComfyUI 工作流")
|
||
try:
|
||
submitted = resp.json()
|
||
except json.JSONDecodeError as exc:
|
||
raise FatalProviderError(f"ComfyUI /prompt 返回的不是 JSON:{resp.text[:400]}",
|
||
code="bad_response") from exc
|
||
job_id = str(submitted.get("prompt_id") or "")
|
||
if not job_id:
|
||
raise FatalProviderError(f"ComfyUI 未返回 prompt_id:{_clip(submitted)}", code="missing_job_id")
|
||
if on_progress:
|
||
on_progress(0.05, f"已提交 ComfyUI 队列 {job_id[:8]}")
|
||
|
||
# 2) 轮询:排队 → 执行 → 产物落盘(本地大模型动辄十几分钟,必须带超时与中断检查)
|
||
# 断连不再一票否决:OutageTracker 按「连续失败次数 + 累计中断时长」双阈值
|
||
# 容忍 ComfyUI 重启与网络抖动(装载 35GB 权重重启要一两分钟,正是最该
|
||
# 保住产物的时刻);超过预算才判死,且远早于 timeout,不会再出现
|
||
# 「服务已经没了、任务还在页面上转圈四十分钟」。
|
||
deadline = time.time() + timeout
|
||
position_logged = -1
|
||
tracker = OutageTracker(cfg)
|
||
while True:
|
||
if time.time() > deadline:
|
||
raise ProviderError(f"ComfyUI 任务 {job_id} 等待超过 {timeout:.0f}s 仍未完成",
|
||
code="provider_timeout", retryable=True)
|
||
time.sleep(interval)
|
||
payload = tolerant_json(client, f"{base}/history/{job_id}", base, tracker,
|
||
stage="查询 ComfyUI 任务结果", on_progress=on_progress)
|
||
if payload is not None:
|
||
tracker.recovered(on_progress=on_progress)
|
||
entry = (payload or {}).get(job_id)
|
||
if entry:
|
||
break
|
||
position = self._queue_position(client, base, job_id)
|
||
if position < 0 and time.time() - deadline < -timeout + 60:
|
||
raise RetryableProviderError(f"ComfyUI 已经丢失任务 {job_id} 的记录", code="job_lost")
|
||
if position != position_logged and on_progress:
|
||
ahead = position if position > 0 else 0
|
||
position_logged = position
|
||
on_progress(0.06 + min(0.09, 0.005 * max(0, 8 - ahead)),
|
||
f"ComfyUI 队列中(前面还有 {ahead} 个任务)" if ahead > 0 else "ComfyUI 正在出图")
|
||
|
||
failure = _failure_message(entry)
|
||
if failure:
|
||
raise FatalProviderError(f"ComfyUI 出图失败:{failure}", code="comfyui_execution_failed")
|
||
item = _first_file(entry)
|
||
if item is None:
|
||
raise RetryableProviderError(f"ComfyUI 任务完成但没有产物文件:{_clip(entry.get('outputs'))}",
|
||
code="no_output_file")
|
||
|
||
# 3) 下载产物到平台媒体目录
|
||
qs = urlencode({"filename": item["filename"], "subfolder": item.get("subfolder", ""),
|
||
"type": item.get("type", "output")})
|
||
with network_guard(base, "下载产物"), client.stream("GET", f"{base}/view?{qs}") as r:
|
||
_raise_for(r, context="下载 ComfyUI 产物")
|
||
with out.open("wb") as fh:
|
||
for chunk in r.iter_bytes():
|
||
fh.write(chunk)
|
||
if not out.exists() or out.stat().st_size < 1024:
|
||
raise RetryableProviderError(f"下载的产物文件异常({item.get('filename')})",
|
||
code="downloaded_file_invalid")
|
||
if on_progress:
|
||
on_progress(0.7, "产物已下载")
|
||
|
||
duration = ff.duration_ms(out) / 1000 if ff.available() else 0.0
|
||
duration = duration or request.duration_seconds
|
||
return VideoGenResult(file_path=str(out), provider_job_id=job_id, duration_seconds=duration,
|
||
cost=float(cfg.get("price_per_call") or 0.0),
|
||
metadata={"provider": "comfyui", "base_url": base,
|
||
"workflow": str(cfg.get("workflow") or "minimax_h3"),
|
||
"comfy_output": f"{item.get('subfolder', '')}/{item['filename']}".strip("/"),
|
||
"canvas": f"{width}x{height}", "length_frames": length,
|
||
"seed": seed, "fps": builder.fps,
|
||
# 镜头参数留痕:景别/机位/运镜随请求下发,台账必须能回答
|
||
# 「这条片子是按哪一档运镜出的」,否则镜头改了、出片没变也没人发现。
|
||
"shot_size": str((request.params or {}).get("shot_size") or ""),
|
||
"camera_angle": str((request.params or {}).get("camera_angle") or ""),
|
||
"camera_movement": str((request.params or {}).get("camera_movement")
|
||
or "static"),
|
||
"camera_movement_via": "prompt",
|
||
"uploaded": {"first_frame": first, "last_frame": last,
|
||
"refs": refs, "reference_mode": mode,
|
||
"identity_refs": max(0, len(refs) - (1 if first in refs else 0)),
|
||
# 音色参考是否真的进了模型:r2v 之外的分支(i2v 首帧)
|
||
# 没有音频条件输入,这里为 0 就说明本镜音色仍是模型即兴
|
||
"ref_audios": len(audios),
|
||
"ref_audio_nodes": sum(
|
||
1 for node in graph.values()
|
||
if node.get("class_type") == "LoadAudio"),
|
||
"ref_audio_skipped": voice_skips}})
|
||
|
||
# ------------------------------------------------------------------ 诊断
|
||
def diagnose(self, config: dict | None = None) -> dict:
|
||
"""返回连通性与 ComfyUI 上实际可用的模型/素材文件名。
|
||
|
||
不同机型的模型文件名差别很大(int8 / gguf / fp8 …),页面能直接照着改 config,
|
||
而不是让用户去猜 unet_name 该填什么。
|
||
"""
|
||
cfg = dict(config or {})
|
||
try:
|
||
base = self._base(cfg)
|
||
except FatalProviderError as exc:
|
||
return {"base_url": "", "available": False, "message": exc.message}
|
||
info: dict[str, Any] = {"base_url": base, "available": False, "message": ""}
|
||
try:
|
||
with comfy_client(timeout=float(cfg.get("probe_timeout", 8)), config=cfg) as client:
|
||
stats = client.get(f"{base}/system_stats")
|
||
_raise_for(stats, context="读取 ComfyUI 状态")
|
||
payload = (stats.json() or {}).get("system") or {}
|
||
devices = (stats.json() or {}).get("devices") or []
|
||
info.update({
|
||
"available": True,
|
||
"version": str(payload.get("comfyui_version") or ""),
|
||
"message": f"ComfyUI {payload.get('comfyui_version', '?')}"
|
||
f"({payload.get('os', '?')})",
|
||
"devices": [{"name": d.get("name"), "vram_free_gb":
|
||
round(float(d.get("vram_free") or 0) / 1024 ** 3, 1)} for d in devices[:4]],
|
||
})
|
||
try:
|
||
objects = client.get(f"{base}/object_info", timeout=60.0).json()
|
||
except httpx.HTTPError:
|
||
objects = {}
|
||
info["nodes"] = {node: (node in objects) for node in
|
||
("MiniMaxH3ImageToVideo", "MiniMaxH3ReferenceToVideo", "EmptyMiniMaxH3LatentAV",
|
||
"VAEDecodeAudio", "CreateVideo", "SaveVideo", "UnetLoaderGGUF",
|
||
"CLIPLoaderGGUF", "UNETLoader", "CLIPLoader")}
|
||
info["files"] = _file_choices(objects)
|
||
try:
|
||
queue = client.get(f"{base}/queue", timeout=20.0).json()
|
||
info["queue"] = {"running": len(queue.get("queue_running") or []),
|
||
"pending": len(queue.get("queue_pending") or [])}
|
||
except httpx.HTTPError:
|
||
pass
|
||
except Exception as exc: # 诊断接口只报告,不抛异常
|
||
info["message"] = diagnosis_message(base, exc, stage="读取状态")
|
||
if is_network_error(exc):
|
||
info["reachable"] = False
|
||
return info
|
||
|
||
# ------------------------------------------------------------------ 排队位置
|
||
@staticmethod
|
||
def _queue_position(client: httpx.Client, base: str, job_id: str) -> int:
|
||
"""返回前面还有多少任务;-1 表示已不在队列(且结果尚未写入 history)。"""
|
||
try:
|
||
q = client.get(f"{base}/queue", timeout=20.0).json()
|
||
except Exception:
|
||
return 0
|
||
running = [i for i in (q.get("queue_running") or []) if str(i[1]) == job_id]
|
||
if running:
|
||
return 0
|
||
pending = q.get("queue_pending") or []
|
||
for idx, item in enumerate(pending):
|
||
if str(item[1]) == job_id:
|
||
return idx + 1
|
||
return -1
|
||
|
||
|
||
# ---------------------------------------------------------------------- 工具
|
||
def _file_choices(object_info: dict) -> dict:
|
||
"""从 object_info 里挑出各类加载器的候选文件名(供模型注册表页面直接选)。"""
|
||
def combo(node: str, field: str) -> list[str]:
|
||
node_info = (object_info or {}).get(node) or {}
|
||
for bucket in ("required", "optional"):
|
||
spec = (node_info.get("input") or {}).get(bucket, {}).get(field)
|
||
if spec and isinstance(spec[0], list):
|
||
return [str(x) for x in spec[0]]
|
||
return []
|
||
|
||
return {
|
||
"unet": combo("UNETLoader", "unet_name") + combo("UnetLoaderGGUF", "unet_name"),
|
||
"clip": combo("CLIPLoader", "clip_name") + combo("CLIPLoaderGGUF", "clip_name"),
|
||
"clip_types": combo("CLIPLoader", "type"),
|
||
"vae": [f for f in combo("VAELoader", "vae_name") if f != "pixel_space"],
|
||
"lora": combo("LoraLoaderModelOnly", "lora_name"),
|
||
"input_images": combo("LoadImage", "image"),
|
||
}
|
||
|
||
|
||
def _client_id(request: VideoGenRequest) -> str:
|
||
"""稳定的 client_id:ComfyUI 用它把 WebSocket 进度和任务关联起来。"""
|
||
seed = (request.idempotency_key or request.label or "nex")[:64]
|
||
return "nex-" + hashlib.md5(seed.encode()).hexdigest()[:16]
|
||
|
||
|
||
def derive_video_seed(request) -> int:
|
||
"""未指定 seed 时派生一个**稳定但随提示词变化**的种子。
|
||
|
||
只用幂等键派生有个致命后果:自动返工时提示词已经写进了上一轮的质检问题,
|
||
种子却没变——同一颗骰子重新摇一次,「两个人分身」「机位跳变」原样复现,
|
||
返工变成纯烧 GPU。改成把提示词摘要一起混进去:
|
||
同一个提示词永远可复现,改过提示词(含返工)就是新的一镜。
|
||
"""
|
||
if request.seed:
|
||
return int(request.seed)
|
||
key = str(request.idempotency_key or request.prompt or "nex")
|
||
prompt = str(request.prompt or "")
|
||
if request.idempotency_key and prompt:
|
||
key = f"{key}:{hashlib.md5(prompt.encode()).hexdigest()[:8]}"
|
||
return int(hashlib.md5(key.encode()).hexdigest()[:8], 16)
|
||
|
||
|
||
def _raise_for(resp: httpx.Response, *, context: str) -> None:
|
||
if resp.status_code < 400:
|
||
return
|
||
body = resp.text[:1200]
|
||
if resp.status_code == 429:
|
||
try:
|
||
retry_after: float | None = float(resp.headers.get("Retry-After", ""))
|
||
except (TypeError, ValueError):
|
||
retry_after = None
|
||
raise RateLimitedError(f"{context}被 ComfyUI 限流(HTTP 429):{body}", retry_after=retry_after)
|
||
if resp.status_code in (500, 502, 503, 504):
|
||
raise RetryableProviderError(f"{context}ComfyUI 暂时不可用(HTTP {resp.status_code}):{body}",
|
||
code=f"http_{resp.status_code}")
|
||
raise FatalProviderError(f"{context}被 ComfyUI 拒绝(HTTP {resp.status_code}):{body}",
|
||
code=f"http_{resp.status_code}")
|
||
|
||
|
||
def _failure_message(entry: dict) -> str:
|
||
status = entry.get("status") or {}
|
||
if not status:
|
||
return ""
|
||
if status.get("completed") is True and str(status.get("status_str", "success")) == "success":
|
||
return ""
|
||
if str(status.get("status_str", "success")) in ("success",) and status.get("completed") is not False:
|
||
return ""
|
||
messages = status.get("messages") or []
|
||
details: list[str] = []
|
||
for item in messages:
|
||
if isinstance(item, (list, tuple)) and len(item) > 1 and isinstance(item[1], dict):
|
||
payload = item[1]
|
||
if item[0] in ("execution_error", "execution_interrupted", "execution_cached_failed"):
|
||
details.append(str(payload.get("exception_message") or payload.get("node_id") or payload))
|
||
elif str(payload.get("status_str", "")) not in ("", "success"):
|
||
details.append(str(payload.get("status_str")))
|
||
elif isinstance(item, str):
|
||
details.append(item)
|
||
text = ";".join(d for d in details if d)
|
||
return text or str(status.get("status_str") or "")
|
||
|
||
|
||
def _first_file(entry: dict) -> dict | None:
|
||
for _node_id, output in (entry.get("outputs") or {}).items():
|
||
for key in ("videos", "gifs", "images"):
|
||
for item in output.get(key) or []:
|
||
name = str(item.get("filename") or "")
|
||
if not name:
|
||
continue
|
||
if key == "images" and not str(item.get("type", "")).lower():
|
||
continue
|
||
if name.lower().endswith((".mp4", ".webm", ".mkv", ".mov", ".gif")) or key in ("videos", "gifs"):
|
||
return item
|
||
return None
|
||
|
||
|
||
def _clip(value: Any, limit: int = 600) -> str:
|
||
try:
|
||
return json.dumps(value, ensure_ascii=False, default=str)[:limit]
|
||
except Exception:
|
||
return str(value)[:limit]
|