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:
+112
-32
@@ -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():
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Kling 4.0 request helpers.
|
||||
|
||||
The released K video node still owns the HTTP task lifecycle. This module
|
||||
keeps the Kling 4.0 capability matrix and request shape in one testable place
|
||||
so the node only has to upload media and call the existing poll/download
|
||||
pipeline.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
KlingV4GenerationMode = str
|
||||
|
||||
GENERATION_MODES = {
|
||||
"text": "文生视频",
|
||||
"keyframes": "关键帧",
|
||||
"omni": "全能参考",
|
||||
}
|
||||
|
||||
ENDPOINTS = {
|
||||
"text": ("/kling/v1/videos/text2video", "/kling/v1/videos/text2video/{task_id}"),
|
||||
"keyframes": ("/kling/v1/videos/image2video", "/kling/v1/videos/image2video/{task_id}"),
|
||||
"omni": ("/kling/v1/videos/omni-video", "/kling/v1/videos/omni-video/{task_id}"),
|
||||
}
|
||||
|
||||
_RESOLUTION_MODE = {"720p": "std", "1080p": "pro"}
|
||||
_ASPECT_RATIOS = {"智能", "16:9", "9:16", "1:1", "21:9"}
|
||||
|
||||
|
||||
def canonical_generation_mode(value: str) -> str:
|
||||
"""Return the wire value for a displayed Kling 4.0 generation mode."""
|
||||
|
||||
if value in GENERATION_MODES:
|
||||
return value
|
||||
for wire_value, display_value in GENERATION_MODES.items():
|
||||
if value == display_value:
|
||||
return wire_value
|
||||
raise ValueError(f"不支持的 Kling 4.0 生成模式:{value}")
|
||||
|
||||
|
||||
def build_kling_v4_body(
|
||||
*,
|
||||
generation_mode: str,
|
||||
prompt: str,
|
||||
negative_prompt: str = "",
|
||||
duration: int = 5,
|
||||
resolution: str = "720p",
|
||||
aspect_ratio: str = "智能",
|
||||
first_frame: str | None = None,
|
||||
middle_frames: list[str] | None = None,
|
||||
last_frame: str | None = None,
|
||||
reference_images: list[str] | None = None,
|
||||
reference_videos: list[str] | None = None,
|
||||
keep_original_sound: bool = False,
|
||||
) -> dict:
|
||||
"""Build a Kling 4.0 proxy request without credentials or media bytes.
|
||||
|
||||
The proxy accepts the legacy Kling envelope (`model_name`, `mode`, and
|
||||
`metadata`) and maps the metadata fields to the official Kling 4.0
|
||||
contents/settings representation. Keyframes and Omni references are
|
||||
mutually exclusive at the provider boundary.
|
||||
"""
|
||||
|
||||
mode = canonical_generation_mode(generation_mode)
|
||||
prompt = str(prompt or "").strip()
|
||||
if not prompt:
|
||||
raise ValueError("Kling 4.0 生成模式下提示词不能为空")
|
||||
if resolution not in _RESOLUTION_MODE:
|
||||
raise ValueError("Kling 4.0 仅支持 720p 或 1080p")
|
||||
try:
|
||||
duration = int(duration)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("Kling 4.0 时长必须是整数秒") from None
|
||||
if duration < 3 or duration > 30:
|
||||
raise ValueError("Kling 4.0 时长必须在 3~30 秒之间")
|
||||
if aspect_ratio not in _ASPECT_RATIOS:
|
||||
raise ValueError(f"Kling 4.0 不支持宽高比:{aspect_ratio}")
|
||||
|
||||
middle_frames = list(middle_frames or [])
|
||||
reference_images = list(reference_images or [])
|
||||
reference_videos = list(reference_videos or [])
|
||||
if len(middle_frames) > 8:
|
||||
raise ValueError("Kling 4.0 最多支持 8 张中间关键帧")
|
||||
if len(reference_images) > 10:
|
||||
raise ValueError("Kling 4.0 最多支持 10 张参考图")
|
||||
if len(reference_videos) > 5:
|
||||
raise ValueError("Kling 4.0 最多支持 5 段参考视频")
|
||||
|
||||
body = {
|
||||
"model_name": "kling-v4",
|
||||
"prompt": prompt,
|
||||
"duration": duration,
|
||||
"mode": _RESOLUTION_MODE[resolution],
|
||||
"watermark_info": {"enabled": False},
|
||||
}
|
||||
if negative_prompt and str(negative_prompt).strip():
|
||||
body["negative_prompt"] = str(negative_prompt).strip()
|
||||
|
||||
if mode == "text":
|
||||
if first_frame or middle_frames or last_frame or reference_images or reference_videos:
|
||||
raise ValueError("文生视频模式不能连接图片或视频素材")
|
||||
elif mode == "keyframes":
|
||||
if not first_frame:
|
||||
raise ValueError("关键帧模式必须提供首帧图片")
|
||||
if reference_images or reference_videos:
|
||||
raise ValueError("关键帧模式不能同时使用全能参考素材")
|
||||
if last_frame and not first_frame:
|
||||
raise ValueError("尾帧必须与首帧一起提供")
|
||||
if len([first_frame, *middle_frames, last_frame] if last_frame else [first_frame, *middle_frames]) > 10:
|
||||
raise ValueError("Kling 4.0 关键帧总数不能超过 10 张")
|
||||
metadata = {"first_frame": first_frame}
|
||||
if middle_frames:
|
||||
metadata["middle_frames"] = middle_frames
|
||||
if last_frame:
|
||||
metadata["last_frame"] = last_frame
|
||||
body["metadata"] = metadata
|
||||
else:
|
||||
if first_frame or middle_frames or last_frame:
|
||||
raise ValueError("全能参考模式不能同时使用关键帧")
|
||||
if not reference_images and not reference_videos:
|
||||
raise ValueError("全能参考模式至少需要一张参考图或一段参考视频")
|
||||
if len(reference_images) + len(reference_videos) > 15:
|
||||
raise ValueError("Kling 4.0 全能参考素材总数不能超过 15 个")
|
||||
metadata = {}
|
||||
if reference_images:
|
||||
metadata["refer_images"] = reference_images
|
||||
if reference_videos:
|
||||
metadata["videos"] = reference_videos
|
||||
if keep_original_sound:
|
||||
body["keep_original_sound"] = True
|
||||
body["metadata"] = metadata
|
||||
|
||||
# The first frame determines the output shape. For text/Omni requests,
|
||||
# "智能" is represented by the provider's adaptive ratio value.
|
||||
if mode != "keyframes":
|
||||
body["aspect_ratio"] = "adaptive" if aspect_ratio == "智能" else aspect_ratio
|
||||
return body
|
||||
|
||||
|
||||
def endpoint_for(generation_mode: str) -> tuple[str, str]:
|
||||
"""Return create/status paths for a canonical or displayed mode."""
|
||||
|
||||
return ENDPOINTS[canonical_generation_mode(generation_mode)]
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Thin Midjourney image client on O1Key's shared async generateImage stack."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any, Callable, List, Optional, Sequence
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from ..utils.config import get_api_key_or_raise, get_base_url_by_route
|
||||
from ..utils.http2_client import create_http_client
|
||||
from ..utils.image_utils import pil_to_tensor, tensor_to_pil
|
||||
from ..utils.mj_prompt import (
|
||||
MJ_CONTENT_REF_MAX,
|
||||
MJ_MODEL_ID,
|
||||
MJ_STYLE_REF_MAX,
|
||||
MJ_SW_DEFAULT,
|
||||
build_mj_prompt,
|
||||
)
|
||||
from ..utils.nano_banana_async import (
|
||||
parse_completed_async_image_task,
|
||||
poll_async_image_task,
|
||||
submit_async_image_task,
|
||||
upload_images_to_temp_urls,
|
||||
)
|
||||
|
||||
MJ_EXPECTED_IMAGE_COUNT = 4
|
||||
MJ_REFERENCE_MAX_BYTES = 7 * 1024 * 1024
|
||||
MJ_DEFAULT_TIMEOUT_SECONDS = 180
|
||||
MJ_NODE_LABEL = "o1key MJ图片生成"
|
||||
|
||||
|
||||
def build_mj_submit_body(
|
||||
*,
|
||||
prompt: str,
|
||||
image_urls: Optional[Sequence[str]] = None,
|
||||
model: str = MJ_MODEL_ID,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the paid Midjourney request body.
|
||||
|
||||
API only accepts at most one URL in ``images[]``. Extra content references
|
||||
must already be embedded in the prompt text.
|
||||
"""
|
||||
normalized_prompt = str(prompt or "").strip()
|
||||
if not normalized_prompt:
|
||||
raise ValueError("提示词不能为空")
|
||||
if model != MJ_MODEL_ID:
|
||||
raise ValueError(f"Midjourney 模型无效:{model}")
|
||||
|
||||
urls = [str(url or "").strip() for url in (image_urls or ())]
|
||||
urls = [url for url in urls if url]
|
||||
if len(urls) > 1:
|
||||
raise ValueError("Midjourney images[] 最多 1 张(多内容参考请写入 Prompt)")
|
||||
if any(not url.startswith("https://") for url in urls):
|
||||
raise ValueError("Midjourney 参考图必须使用临时素材 HTTPS URL")
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"prompt": normalized_prompt,
|
||||
}
|
||||
if urls:
|
||||
body["images"] = urls
|
||||
return body
|
||||
|
||||
|
||||
def validate_mj_reference_image(image: Image.Image, *, label: str = "参考图") -> None:
|
||||
"""Validate Midjourney reference limits before upload."""
|
||||
if image is None:
|
||||
raise ValueError(f"{label}为空")
|
||||
width, height = int(image.width), int(image.height)
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError(f"{label}尺寸无效:{width}×{height}")
|
||||
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format="PNG")
|
||||
size = len(buf.getvalue())
|
||||
if size > MJ_REFERENCE_MAX_BYTES:
|
||||
raise ValueError(
|
||||
f"{label}不能超过 7MB,当前为 {size / 1024 / 1024:.2f}MB"
|
||||
)
|
||||
|
||||
|
||||
class MjImageClient:
|
||||
"""Upload content/style refs, submit one MJ task, poll, decode images."""
|
||||
|
||||
def __init__(self, *, base_url: Optional[str] = None, api_key: Optional[str] = None):
|
||||
self.base_url = str(base_url or get_base_url_by_route()).rstrip("/")
|
||||
self.api_key = api_key or get_api_key_or_raise("O1KEY_API_KEY")
|
||||
|
||||
async def generate_async(
|
||||
self,
|
||||
*,
|
||||
session: Any,
|
||||
prompt: str,
|
||||
aspect_ratio: str = "1:1",
|
||||
quality: int = 2,
|
||||
hd: bool = False,
|
||||
image_weight: float = 1.0,
|
||||
raw: bool = False,
|
||||
stylize: int = 250,
|
||||
chaos: int = 0,
|
||||
seed: int = -1,
|
||||
weird: int = 0,
|
||||
tile: bool = False,
|
||||
exp: int = 0,
|
||||
draft: bool = False,
|
||||
no_text: str = "",
|
||||
style_weight: int = MJ_SW_DEFAULT,
|
||||
images: Optional[Sequence[Image.Image]] = None,
|
||||
style_images: Optional[Sequence[Image.Image]] = None,
|
||||
timeout_seconds: int = MJ_DEFAULT_TIMEOUT_SECONDS,
|
||||
check_interrupt: Optional[Callable[[], None]] = None,
|
||||
progress_callback: Optional[Callable[[float], None]] = None,
|
||||
log_downloads: bool = True,
|
||||
log_task_success: bool = True,
|
||||
) -> List[Image.Image]:
|
||||
content_images = list(images or ())
|
||||
style_refs = list(style_images or ())
|
||||
if len(content_images) > MJ_CONTENT_REF_MAX:
|
||||
raise ValueError(f"内容参考图最多 {MJ_CONTENT_REF_MAX} 张")
|
||||
if len(style_refs) > MJ_STYLE_REF_MAX:
|
||||
raise ValueError(f"风格参考图最多 {MJ_STYLE_REF_MAX} 张")
|
||||
for index, image in enumerate(content_images, start=1):
|
||||
validate_mj_reference_image(image, label=f"参考图{index}")
|
||||
for index, image in enumerate(style_refs, start=1):
|
||||
validate_mj_reference_image(image, label=f"风格参考图{index}")
|
||||
|
||||
started = time.time()
|
||||
timeout = max(30, int(timeout_seconds))
|
||||
|
||||
def _guard() -> None:
|
||||
if check_interrupt:
|
||||
check_interrupt()
|
||||
elapsed = time.time() - started
|
||||
if elapsed > timeout:
|
||||
raise TimeoutError(
|
||||
f"{MJ_NODE_LABEL} 超时({timeout}秒),请稍后重试或调大「超时秒数」"
|
||||
)
|
||||
|
||||
_guard()
|
||||
upload_batch = content_images + style_refs
|
||||
uploaded_urls = await upload_images_to_temp_urls(
|
||||
session=session,
|
||||
base_url=self.base_url,
|
||||
api_key=self.api_key,
|
||||
images=upload_batch,
|
||||
node_label=MJ_NODE_LABEL,
|
||||
check_interrupt=_guard,
|
||||
log_success=log_task_success,
|
||||
)
|
||||
content_urls = list(uploaded_urls[: len(content_images)])
|
||||
style_urls = list(uploaded_urls[len(content_images) :])
|
||||
|
||||
# API images[] accepts only 1 URL; remaining content refs go into prompt.
|
||||
images_field = content_urls[:1]
|
||||
prompt_content_urls = content_urls[1:]
|
||||
|
||||
assembled = build_mj_prompt(
|
||||
prompt,
|
||||
aspect_ratio=aspect_ratio,
|
||||
quality=quality,
|
||||
hd=hd,
|
||||
image_weight=image_weight,
|
||||
raw=raw,
|
||||
stylize=stylize,
|
||||
chaos=chaos,
|
||||
seed=seed,
|
||||
has_reference_image=bool(content_urls),
|
||||
content_ref_urls=prompt_content_urls,
|
||||
style_ref_urls=style_urls,
|
||||
style_weight=style_weight,
|
||||
weird=weird,
|
||||
tile=tile,
|
||||
exp=exp,
|
||||
draft=draft,
|
||||
no_text=no_text,
|
||||
)
|
||||
body = build_mj_submit_body(prompt=assembled, image_urls=images_field)
|
||||
|
||||
if log_task_success:
|
||||
if content_urls and style_urls:
|
||||
mode = "内容+风格参考"
|
||||
elif content_urls:
|
||||
mode = "图生图"
|
||||
elif style_urls:
|
||||
mode = "风格参考"
|
||||
else:
|
||||
mode = "文生图"
|
||||
print(
|
||||
f"[{MJ_NODE_LABEL}] {mode} | model={MJ_MODEL_ID} | "
|
||||
f"timeout={timeout}s | content_refs={len(content_urls)} | "
|
||||
f"style_refs={len(style_urls)} | prompt={assembled[:120]}"
|
||||
f"{'…' if len(assembled) > 120 else ''}"
|
||||
)
|
||||
|
||||
task_id = await submit_async_image_task(
|
||||
session,
|
||||
self.base_url,
|
||||
self.api_key,
|
||||
body,
|
||||
MJ_NODE_LABEL,
|
||||
log_body_enabled=False,
|
||||
log_success=log_task_success,
|
||||
)
|
||||
task_payload = await poll_async_image_task(
|
||||
session,
|
||||
self.base_url,
|
||||
self.api_key,
|
||||
task_id,
|
||||
MJ_NODE_LABEL,
|
||||
check_interrupt=_guard,
|
||||
log_body_enabled=False,
|
||||
progress_callback=progress_callback,
|
||||
log_success=log_task_success,
|
||||
)
|
||||
_guard()
|
||||
task_payload, parsed = await parse_completed_async_image_task(
|
||||
task_payload,
|
||||
session,
|
||||
self.base_url,
|
||||
self.api_key,
|
||||
task_id,
|
||||
MJ_NODE_LABEL,
|
||||
check_interrupt=_guard,
|
||||
result_url_callback=None,
|
||||
log_downloads=log_downloads,
|
||||
)
|
||||
if isinstance(parsed, tuple) and len(parsed) == 2:
|
||||
result_images = parsed[0]
|
||||
else:
|
||||
result_images = parsed
|
||||
|
||||
if draft:
|
||||
if len(result_images) < 1:
|
||||
raise RuntimeError(
|
||||
f"{MJ_NODE_LABEL} 草稿模式应至少返回 1 张图,"
|
||||
f"实际返回 {len(result_images)} 张(task_id={task_id})"
|
||||
)
|
||||
elif len(result_images) != MJ_EXPECTED_IMAGE_COUNT:
|
||||
raise RuntimeError(
|
||||
f"{MJ_NODE_LABEL} 应返回 {MJ_EXPECTED_IMAGE_COUNT} 张图,"
|
||||
f"实际返回 {len(result_images)} 张(task_id={task_id})"
|
||||
)
|
||||
|
||||
if log_task_success:
|
||||
print(
|
||||
f"[{MJ_NODE_LABEL}] 完成 | task_id={task_id} | "
|
||||
f"生成={len(result_images)} 张 | 耗时={time.time() - started:.1f}s"
|
||||
)
|
||||
return list(result_images)
|
||||
|
||||
def generate_sync(
|
||||
self,
|
||||
*,
|
||||
prompt: str,
|
||||
aspect_ratio: str = "1:1",
|
||||
quality: int = 2,
|
||||
hd: bool = False,
|
||||
image_weight: float = 1.0,
|
||||
raw: bool = False,
|
||||
stylize: int = 250,
|
||||
chaos: int = 0,
|
||||
seed: int = -1,
|
||||
weird: int = 0,
|
||||
tile: bool = False,
|
||||
exp: int = 0,
|
||||
draft: bool = False,
|
||||
no_text: str = "",
|
||||
style_weight: int = MJ_SW_DEFAULT,
|
||||
images: Optional[Sequence[Image.Image]] = None,
|
||||
style_images: Optional[Sequence[Image.Image]] = None,
|
||||
timeout_seconds: int = MJ_DEFAULT_TIMEOUT_SECONDS,
|
||||
check_interrupt: Optional[Callable[[], None]] = None,
|
||||
progress_callback: Optional[Callable[[float], None]] = None,
|
||||
) -> List[Image.Image]:
|
||||
timeout = max(30, int(timeout_seconds))
|
||||
|
||||
async def _run_async() -> List[Image.Image]:
|
||||
async with create_http_client(
|
||||
http2=True,
|
||||
max_connections=8,
|
||||
max_keepalive_connections=4,
|
||||
) as session:
|
||||
return await self.generate_async(
|
||||
session=session,
|
||||
prompt=prompt,
|
||||
aspect_ratio=aspect_ratio,
|
||||
quality=quality,
|
||||
hd=hd,
|
||||
image_weight=image_weight,
|
||||
raw=raw,
|
||||
stylize=stylize,
|
||||
chaos=chaos,
|
||||
seed=seed,
|
||||
weird=weird,
|
||||
tile=tile,
|
||||
exp=exp,
|
||||
draft=draft,
|
||||
no_text=no_text,
|
||||
style_weight=style_weight,
|
||||
images=images,
|
||||
style_images=style_images,
|
||||
timeout_seconds=timeout,
|
||||
check_interrupt=check_interrupt,
|
||||
progress_callback=progress_callback,
|
||||
)
|
||||
|
||||
def _run() -> List[Image.Image]:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
try:
|
||||
return loop.run_until_complete(_run_async())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
future = executor.submit(_run)
|
||||
try:
|
||||
return future.result(timeout=timeout + 60)
|
||||
except TimeoutError as exc:
|
||||
raise TimeoutError(
|
||||
f"{MJ_NODE_LABEL} 超时({timeout}秒),请稍后重试或调大「超时秒数」"
|
||||
) from exc
|
||||
|
||||
|
||||
def tensors_to_reference_images(
|
||||
image_tensor,
|
||||
*,
|
||||
max_count: int = MJ_CONTENT_REF_MAX,
|
||||
label: str = "参考图",
|
||||
) -> List[Image.Image]:
|
||||
"""Convert an optional Comfy IMAGE tensor into up to ``max_count`` PIL images."""
|
||||
if image_tensor is None:
|
||||
return []
|
||||
images = tensor_to_pil(image_tensor)
|
||||
if not images:
|
||||
return []
|
||||
if len(images) > max_count:
|
||||
raise ValueError(f"{label}最多 {max_count} 张(当前输入为 {len(images)} 张)")
|
||||
return list(images)
|
||||
|
||||
|
||||
def pil_images_to_output_tensor(images: Sequence[Image.Image]):
|
||||
return pil_to_tensor(list(images))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MJ_DEFAULT_TIMEOUT_SECONDS",
|
||||
"MJ_EXPECTED_IMAGE_COUNT",
|
||||
"MJ_NODE_LABEL",
|
||||
"MJ_REFERENCE_MAX_BYTES",
|
||||
"MjImageClient",
|
||||
"build_mj_submit_body",
|
||||
"pil_images_to_output_tensor",
|
||||
"tensors_to_reference_images",
|
||||
"validate_mj_reference_image",
|
||||
]
|
||||
Reference in New Issue
Block a user