Add MJ image node, GIF save, and Kling/image generator updates

Ship o1key MJ图片生成 with content/style refs and prompt flags, save-GIF with preview, Kling 4.0 helpers, plus GPT/unified image node polish and docs.
This commit is contained in:
Jony
2026-11-09 09:11:12 +08:00
parent ff1cf830fa
commit a181cc1768
40 changed files with 6711 additions and 675 deletions
+112 -32
View File
@@ -42,9 +42,14 @@ from ..utils.http2_client import (
from ..utils.o1key_image_catalog import (
GPT_IMAGE_BACKGROUND_OPTIONS,
GPT_IMAGE_MODEL_OPTIONS,
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
resolve_gpt_image_complexity,
resolve_gpt_image_frame_count,
resolve_gpt_image_frame_duration_ms,
resolve_gpt_image_output_format,
validate_gpt_image_vector_output,
UNIFIED_IMAGE_ROUTE_OPTIONS,
)
from ..utils.gpt_image_media import materialize_result_images
try:
from comfy.model_management import processing_interrupted, InterruptProcessingException
@@ -63,15 +68,21 @@ _ENDPOINT_ASYNC_TASK = "/async/v1/tasks/{task_id}"
# ── 主模型与模型线路映射(界面值 → API 模型名)──────────────────────────────
GPT_IMAGE_ROUTE_OPTIONS = UNIFIED_IMAGE_ROUTE_OPTIONS
GPT_IMAGE_MODEL_MATRIX = {
("gpt-image-2", "畅速"): "gpt-image-2-c-sp",
("gpt-image-2", "直连"): "gpt-image-2-c-sd",
("gpt-image-2", "专线"): "gpt-image-2",
("gpt-image-2.6-sunburst", "畅速"): "gpt-image-2.6-sunburst-sp",
("gpt-image-2.6-sunburst", "直连"): "gpt-image-2.6-sunburst-sd",
("gpt-image-2.6-sunburst", "专线"): "gpt-image-2.6-sunburst",
("gpt-image-2.6-flare", "畅速"): "gpt-image-2.6-flare-sp",
("gpt-image-2.6-flare", "直连"): "gpt-image-2.6-flare-sd",
("gpt-image-2.6-flare", "专线"): "gpt-image-2.6-flare",
("gpt-image-2.5-sunburst", "畅速"): "gpt-image-2.5-sunburst-sp",
("gpt-image-2.5-sunburst", "直连"): "gpt-image-2.5-sunburst-sd",
("gpt-image-2.5-sunburst", "专线"): "gpt-image-2.5-sunburst",
("gpt-image-2.5-flare", "畅速"): "gpt-image-2.5-flare-sp",
("gpt-image-2.5-flare", "直连"): "gpt-image-2.5-flare-sd",
("gpt-image-2.5-flare", "专线"): "gpt-image-2.5-flare",
("gpt-image-2", "畅速"): "gpt-image-2-c-sp",
("gpt-image-2", "直连"): "gpt-image-2-c-sd",
("gpt-image-2", "专线"): "gpt-image-2",
}
_MODEL_NAME_MAP = {
"畅速": "gpt-image-2-c-sp",
@@ -246,13 +257,15 @@ class GptImageClient:
session: aiohttp.ClientSession,
url: str,
label: str,
) -> tuple[Image.Image, int, float]:
"""Download and fully decode an image, retrying interrupted GET reads."""
requested_format: Optional[str] = None,
) -> tuple[list[Image.Image], int, float]:
"""Download and fully decode result bytes, retrying interrupted GET reads."""
download_started = time.perf_counter()
for attempt in range(_RESPONSE_READ_MAX_RETRIES + 1):
try:
async with session.get(url, allow_redirects=True) as resp:
image_bytes, diagnostics = await read_response_body_with_diagnostics(resp)
content_type = str(resp.headers.get("Content-Type") or "")
if resp.status != 200:
print(
f"[o1key GPT Image] 结果下载传输追踪"
@@ -263,10 +276,12 @@ class GptImageClient:
raise _RetryableResultHTTPError(message)
raise RuntimeError(message)
image = Image.open(BytesIO(image_bytes))
image.load()
_attach_original_image_info(image, image_bytes)
return image, len(image_bytes), time.perf_counter() - download_started
images = materialize_result_images(
image_bytes,
requested_format=requested_format,
content_type=content_type,
)
return images, len(image_bytes), time.perf_counter() - download_started
except (
aiohttp.ClientError,
asyncio.TimeoutError,
@@ -807,19 +822,26 @@ class GptImageClient:
raise RuntimeError(f"{label} base64 解码失败: {e}") from None
@staticmethod
def _decode_inline_result_image(b64: str, label: str) -> tuple[Image.Image, int]:
"""Strictly decode and fully load a completed task's inline image."""
def _decode_inline_result_image(
b64: str,
label: str,
requested_format: Optional[str] = None,
) -> tuple[list[Image.Image], int]:
"""Strictly decode and fully load a completed task's inline image/media."""
try:
if not isinstance(b64, str) or not b64:
raise ValueError("empty base64 payload")
image_bytes = base64.b64decode(b64, validate=True)
if not image_bytes:
raise ValueError("decoded image is empty")
image = Image.open(BytesIO(image_bytes))
image.load()
_attach_original_image_info(image, image_bytes)
return image, len(image_bytes)
except (binascii.Error, ValueError, OSError, UnidentifiedImageError) as exc:
images = materialize_result_images(
image_bytes,
requested_format=requested_format,
)
if not images:
raise ValueError("decoded image is empty")
return images, len(image_bytes)
except (binascii.Error, ValueError, OSError, UnidentifiedImageError, RuntimeError) as exc:
raise _IncompleteInlineImageError(f"{label}不完整或无法解码: {exc}") from None
async def _append_images_from_payload(
@@ -1064,21 +1086,37 @@ class GptImageClient:
background: str = "auto",
moderation: Optional[str] = None,
resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> dict:
if int(n) != 1:
raise ValueError("GPT Image 单次请求的 n 必须为 1;多图请使用外层并发")
output_format = str(output_format or "png").strip().lower()
background = str(background or "auto").strip().lower()
moderation = str(moderation).strip().lower() if moderation is not None else None
if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS:
raise ValueError("GPT Image 输出格式无效")
if background not in GPT_IMAGE_BACKGROUND_OPTIONS:
raise ValueError("GPT Image 背景参数无效")
if moderation not in {None, "low"}:
raise ValueError("GPT Image 内容审查强度无效")
if background == "transparent" and output_format == "jpeg":
raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式")
api_model = _MODEL_NAME_MAP.get(model, model)
base_model = next((base for base in GPT_IMAGE_MODEL_OPTIONS
if api_model in {base, base + "-sp", base + "-sd"}), api_model)
output_format = resolve_gpt_image_output_format(base_model, output_format)
if background == "transparent" and output_format not in {"png", "webp"}:
raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式")
has_images = bool(image_list)
has_mask = mask_tensor is not None
validate_gpt_image_vector_output(
base_model,
output_format,
has_images=has_images,
has_mask=has_mask,
)
frame_count_value = resolve_gpt_image_frame_count(output_format, frame_count)
frame_duration_value = resolve_gpt_image_frame_duration_ms(
output_format, frame_duration_ms
)
complexity_value = resolve_gpt_image_complexity(base_model, complexity)
assets: List[Dict[str, Any]] = []
image_keys: List[str] = []
mask_key = None
@@ -1133,6 +1171,12 @@ class GptImageClient:
body["mask"] = {
"image_url": self._png_bytes_to_data_url(asset_bytes[mask_key])
}
if complexity_value is not None:
body["complexity"] = complexity_value
if frame_count_value is not None:
body["frame_count"] = frame_count_value
if frame_duration_value is not None:
body["frame_duration_ms"] = frame_duration_value
if moderation == "low":
body["moderation"] = "low"
return body
@@ -1273,6 +1317,7 @@ class GptImageClient:
result_url_callback: Optional[Callable[[str], None]] = None,
log_downloads: bool = True,
log_prefix: str = "[o1key GPT Image]",
requested_format: Optional[str] = None,
) -> List[Image.Image]:
data = task.get("data", {})
image_items = data.get("images") if isinstance(data, dict) else None
@@ -1297,42 +1342,47 @@ class GptImageClient:
f"第 {idx} 张内联 data URL 缺少有效 Base64 头"
)
started = time.perf_counter()
img, byte_count = self._decode_inline_result_image(
decoded, byte_count = self._decode_inline_result_image(
b64_data,
f"第 {idx} 张内联 data URL 图片",
requested_format=requested_format,
)
images.append(img)
images.extend(decoded)
if log_downloads:
first = decoded[0]
print(
f"{log_prefix} 结果图像 {idx}/{len(image_items)} 内联 data URL,无网络下载 | "
f"{img.size[0]}×{img.size[1]} | {self._format_transfer_size(byte_count)} | "
f"{first.size[0]}×{first.size[1]}×{len(decoded)} | {self._format_transfer_size(byte_count)} | "
f"解码={time.perf_counter() - started:.2f}s"
)
elif url and isinstance(url, str) and url.startswith("http"):
if log_downloads:
print(f"{log_prefix} 下载图像 {idx}/{len(image_items)} 开始")
img, byte_count, elapsed = await self._download_image_with_response_retry(
session, url, f"第 {idx} 张图片"
downloaded, byte_count, elapsed = await self._download_image_with_response_retry(
session, url, f"第 {idx} 张图片", requested_format=requested_format,
)
images.append(img)
images.extend(downloaded)
result_urls.append(url)
if log_downloads:
first = downloaded[0]
print(
f"{log_prefix} 下载图像 {idx}/{len(image_items)} 完成 | "
f"{img.size[0]}×{img.size[1]} | {self._format_transfer_size(byte_count)} | "
f"{first.size[0]}×{first.size[1]}×{len(downloaded)} | {self._format_transfer_size(byte_count)} | "
f"{elapsed:.2f}s | {self._format_transfer_rate(byte_count, elapsed)}"
)
elif b64:
started = time.perf_counter()
img, byte_count = self._decode_inline_result_image(
decoded, byte_count = self._decode_inline_result_image(
b64,
f"第 {idx} 张内联 Base64 图片",
requested_format=requested_format,
)
images.append(img)
images.extend(decoded)
if log_downloads:
first = decoded[0]
print(
f"{log_prefix} 结果图像 {idx}/{len(image_items)} 内联 base64,无网络下载 | "
f"{img.size[0]}×{img.size[1]} | {self._format_transfer_size(byte_count)} | "
f"{first.size[0]}×{first.size[1]}×{len(decoded)} | {self._format_transfer_size(byte_count)} | "
f"解码={time.perf_counter() - started:.2f}s"
)
else:
@@ -1366,6 +1416,7 @@ class GptImageClient:
result_url_callback: Optional[Callable[[str], None]] = None,
log_downloads: bool = True,
log_prefix: str = "[o1key GPT Image]",
requested_format: Optional[str] = None,
) -> tuple[dict, List[Image.Image]]:
"""Re-fetch a completed task when its inline image is incomplete."""
current_task = task
@@ -1377,6 +1428,7 @@ class GptImageClient:
result_url_callback=result_url_callback,
log_downloads=log_downloads,
log_prefix=log_prefix,
requested_format=requested_format,
)
return current_task, images
except _IncompleteInlineImageError as exc:
@@ -1422,6 +1474,9 @@ class GptImageClient:
log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]:
body = self._build_async_generate_body(
prompt=prompt,
@@ -1435,6 +1490,9 @@ class GptImageClient:
background=background,
moderation=moderation,
resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
)
mode = "图像编辑" if mask_tensor is not None else ("图生图" if image_tensor else "文生图")
@@ -1470,6 +1528,7 @@ class GptImageClient:
result_url_callback=_on_result_url,
log_downloads=log_downloads,
log_prefix=log_prefix,
requested_format=output_format,
)
if task_completed_callback:
task_completed_callback(task_id, len(images), time.time() - task_started, upstream_urls)
@@ -1496,6 +1555,9 @@ class GptImageClient:
log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]:
"""多图生成:并发提交 n 个单图任务,每个请求固定传 n=1。"""
request_count = max(1, int(n))
@@ -1540,6 +1602,9 @@ class GptImageClient:
log_request_start=log_request_start,
task_completed_callback=task_completed_callback,
resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
)
)
for task_index in range(request_count)
@@ -1870,6 +1935,9 @@ class GptImageClient:
log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]:
"""异步公共入口;多图始终拆成并发的 n=1 单图请求。"""
requested_n = max(1, int(n))
@@ -1894,6 +1962,9 @@ class GptImageClient:
log_request_start=log_request_start,
task_completed_callback=task_completed_callback,
resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
)
return await self._generate_image_task_async(
prompt=prompt,
@@ -1915,6 +1986,9 @@ class GptImageClient:
log_request_start=log_request_start,
task_completed_callback=task_completed_callback,
resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
)
def generate_image_async_sync(
@@ -1939,6 +2013,9 @@ class GptImageClient:
log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]:
"""
新版异步任务入口,供节点调用。
@@ -1965,6 +2042,9 @@ class GptImageClient:
log_request_start=log_request_start,
task_completed_callback=task_completed_callback,
resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
)
def _run():