468 lines
22 KiB
Python
468 lines
22 KiB
Python
"""ComfyUI 多能力适配器共用逻辑:提交图、轮询、下载、GPU 串行锁与**断连收口**。
|
||
|
||
为什么网络处理要放在这里而不是各适配器里:H3 视频、Qwen 图像、IndexTTS 配音
|
||
打的是同一台机器上的同一个 ComfyUI(本机 9200),三边的失败模式完全一样,
|
||
以前却各写各的轮询——一次 ConnectError 就把跑了十几分钟的出图判死,
|
||
反过来地址写错时又能一路重试到 timeout,任务在页面上永远「进行中」。
|
||
现在统一成三层:
|
||
|
||
1. ``require_reachable``:开工前探活。连不上就在几秒内失败,不去排队、不占 GPU 锁;
|
||
2. ``network_guard``:上传/提交/下载阶段的异常翻译,绝不让裸 httpx 英文异常泄漏出去;
|
||
3. ``OutageTracker``:轮询期间的容错记账,按「连续失败次数 + 累计中断时长」双阈值,
|
||
短暂重启不丢产物,持续断连远早于 timeout 就判死。
|
||
|
||
三者最终都收敛到同一个错误码 ``provider_unreachable``,调度中心按可重试处理,
|
||
前端的任务卡片也能据此给出确定性的解释。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import mimetypes
|
||
import os
|
||
import threading
|
||
import time
|
||
from contextlib import ExitStack, contextmanager
|
||
from pathlib import Path
|
||
from typing import Any, Callable, Iterator
|
||
from urllib.parse import urlencode, urlparse
|
||
|
||
import httpx
|
||
|
||
from app.config import settings
|
||
from app.providers.base import FatalProviderError, ProviderError, RateLimitedError, RetryableProviderError
|
||
|
||
_LOCKS: dict[str, threading.RLock] = {}
|
||
_LOCKS_GUARD = threading.Lock()
|
||
|
||
|
||
def endpoint_key(base_url: str) -> str:
|
||
"""把 ComfyUI 接入点规范化成 ``host:port``,作为同卡互斥的默认锁键。"""
|
||
raw = str(base_url or "").strip()
|
||
parsed = urlparse(raw if "://" in raw else f"http://{raw}")
|
||
host = (parsed.hostname or "").lower()
|
||
if not host:
|
||
return raw.rstrip("/")
|
||
port = parsed.port or (443 if parsed.scheme.lower() == "https" else 80)
|
||
return f"{host}:{port}"
|
||
|
||
|
||
def resource_lock(key: str) -> threading.RLock:
|
||
with _LOCKS_GUARD:
|
||
return _LOCKS.setdefault(key, threading.RLock())
|
||
|
||
|
||
def lock_keys(config: dict | None, base_url: str) -> list[str]:
|
||
"""返回本次生成要持有的全部锁键(接入点锁 + 可选的分组锁)。
|
||
|
||
历史配置里 video 适配器常常漏填 ``resource_group``,于是它落在
|
||
``base_url`` 键上、而 TTS / 图像落在 ``comfyui:9200`` 键上,视频与图像
|
||
会在同一张卡上并发执行,把对方的权重挤出统一内存,下一段视频要先重新
|
||
装载 35GB 权重。这里同时取两把锁:地址相同的适配器一定互斥,
|
||
``resource_group`` 仍可用于把多个接入点归并成一组。
|
||
"""
|
||
keys = [endpoint_key(base_url)]
|
||
group = str((config or {}).get("resource_group") or "").strip().lower()
|
||
if group and group not in keys:
|
||
keys.append(group)
|
||
return keys
|
||
|
||
|
||
@contextmanager
|
||
def gpu_slot(config: dict, base_url: str) -> Iterator[None]:
|
||
# 锁键先排序再逐个获取,保证全局一致的加锁顺序,避免死锁。
|
||
locks = [resource_lock(key) for key in sorted(lock_keys(config, base_url))]
|
||
with ExitStack() as stack:
|
||
for lock in locks:
|
||
stack.enter_context(lock)
|
||
yield
|
||
|
||
|
||
def comfy_base(config: dict, default: str = "") -> str:
|
||
base = str(config.get("base_url") or config.get("url") or default or "").rstrip("/")
|
||
if not base:
|
||
raise FatalProviderError("ComfyUI 适配器缺少 base_url", code="provider_not_configured")
|
||
return base
|
||
|
||
|
||
# ---------------------------------------------------------------- 直连策略
|
||
# 后端进程常常是从配了系统代理的终端里起来的(macOS 上 Clash/Verge 会往 shell
|
||
# 里注入 HTTP_PROXY/HTTPS_PROXY)。ComfyUI 跑在局域网甚至本机端口上,这类流量
|
||
# 一旦继承环境代理就会被绕进本地代理:轻则多一跳延迟、上传 35GB 权重时吞吐被
|
||
# 限死,重则代理替你回答了这次请求——本机端口关掉时代理返回的是「HTTP 502 空
|
||
# body」,于是平台把「进程根本没起来」误判成「服务临时抖动」,一路重试到超时,
|
||
# 用户看到的还是指错方向的排查建议。所以 ComfyUI 相关流量默认 **直连**
|
||
# (``trust_env=False``),只有明确需要时才通过配置或环境变量打开系统代理。
|
||
|
||
|
||
def use_system_proxy(config: dict | None = None) -> bool:
|
||
"""是否让 ComfyUI 的请求继承环境代理(默认关闭)。"""
|
||
cfg = config or {}
|
||
if "use_system_proxy" in cfg:
|
||
return bool(cfg.get("use_system_proxy"))
|
||
return os.environ.get("NEX_COMFY_USE_PROXY", "").strip().lower() in {"1", "true", "yes", "on"}
|
||
|
||
|
||
def client(*, timeout: float = 60.0, config: dict | None = None, **kwargs: Any) -> httpx.Client:
|
||
"""ComfyUI 专用 httpx Client:默认直连,不受 shell 里的 HTTP_PROXY 影响。"""
|
||
kwargs.setdefault("follow_redirects", True)
|
||
return httpx.Client(timeout=timeout, trust_env=use_system_proxy(config), **kwargs)
|
||
|
||
|
||
# ---------------------------------------------------------------- 断连收口
|
||
# 裸 httpx 异常的英文原文(`[Errno 61] Connection refused`)既看不懂也判不准,
|
||
# 这里统一识别 + 翻译成中文,并保证「连不上」永远是 retryable:
|
||
# 服务恢复后调度中心会自动续跑,不需要人工去队列里点重试。
|
||
NETWORK_MARKERS = (
|
||
"connecterror", "connect timeout", "connection refused", "connection reset",
|
||
"connection aborted", "connectionfailed", "readtimeout", "read timeout",
|
||
"writetimeout", "pooltimeout", "pool timeout", "no route to host",
|
||
"network is unreachable", "unreachable host", "failed to establish a new connection",
|
||
"remoteprotocolerror", "sockconnecterror", "timed out", "eof occurred",
|
||
)
|
||
|
||
|
||
def is_network_error(exc: BaseException | None) -> bool:
|
||
"""判断异常是否属于「网络/服务不可达」,用于把裸 httpx 异常也归到同一类。"""
|
||
if exc is None:
|
||
return False
|
||
if isinstance(exc, (httpx.RequestError, OSError)):
|
||
return True
|
||
text = f"{type(exc).__name__} {exc}".lower()
|
||
return any(marker in text for marker in NETWORK_MARKERS)
|
||
|
||
|
||
def retryable_error(message: str, code: str, *, retry_after: float = 30.0) -> RetryableProviderError:
|
||
"""可重试错误 + 建议退避秒数。
|
||
|
||
``retry_after`` 只在 ``RateLimitedError`` 上是构造参数,基类不认,
|
||
而调度中心是按 ``getattr(exc, "retry_after")`` 读的——只能构造完再挂属性。
|
||
默认 30s:服务重启通常十几秒就好,按指数退避一路涨到 300s 反而让队列空转。
|
||
"""
|
||
error = RetryableProviderError(message, code=code)
|
||
error.retry_after = float(retry_after)
|
||
return error
|
||
|
||
|
||
def unreachable_error(base: str, exc: BaseException | None = None, *, stage: str = "",
|
||
note: str = "", retry_after: float = 30.0) -> RetryableProviderError:
|
||
"""统一的「连不上 ComfyUI」错误:点名地址、说清在哪一步、给出可照做的检查项。"""
|
||
detail = f"{type(exc).__name__}: {exc}"[:200] if exc is not None else ""
|
||
where = f"({stage})" if stage else ""
|
||
tail = ";".join(part for part in (detail, note) if part)
|
||
exc_out = retryable_error(
|
||
f"连不上 ComfyUI 服务 {base}{where}"
|
||
+ (f":{tail}" if tail else "")
|
||
+ f"。请检查 {endpoint_key(base)} 上的 ComfyUI 进程是否还在、端口有没有变、"
|
||
"本机到它的网络是否可达;恢复后任务会自动重试,也可以在「模型中心」点「探测」立即复测。",
|
||
code="provider_unreachable", retry_after=retry_after)
|
||
return exc_out
|
||
|
||
|
||
def diagnosis_message(base: str, exc: BaseException, *, stage: str = "探测") -> str:
|
||
"""「模型中心 → 探测」用的一句话结论:地址、错误、下一步查什么。
|
||
|
||
以前这里直接把 ``ConnectError: [Errno 61] Connection refused`` 甩到页面上,
|
||
既看不出是哪个地址,也不说明平台已经**直连** ComfyUI——用户会去翻系统代理,
|
||
而真正该看的是那台机器上的进程。
|
||
"""
|
||
if is_network_error(exc):
|
||
return (f"连不上 ComfyUI {base}({stage}):{type(exc).__name__}: {str(exc)[:160]}。"
|
||
"请确认该地址上的 ComfyUI 进程是否还在、端口有没有被改;"
|
||
"平台直连 ComfyUI,不走系统代理,所以不必检查代理设置。")
|
||
return f"{type(exc).__name__}: {exc}"[:400]
|
||
|
||
|
||
def outage_limits(config: dict | None = None) -> tuple[int, float]:
|
||
"""轮询容错预算:连续失败次数上限 + 最长容忍秒数,模型 config_json 可覆盖。"""
|
||
cfg = config or {}
|
||
errors = int(cfg.get("poll_error_budget") or settings.provider_outage_tolerance)
|
||
seconds = float(cfg.get("outage_seconds") or settings.provider_outage_seconds)
|
||
return max(1, errors), max(5.0, seconds)
|
||
|
||
|
||
class OutageTracker:
|
||
"""轮询期间的断连记账:次数与时长任一超预算即判死,成功一次立刻清零。
|
||
|
||
两个阈值缺一不可:只数次数,10s 间隔的轮询要连挂 6 次(1 分钟)才判死,
|
||
地址整个写错时白等;只看时长,秒级抖动的服务会连着被判死,
|
||
而 ComfyUI 装载 35GB 权重重启一次要一两分钟——那正是最该保住产物的时刻。
|
||
"""
|
||
|
||
def __init__(self, config: dict | None = None):
|
||
self.max_errors, self.max_seconds = outage_limits(config)
|
||
self.consecutive = 0
|
||
self.total = 0
|
||
self.since = 0.0
|
||
|
||
@property
|
||
def down_seconds(self) -> float:
|
||
return time.monotonic() - self.since if self.consecutive else 0.0
|
||
|
||
def record(self, base: str, exc: BaseException, *, stage: str = "",
|
||
on_progress: Callable[[float, str], None] | None = None) -> None:
|
||
now = time.monotonic()
|
||
if not self.consecutive:
|
||
self.since = now
|
||
self.consecutive += 1
|
||
self.total += 1
|
||
down = now - self.since
|
||
if self.consecutive >= self.max_errors or down >= self.max_seconds:
|
||
raise unreachable_error(
|
||
base, exc, stage=stage or "轮询结果",
|
||
note=f"已连续 {self.consecutive} 次请求失败、中断 {down:.0f}s"
|
||
f"(容忍上限 {self.max_errors} 次 / {self.max_seconds:.0f}s)")
|
||
if on_progress:
|
||
on_progress(-1.0, f"与 ComfyUI 的连接中断(第 {self.consecutive} 次,已 {down:.0f}s):"
|
||
f"{type(exc).__name__},正在重试,产物不会丢")
|
||
|
||
def recovered(self, *, on_progress: Callable[[float, str], None] | None = None) -> None:
|
||
if self.consecutive and on_progress:
|
||
on_progress(-1.0, f"与 ComfyUI 的连接已恢复(中断 {self.down_seconds:.0f}s)")
|
||
self.consecutive = 0
|
||
|
||
|
||
@contextmanager
|
||
def network_guard(base: str, stage: str = "") -> Iterator[None]:
|
||
"""把一段 ComfyUI 调用里的网络异常翻译成平台的中文可重试错误。
|
||
|
||
``ProviderError``(含 HTTP 状态码映射出来的 429/5xx)原样放行——
|
||
那是供应商明确给出的结论,不该被重新解释成「连不上」。
|
||
"""
|
||
try:
|
||
yield
|
||
except ProviderError:
|
||
raise
|
||
except httpx.TimeoutException as exc:
|
||
# 超时单独留 provider_timeout:服务活着但答不上来(被上一个任务占满、
|
||
# 正在装载权重),和「地址根本连不上」的排查方向完全不同。
|
||
raise retryable_error(
|
||
f"ComfyUI 服务 {base} 请求超时({stage or '请求'}:{type(exc).__name__})。"
|
||
"服务可能被上一个任务占满或正在装载权重;先确认它还在跑,稍后任务会自动重试。",
|
||
"provider_timeout", retry_after=30.0) from exc
|
||
except (httpx.RequestError, OSError) as exc:
|
||
raise unreachable_error(base, exc, stage=stage) from exc
|
||
|
||
|
||
# 探活结果缓存:稳态下每次生成不再多打一次 /system_stats。
|
||
# 阳性结果缓存 15s 省掉重复握手;**阴性只缓存 1s**——刚把 ComfyUI 重启回来的那
|
||
# 一刻必须立刻放行,否则「服务已经好了,任务还要等缓存过期」又是一次莫名的卡住。
|
||
_REACH_TTL = 15.0
|
||
_DOWN_TTL = 1.0
|
||
_reach: dict[str, tuple[float, bool, str]] = {}
|
||
_reach_lock = threading.Lock()
|
||
|
||
|
||
def probe_reachable(base: str, *, timeout: float = 5.0, force: bool = False) -> tuple[bool, str]:
|
||
"""最小探活:只回答「这台 ComfyUI 连不连得上」,不判断节点/权重是否齐全。
|
||
|
||
与适配器各自的 ``is_available()`` 的区别是刻意的——IndexTTS 的 is_available
|
||
还要求自定义节点存在,「可达但缺节点」必须在提交前报「缺少节点」而不是「连不上」,
|
||
否则用户会去查网络,而真正该查的是 ComfyUI 插件。
|
||
"""
|
||
now = time.monotonic()
|
||
with _reach_lock:
|
||
hit = _reach.get(base)
|
||
if hit and not force:
|
||
window = _REACH_TTL if hit[1] else _DOWN_TTL
|
||
if now - hit[0] < window:
|
||
return hit[1], hit[2]
|
||
try:
|
||
with client(timeout=timeout) as http: # 直连:代理不该替 ComfyUI 回答问题
|
||
resp = http.get(f"{base}/system_stats")
|
||
ok, info = resp.status_code < 400, ("" if resp.status_code < 400 else f"HTTP {resp.status_code}")
|
||
except Exception as exc: # noqa: BLE001 - 探活本身绝不允许抛
|
||
ok, info = False, f"{type(exc).__name__}: {exc}"[:200]
|
||
with _reach_lock:
|
||
_reach[base] = (time.monotonic(), ok, info)
|
||
return ok, info
|
||
|
||
|
||
def invalidate_reachability(base: str | None = None) -> None:
|
||
"""清掉探活缓存(模型中心「探测」按钮 / 配置变更)。"""
|
||
with _reach_lock:
|
||
if base is None:
|
||
_reach.clear()
|
||
else:
|
||
_reach.pop(base, None)
|
||
|
||
|
||
def require_reachable(base: str, *, stage: str = "开工前", timeout: float = 5.0) -> str:
|
||
"""开工前闸门:连不上就立刻抛 provider_unreachable,几秒内出结论。"""
|
||
ok, info = probe_reachable(base, timeout=timeout)
|
||
if not ok:
|
||
raise unreachable_error(base, None, stage=stage, note=info or "无探测记录")
|
||
return base
|
||
|
||
|
||
# 轮询期间可以当作「抖一下」吞掉的错误:都代表服务此刻不健康,而不代表
|
||
# 这个镜头的参数/素材有问题。缺了这一层,ComfyUI 重启瞬间返回的 502/504
|
||
# 照样会把十几分钟的出图判死,而用户看到的仍然是一句英文 HTTP 状态码。
|
||
POLL_TOLERATED_CODES = {"provider_unreachable", "provider_timeout", "rate_limited",
|
||
"http_500", "http_502", "http_503", "http_504"}
|
||
|
||
|
||
def tolerant_json(client: httpx.Client, url: str, base: str, tracker: OutageTracker, *,
|
||
stage: str = "轮询结果", timeout: float = 30.0,
|
||
on_progress: Callable[[float, str], None] | None = None) -> Any | None:
|
||
"""带断连记账的一次 GET:返回 JSON,本轮抖动则返回 None(下一轮再问)。
|
||
|
||
返回 None 而不是抛异常,是「ComfyUI 重启两分钟、产物不该丢」这条诉求的落点:
|
||
超过预算由 ``OutageTracker.record`` 统一判死,调用方无需关心重试计数。
|
||
"""
|
||
try:
|
||
with network_guard(base, stage):
|
||
resp = client.get(url, timeout=timeout)
|
||
raise_for(resp, context=stage)
|
||
return resp.json()
|
||
except ProviderError as exc:
|
||
if exc.code not in POLL_TOLERATED_CODES:
|
||
raise # 404/参数错误等明确结论照常上抛
|
||
tracker.record(base, exc, stage=stage, on_progress=on_progress)
|
||
return None
|
||
except ValueError as exc: # 反序列化失败:网关返回 HTML 之类,按抖动处理
|
||
tracker.record(base, exc, stage=stage, on_progress=on_progress)
|
||
return None
|
||
|
||
|
||
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(resp.headers.get("Retry-After", ""))
|
||
except (TypeError, ValueError):
|
||
retry_after = None
|
||
raise RateLimitedError(f"{context}被 ComfyUI 限流:{body}", retry_after=retry_after)
|
||
error = RetryableProviderError if resp.status_code >= 500 else FatalProviderError
|
||
raise error(f"{context}失败(HTTP {resp.status_code}):{body}", code=f"http_{resp.status_code}")
|
||
|
||
|
||
def upload_input(client: httpx.Client, base: str, local_path: str, subfolder: str,
|
||
tag: str, content_type: str = "") -> str:
|
||
src = Path(local_path)
|
||
if not src.exists():
|
||
raise FatalProviderError(f"{tag}文件不存在:{local_path}", code="missing_media")
|
||
digest = hashlib.md5(src.read_bytes()).hexdigest()[:12]
|
||
name = f"{src.stem[:48]}-{digest}{src.suffix.lower()}"
|
||
mime = content_type or mimetypes.guess_type(name)[0] or "application/octet-stream"
|
||
data = {"name": name, "type": "input", "overwrite": "true", "subfolder": subfolder}
|
||
with src.open("rb") as handle:
|
||
with network_guard(base, f"上传{tag}"):
|
||
resp = client.post(f"{base}/upload/image", data=data, files={"image": (name, handle, mime)})
|
||
raise_for(resp, context=f"上传{tag}")
|
||
payload = resp.json()
|
||
full = str(payload.get("name") or name)
|
||
sub = str(payload.get("subfolder") or subfolder or "")
|
||
return f"{sub}/{full}" if sub else full
|
||
|
||
|
||
def submit_graph(client: httpx.Client, base: str, graph: dict, client_id: str,
|
||
*, idempotency_key: str = "") -> str:
|
||
body: dict[str, Any] = {"prompt": graph, "client_id": client_id}
|
||
if idempotency_key:
|
||
body.update({"number": 0, "front": False})
|
||
with network_guard(base, "提交工作流"):
|
||
resp = client.post(f"{base}/prompt", json=body)
|
||
raise_for(resp, context="提交 ComfyUI 工作流")
|
||
try:
|
||
payload = resp.json()
|
||
except json.JSONDecodeError as exc:
|
||
raise FatalProviderError(f"ComfyUI /prompt 返回非 JSON:{resp.text[:400]}",
|
||
code="bad_response") from exc
|
||
prompt_id = str(payload.get("prompt_id") or "")
|
||
if not prompt_id:
|
||
raise FatalProviderError(f"ComfyUI 未返回 prompt_id:{payload}", code="missing_job_id")
|
||
return prompt_id
|
||
|
||
|
||
def wait_history(client: httpx.Client, base: str, prompt_id: str, config: dict, *,
|
||
on_progress: Callable[[float, str], None] | None = None) -> dict:
|
||
"""轮询任务历史直到出产物。断连按 ``OutageTracker`` 的预算容忍,不半途判死。"""
|
||
timeout = float(config.get("timeout") or 900)
|
||
interval = max(0.5, float(config.get("poll_interval") or 2))
|
||
deadline = time.monotonic() + timeout
|
||
started = time.monotonic()
|
||
tracker = OutageTracker(config)
|
||
while time.monotonic() < deadline:
|
||
time.sleep(interval)
|
||
payload = tolerant_json(client, f"{base}/history/{prompt_id}", base, tracker,
|
||
stage="查询 ComfyUI 结果", on_progress=on_progress)
|
||
if payload is None:
|
||
continue
|
||
tracker.recovered(on_progress=on_progress)
|
||
entry = (payload or {}).get(prompt_id)
|
||
if entry:
|
||
failure = failure_message(entry)
|
||
if failure:
|
||
raise FatalProviderError(f"ComfyUI 执行失败:{failure}", code="comfyui_execution_failed")
|
||
return entry
|
||
if not queue_contains(client, base, prompt_id) and time.monotonic() > started + 30:
|
||
raise RetryableProviderError(f"ComfyUI 已丢失任务 {prompt_id}", code="job_lost")
|
||
raise ProviderError(f"ComfyUI 任务 {prompt_id} 等待超过 {timeout:.0f}s",
|
||
code="provider_timeout", retryable=True)
|
||
|
||
|
||
def queue_contains(client: httpx.Client, base: str, prompt_id: str) -> bool:
|
||
# 查不到队列时一律回答「还在」:判任务丢失的代价(重烧一张卡)远高于多等一轮。
|
||
try:
|
||
payload = client.get(f"{base}/queue", timeout=15.0).json()
|
||
return any(str(item[1]) == prompt_id for item in
|
||
(payload.get("queue_running") or []) + (payload.get("queue_pending") or []))
|
||
except Exception:
|
||
return True
|
||
|
||
|
||
def failure_message(entry: dict) -> str:
|
||
status = entry.get("status") or {}
|
||
if not status:
|
||
return ""
|
||
status_text = str(status.get("status_str") or "success")
|
||
if status.get("completed") is True and status_text == "success":
|
||
return ""
|
||
details: list[str] = []
|
||
for item in status.get("messages") or []:
|
||
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))
|
||
return ";".join(details) or ("" if status_text == "success" else status_text)
|
||
|
||
|
||
def first_output(entry: dict, *, keys: tuple[str, ...], suffixes: tuple[str, ...]) -> dict | None:
|
||
for output in (entry.get("outputs") or {}).values():
|
||
for key in keys:
|
||
for item in output.get(key) or []:
|
||
filename = str(item.get("filename") or "")
|
||
if filename and filename.lower().endswith(suffixes):
|
||
return item
|
||
return None
|
||
|
||
|
||
def download_output(client: httpx.Client, base: str, item: dict, out: Path) -> None:
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
query = urlencode({"filename": item["filename"], "subfolder": item.get("subfolder", ""),
|
||
"type": item.get("type", "output")})
|
||
with network_guard(base, "下载产物"), client.stream("GET", f"{base}/view?{query}") as resp:
|
||
raise_for(resp, context="下载 ComfyUI 产物")
|
||
with out.open("wb") as handle:
|
||
for chunk in resp.iter_bytes():
|
||
handle.write(chunk)
|
||
if not out.exists() or out.stat().st_size < 128:
|
||
raise RetryableProviderError(f"ComfyUI 产物异常:{item.get('filename')}",
|
||
code="downloaded_file_invalid")
|
||
|
||
|
||
def stable_client_id(value: str) -> str:
|
||
return "nex-" + hashlib.md5(value.encode("utf-8")).hexdigest()[:16]
|
||
|
||
|
||
def object_candidates(objects: dict, node: str, field: str) -> list[str]:
|
||
spec = ((objects.get(node) or {}).get("input") or {})
|
||
for bucket in ("required", "optional"):
|
||
raw = (spec.get(bucket) or {}).get(field)
|
||
if raw and isinstance(raw[0], list):
|
||
return [str(item) for item in raw[0]]
|
||
return []
|