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:
+217
-1
@@ -25,6 +25,10 @@ import aiohttp
|
||||
|
||||
from comfy_api.latest import io
|
||||
|
||||
from ..clients.kling_video_client import (
|
||||
build_kling_v4_body,
|
||||
endpoint_for as kling_v4_endpoint_for,
|
||||
)
|
||||
from ..utils.config import get_api_key_or_raise, get_base_url_by_route
|
||||
from ..utils.image_utils import tensor_to_pil
|
||||
from ..utils.r2_uploader import upload_image
|
||||
@@ -104,6 +108,11 @@ _REFERENCE_VIDEO_MIN_FPS = 24.0
|
||||
_REFERENCE_VIDEO_MAX_FPS = 60.0
|
||||
_REFERENCE_VIDEO_MIN_RATIO = 1 / 2.5
|
||||
_REFERENCE_VIDEO_MAX_RATIO = 2.5
|
||||
_V4_REFERENCE_VIDEO_MAX_BYTES = 300 * 1024 * 1024
|
||||
_V4_REFERENCE_VIDEO_MIN_DURATION = 3.0
|
||||
_V4_REFERENCE_VIDEO_MAX_DURATION = 30.0
|
||||
_V4_REFERENCE_VIDEO_MIN_RATIO = 2 / 5
|
||||
_V4_REFERENCE_VIDEO_MAX_RATIO = 5 / 2
|
||||
|
||||
|
||||
# ── 工具函数 ───────────────────────────────────────────────────────────────────
|
||||
@@ -428,6 +437,30 @@ def _validate_reference_video(video_path: str, model: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _validate_kling_v4_reference_video(video_path: str) -> float:
|
||||
"""Validate one Kling 4.0 Omni reference clip and return its duration."""
|
||||
ext = os.path.splitext(video_path)[1].lower()
|
||||
if ext not in (".mp4", ".mov"):
|
||||
raise RuntimeError(f"Kling 4.0 参考视频仅支持 MP4/MOV,当前为 {ext or '无扩展名'}。")
|
||||
size = os.path.getsize(video_path)
|
||||
if size > _V4_REFERENCE_VIDEO_MAX_BYTES:
|
||||
raise RuntimeError(
|
||||
f"Kling 4.0 参考视频不能超过 300MB,当前为 {size / 1024 / 1024:.1f}MB。"
|
||||
)
|
||||
meta = _probe_video_with_ffprobe(video_path) or _probe_video_with_cv2(video_path)
|
||||
if not meta or not meta.get("width") or not meta.get("height") or not meta.get("duration"):
|
||||
raise RuntimeError("无法读取 Kling 4.0 参考视频的尺寸和时长。")
|
||||
duration = float(meta["duration"])
|
||||
if not _V4_REFERENCE_VIDEO_MIN_DURATION <= duration <= _V4_REFERENCE_VIDEO_MAX_DURATION:
|
||||
raise RuntimeError(
|
||||
f"Kling 4.0 单段参考视频时长需在 3~30 秒之间,当前为 {duration:.2f} 秒。"
|
||||
)
|
||||
ratio = float(meta["width"]) / float(meta["height"])
|
||||
if not _V4_REFERENCE_VIDEO_MIN_RATIO <= ratio <= _V4_REFERENCE_VIDEO_MAX_RATIO:
|
||||
raise RuntimeError("Kling 4.0 参考视频宽高比需在 2:5~5:2 之间。")
|
||||
return duration
|
||||
|
||||
|
||||
def _collect_shots(分镜模式: dict, 时长: int) -> list:
|
||||
"""从 DynamicCombo 的 dict 收集分镜参数并校验。
|
||||
|
||||
@@ -605,6 +638,38 @@ def _v3_omni_subs():
|
||||
]
|
||||
|
||||
|
||||
def _v4_subs():
|
||||
"""Kling 4.0 generation mode and its capability-limited parameters."""
|
||||
return [
|
||||
io.Combo.Input(
|
||||
"生成模式",
|
||||
options=["文生视频", "关键帧", "全能参考"],
|
||||
default="文生视频",
|
||||
tooltip="文生视频:只使用提示词;关键帧:首帧可加中间帧和尾帧;全能参考:使用参考图或参考视频。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"时长",
|
||||
default=5,
|
||||
min=3,
|
||||
max=30,
|
||||
display_mode=io.NumberDisplay.slider,
|
||||
tooltip="Kling 4.0 支持 3~30 秒。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"模式",
|
||||
options=["720p", "1080p"],
|
||||
default="720p",
|
||||
tooltip="Kling 4.0 支持 720p 和 1080p。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"宽高比",
|
||||
options=["智能", "16:9", "9:16", "1:1", "21:9"],
|
||||
default="智能",
|
||||
tooltip="关键帧模式跟随首帧比例;文生和全能参考支持智能、16:9、9:16、1:1、21:9。",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _build_model_input():
|
||||
"""构建「模型」DynamicCombo,把「时长」「模式」作为随模型变化的子输入。
|
||||
|
||||
@@ -637,8 +702,11 @@ def _build_model_input():
|
||||
io.DynamicCombo.Option("v3-omni", _v3_omni_subs()),
|
||||
io.DynamicCombo.Option("v2-6", _v26_subs()),
|
||||
io.DynamicCombo.Option("v3", _v3_subs()),
|
||||
# Append the new branch so existing DynamicCombo option order and
|
||||
# saved v3/v2.6 workflows remain unchanged.
|
||||
io.DynamicCombo.Option("v4", _v4_subs()),
|
||||
],
|
||||
tooltip="v2-6: 5/10s; v3: 3-15s; v3-omni: 多模态参考、视频编辑、主体管理",
|
||||
tooltip="v2-6: 5/10s; v3: 3-15s; v3-omni: 多模态参考、视频编辑、主体管理;v4: 文生、关键帧、全能参考,3-30s。",
|
||||
)
|
||||
|
||||
|
||||
@@ -706,6 +774,28 @@ class K3Video(io.ComfyNode):
|
||||
tooltip="seed 仅控制节点是否重新运行,结果本身不可复现。"),
|
||||
# 负向提示词置于最下方(全局生效,两种模式都可用)
|
||||
io.String.Input("负向提示词", multiline=True, default=""),
|
||||
# Kling 4.0 sockets are appended after the released layout so
|
||||
# positional widgets in existing K3Video workflows do not move.
|
||||
*[
|
||||
io.Image.Input(f"中间帧{i}", optional=True,
|
||||
tooltip="Kling 4.0 关键帧模式使用;按连接顺序插入首帧与尾帧之间。")
|
||||
for i in range(1, 9)
|
||||
],
|
||||
*[
|
||||
io.Image.Input(f"参考图{i}", optional=True,
|
||||
tooltip="Kling 4.0 全能参考模式使用;最多 10 张参考图。")
|
||||
for i in range(6, 11)
|
||||
],
|
||||
io.Image.Input(
|
||||
"参考图1",
|
||||
optional=True,
|
||||
tooltip="Kling 4.0 全能参考模式使用;最多 10 张参考图。",
|
||||
),
|
||||
*[
|
||||
io.Video.Input(f"参考视频{i}", optional=True,
|
||||
tooltip="Kling 4.0 全能参考模式使用;最多 5 段参考视频。")
|
||||
for i in range(2, 6)
|
||||
],
|
||||
],
|
||||
outputs=[io.Video.Output(display_name="视频")],
|
||||
accept_all_inputs=True,
|
||||
@@ -730,6 +820,49 @@ class K3Video(io.ComfyNode):
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
shots = _collect_shots(分镜模式, 时长)
|
||||
if 模型代号 == "v4":
|
||||
generation_mode = 模型.get("生成模式", "文生视频")
|
||||
middle_frames = [
|
||||
_kwargs.get(f"中间帧{i}")
|
||||
for i in range(1, 9)
|
||||
if _kwargs.get(f"中间帧{i}") is not None
|
||||
]
|
||||
reference_images = [
|
||||
image for image in (
|
||||
_kwargs.get("参考图1"),
|
||||
参考图2, 参考图3, 参考图4, 参考图5,
|
||||
*[_kwargs.get(f"参考图{i}") for i in range(6, 11)],
|
||||
) if image is not None
|
||||
]
|
||||
reference_videos = [
|
||||
video for video in (
|
||||
参考视频,
|
||||
*[_kwargs.get(f"参考视频{i}") for i in range(2, 6)],
|
||||
) if video is not None
|
||||
]
|
||||
v4_prompt = (
|
||||
(分镜模式.get("正向提示词") or "")
|
||||
if not shots else shots[0]["prompt"]
|
||||
)
|
||||
save_path = await cls._build_v4(
|
||||
base_url,
|
||||
headers,
|
||||
generation_mode,
|
||||
v4_prompt,
|
||||
负向提示词,
|
||||
时长,
|
||||
模式,
|
||||
宽高比,
|
||||
起始帧,
|
||||
middle_frames,
|
||||
尾帧,
|
||||
reference_images,
|
||||
reference_videos,
|
||||
shots,
|
||||
)
|
||||
if _FOLDER_PATHS_OK:
|
||||
return io.NodeOutput(InputImpl.VideoFromFile(save_path))
|
||||
return io.NodeOutput(save_path)
|
||||
# 正向提示词仅在「禁用」(单段)时存在;选故事板后腾讯忽略主 Prompt,故隐藏。
|
||||
提示词 = (分镜模式.get("正向提示词") or "") if not shots else ""
|
||||
|
||||
@@ -1028,6 +1161,89 @@ class K3Video(io.ComfyNode):
|
||||
)
|
||||
|
||||
# ── 标准 image2video 端点(v3 / v2-6)────────────────────────
|
||||
@classmethod
|
||||
async def _build_v4(
|
||||
cls,
|
||||
base_url,
|
||||
headers,
|
||||
generation_mode,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
duration,
|
||||
resolution,
|
||||
aspect_ratio,
|
||||
first_frame,
|
||||
middle_frame_inputs,
|
||||
last_frame,
|
||||
reference_image_inputs,
|
||||
reference_video_inputs,
|
||||
shots,
|
||||
):
|
||||
"""Build and run one Kling 4.0 text/keyframe/Omni task."""
|
||||
from ..utils.r2_uploader import upload_video
|
||||
|
||||
async def upload_frame(image, label):
|
||||
if image is None:
|
||||
return None
|
||||
print(f"[Kling 4.0] uploading {label}...")
|
||||
return await upload_image(_prepare_image_for_upload(image), base_url=base_url)
|
||||
|
||||
validated_video_paths = []
|
||||
reference_video_seconds = 0.0
|
||||
for video in reference_video_inputs:
|
||||
video_path = _resolve_reference_video_path(video)
|
||||
reference_video_seconds += _validate_kling_v4_reference_video(video_path)
|
||||
validated_video_paths.append(video_path)
|
||||
if reference_video_seconds > _V4_REFERENCE_VIDEO_MAX_DURATION:
|
||||
raise RuntimeError("Kling 4.0 参考视频总时长不能超过 30 秒。")
|
||||
|
||||
first_url = await upload_frame(first_frame, "first frame")
|
||||
middle_urls = [
|
||||
await upload_frame(image, f"middle frame {index}")
|
||||
for index, image in enumerate(middle_frame_inputs, start=1)
|
||||
]
|
||||
last_url = await upload_frame(last_frame, "last frame")
|
||||
|
||||
reference_image_urls = [
|
||||
await upload_frame(image, f"reference image {index}")
|
||||
for index, image in enumerate(reference_image_inputs, start=1)
|
||||
]
|
||||
reference_video_urls = []
|
||||
for index, video_path in enumerate(validated_video_paths, start=1):
|
||||
print(f"[Kling 4.0] uploading reference video {index}...")
|
||||
reference_video_urls.append(await upload_video(video_path, base_url=base_url))
|
||||
|
||||
body = build_kling_v4_body(
|
||||
generation_mode=generation_mode,
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
duration=duration,
|
||||
resolution=resolution,
|
||||
aspect_ratio=aspect_ratio,
|
||||
first_frame=first_url,
|
||||
middle_frames=middle_urls,
|
||||
last_frame=last_url,
|
||||
reference_images=reference_image_urls,
|
||||
reference_videos=reference_video_urls,
|
||||
)
|
||||
if shots:
|
||||
body["multi_shot"] = True
|
||||
body["shot_type"] = "customize"
|
||||
body["multi_prompt"] = [
|
||||
{"index": shot["index"], "prompt": shot["prompt"], "duration": shot["duration"]}
|
||||
for shot in shots
|
||||
]
|
||||
|
||||
create_path, status_path = kling_v4_endpoint_for(generation_mode)
|
||||
return await _run_video_task(
|
||||
base_url,
|
||||
headers,
|
||||
body,
|
||||
create_path,
|
||||
status_path,
|
||||
f"Kling 4.0 {generation_mode} submit: ",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def _build_standard(cls, 模型, base_url, headers, 起始帧, 提示词, 负向提示词, 时长, 生成音频, 模式, shots, 尾帧=None):
|
||||
"""标准图生视频接口:POST /kling/v1/videos/image2video
|
||||
|
||||
+3
-1
@@ -28,6 +28,7 @@ from .grok_video import O1keyGrokVideo, O1keyGrokVideoEdit
|
||||
from .K3_video import K3Video
|
||||
from .K3_motion_control import K3MotionControl
|
||||
from .save_image_format import SaveImageFormat
|
||||
from .save_gif import O1keySaveGIF
|
||||
from .save_psd import O1keySavePSD
|
||||
from .remove_bg import O1keyRemoveBackground
|
||||
from .grid_splitter import O1keyGridSplitter
|
||||
@@ -40,5 +41,6 @@ from .seedance_autopass_batch import SeedanceAutoPassBatch
|
||||
from .o1key_image_generator import O1keyImageGenerator, O1keyImageSave
|
||||
from .o1key_video_generator import O1keyVideoGenerator, O1keyVideoResult
|
||||
from .omni_flash_video import O1keyOmniFlashVideo
|
||||
from .mj_image import O1keyMJImage
|
||||
|
||||
__all__ = ['NanoBanana', 'BatchNanoBananaPro', 'GoogleGemini', 'LoadFile', 'LoadImagesFromFolder', 'ImageStitchPro', 'BatchCleanMetadata', 'VideoPreview', 'GoogleVeo', 'Google31Video', 'MiniMaxH3Video', 'FluxImageEdit', 'UniversalLLMChat', 'BatchImagesO1key', 'SeedanceMultiModal', 'StreamPreview', 'DoubaoImage', 'O1keyGPTImage', 'O1keyGPTImageBatch', 'O1keyGrokImage', 'O1keyGrokVideo', 'O1keyGrokVideoEdit', 'K3Video', 'K3MotionControl', 'SaveImageFormat', 'O1keySavePSD', 'O1keyRemoveBackground', 'O1keyGridSplitter', 'O1keyAutoRedCast', 'O1keyPromptMultiFunction', 'O1keyVideoTrim', 'SeedanceElementCreate', 'SeedanceAutoPass', 'SeedanceAutoPassBatch', 'O1keyImageGenerator', 'O1keyImageSave', 'O1keyVideoGenerator', 'O1keyVideoResult', 'O1keyOmniFlashVideo']
|
||||
__all__ = ['NanoBanana', 'BatchNanoBananaPro', 'GoogleGemini', 'LoadFile', 'LoadImagesFromFolder', 'ImageStitchPro', 'BatchCleanMetadata', 'VideoPreview', 'GoogleVeo', 'Google31Video', 'MiniMaxH3Video', 'FluxImageEdit', 'UniversalLLMChat', 'BatchImagesO1key', 'SeedanceMultiModal', 'StreamPreview', 'DoubaoImage', 'O1keyGPTImage', 'O1keyGPTImageBatch', 'O1keyGrokImage', 'O1keyGrokVideo', 'O1keyGrokVideoEdit', 'K3Video', 'K3MotionControl', 'SaveImageFormat', 'O1keySaveGIF', 'O1keySavePSD', 'O1keyRemoveBackground', 'O1keyGridSplitter', 'O1keyAutoRedCast', 'O1keyPromptMultiFunction', 'O1keyVideoTrim', 'SeedanceElementCreate', 'SeedanceAutoPass', 'SeedanceAutoPassBatch', 'O1keyImageGenerator', 'O1keyImageSave', 'O1keyVideoGenerator', 'O1keyVideoResult', 'O1keyOmniFlashVideo', 'O1keyMJImage']
|
||||
|
||||
+113
-14
@@ -1,6 +1,6 @@
|
||||
"""
|
||||
o1key GPT Image 节点
|
||||
支持 GPT Image 2 / 2.5 系列的文生图、图生图和带蒙版图像编辑
|
||||
支持 GPT Image 2 / 2.5 / 2.6 系列的文生图、图生图和带蒙版图像编辑
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -20,12 +20,29 @@ from ..utils.image_utils import parse_batch_prompts, pil_to_tensor, tensor_to_pi
|
||||
from ..utils.config import get_base_url_by_route
|
||||
from ..utils.o1key_image_catalog import (
|
||||
GPT_IMAGE_BACKGROUND_OPTIONS,
|
||||
GPT_IMAGE_COMPLEXITY_OPTIONS,
|
||||
GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MAX,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MIN,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MAX,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MIN,
|
||||
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,
|
||||
GPT_IMAGE_EXACT_SIZE_OPTIONS,
|
||||
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
|
||||
GPT_IMAGE_25_QUALITY_OPTIONS,
|
||||
resolve_gpt_image_quality,
|
||||
resolve_gpt_image_size,
|
||||
)
|
||||
from ..utils.gpt_image_media import (
|
||||
animation_bytes_from_images,
|
||||
svg_bytes_from_image,
|
||||
write_bytes_atomic,
|
||||
)
|
||||
from ..utils.file_utils import (
|
||||
ImageInfo,
|
||||
generate_timestamp_filename,
|
||||
@@ -142,13 +159,17 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
io.Combo.Input(
|
||||
"模型",
|
||||
options=GPT_IMAGE_MODEL_OPTIONS,
|
||||
default="gpt-image-2.5-sunburst",
|
||||
default="gpt-image-2.6-sunburst",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"模型线路",
|
||||
options=GPT_IMAGE_ROUTE_OPTIONS,
|
||||
default="畅速",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"复杂度", options=GPT_IMAGE_COMPLEXITY_OPTIONS, default="高",
|
||||
tooltip="仅 GPT Image 2.6 生效:低 / 中 / 高;越高规划越充分、耗时越长。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"分辨率",
|
||||
options=GPT_IMAGE_EXACT_SIZE_OPTIONS,
|
||||
@@ -168,13 +189,13 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
"质量",
|
||||
options=GPT_IMAGE_25_QUALITY_OPTIONS,
|
||||
default="自动",
|
||||
tooltip="GPT Image 2 支持高/中/低/自动;GPT Image 2.5 另支持超高=xhigh、最高=max。",
|
||||
tooltip="GPT Image 2 支持高/中/低/自动;GPT Image 2.5 / 2.6 另支持超高=xhigh、最高=max。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"输出格式",
|
||||
options=["png", "jpeg", "webp"],
|
||||
options=GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS,
|
||||
default="png",
|
||||
tooltip="Generated image output format",
|
||||
tooltip="2.6 另支持 svg / gif;svg/gif 仅纯文生图可用。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"背景",
|
||||
@@ -204,8 +225,29 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
control_after_generate=io.ControlAfterGenerate.randomize,
|
||||
tooltip="Random seed (0 = not specified)",
|
||||
),
|
||||
io.Int.Input(
|
||||
"帧数",
|
||||
default=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
min=GPT_IMAGE_GIF_FRAME_COUNT_MIN,
|
||||
max=GPT_IMAGE_GIF_FRAME_COUNT_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="仅输出格式为 gif 时生效:2–64,默认 9。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"帧时长ms",
|
||||
default=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
min=GPT_IMAGE_GIF_FRAME_DURATION_MIN,
|
||||
max=GPT_IMAGE_GIF_FRAME_DURATION_MAX,
|
||||
step=10,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="仅输出格式为 gif 时生效:20–2000ms,默认 200,按 10ms 取整。",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(display_name="IMAGE"),
|
||||
io.String.Output("FILE", display_name="文件路径"),
|
||||
],
|
||||
outputs=[io.Image.Output(display_name="IMAGE")],
|
||||
# 兼容 Autogrow 改造前保存的参考图1~参考图9端口。
|
||||
accept_all_inputs=True,
|
||||
)
|
||||
@@ -214,7 +256,7 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
def execute(
|
||||
cls,
|
||||
prompt: str,
|
||||
模型: str = "gpt-image-2.5-sunburst",
|
||||
模型: str = "gpt-image-2.6-sunburst",
|
||||
模型线路: str = "畅速",
|
||||
分辨率: str = "智能",
|
||||
质量: str = "自动",
|
||||
@@ -224,6 +266,9 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
遮罩=None,
|
||||
缩放图片: str = "智能缩放",
|
||||
背景: str = "auto",
|
||||
复杂度: str = "高",
|
||||
帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
**kwargs,
|
||||
) -> io.NodeOutput:
|
||||
result = cls.generate(
|
||||
@@ -238,15 +283,21 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
遮罩=遮罩,
|
||||
缩放图片=缩放图片,
|
||||
背景=背景,
|
||||
复杂度=复杂度,
|
||||
帧数=帧数,
|
||||
帧时长ms=帧时长ms,
|
||||
**kwargs,
|
||||
)
|
||||
return io.NodeOutput(*result)
|
||||
tensor, file_path, preview = result
|
||||
if preview is not None:
|
||||
return io.NodeOutput(tensor, file_path, ui=preview)
|
||||
return io.NodeOutput(tensor, file_path)
|
||||
|
||||
@classmethod
|
||||
def generate(
|
||||
cls,
|
||||
prompt: str,
|
||||
模型: str = "gpt-image-2.5-sunburst",
|
||||
模型: str = "gpt-image-2.6-sunburst",
|
||||
模型线路: str = "畅速",
|
||||
分辨率: str = "智能",
|
||||
质量: str = "自动",
|
||||
@@ -256,6 +307,9 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
遮罩=None,
|
||||
缩放图片: str = "智能缩放",
|
||||
背景: str = "auto",
|
||||
复杂度: str = "高",
|
||||
帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
@@ -285,12 +339,19 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
raise ValueError("提供了遮罩但未提供图片,请同时提供图片和遮罩")
|
||||
if 缩放图片 not in {"不缩放", "智能缩放"}:
|
||||
raise ValueError("缩放图片参数无效")
|
||||
if 输出格式 not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS:
|
||||
raise ValueError("GPT Image 输出格式无效")
|
||||
if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS:
|
||||
raise ValueError("GPT Image 背景参数无效")
|
||||
if 背景 == "transparent" and 输出格式 == "jpeg":
|
||||
输出格式 = resolve_gpt_image_output_format(模型, 输出格式)
|
||||
if 背景 == "transparent" and 输出格式 not in {"png", "webp"}:
|
||||
raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式")
|
||||
validate_gpt_image_vector_output(
|
||||
模型,
|
||||
输出格式,
|
||||
has_images=bool(图片),
|
||||
has_mask=遮罩 is not None,
|
||||
)
|
||||
frame_count = resolve_gpt_image_frame_count(输出格式, 帧数)
|
||||
frame_duration_ms = resolve_gpt_image_frame_duration_ms(输出格式, 帧时长ms)
|
||||
|
||||
# ── 2. 解析分辨率显示值 → API 参数值 ──────────────────────────────────
|
||||
size = _resolve_async_size(分辨率)
|
||||
@@ -300,6 +361,7 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
|
||||
# ── 2c. 解析质量显示值 → API 参数值 ───────────────────────────────────
|
||||
quality = resolve_gpt_image_quality(模型, 质量)
|
||||
complexity = resolve_gpt_image_complexity(模型, 复杂度)
|
||||
|
||||
# ── 3. 创建客户端 ─────────────────────────────────────────────────────
|
||||
try:
|
||||
@@ -348,6 +410,9 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
mask_tensor=遮罩,
|
||||
output_format=输出格式,
|
||||
background=背景,
|
||||
**({"complexity": complexity} if complexity is not None else {}),
|
||||
**({"frame_count": frame_count} if frame_count is not None else {}),
|
||||
**({"frame_duration_ms": frame_duration_ms} if frame_duration_ms is not None else {}),
|
||||
progress_callback=_make_node_progress_callback(progress_bar, idx, total),
|
||||
special_price_parallel=True,
|
||||
task_submitted_callback=_submitted,
|
||||
@@ -381,6 +446,9 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
mask_tensor=遮罩,
|
||||
output_format=输出格式,
|
||||
background=背景,
|
||||
**({"complexity": complexity} if complexity is not None else {}),
|
||||
**({"frame_count": frame_count} if frame_count is not None else {}),
|
||||
**({"frame_duration_ms": frame_duration_ms} if frame_duration_ms is not None else {}),
|
||||
progress_callback=_make_node_progress_callback(progress_bar, 1, 1),
|
||||
special_price_parallel=True,
|
||||
task_submitted_callback=_submitted,
|
||||
@@ -402,6 +470,37 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
raise RuntimeError("所有提示词均生成失败,无可用图像输出")
|
||||
|
||||
# ── 7. PIL → tensor ───────────────────────────────────────────────
|
||||
file_path = ""
|
||||
preview = None
|
||||
anim = animation_bytes_from_images(all_pil_images)
|
||||
svg = svg_bytes_from_image(all_pil_images[0]) if all_pil_images else None
|
||||
if _FOLDER_PATHS_AVAILABLE and (anim is not None or svg is not None):
|
||||
media_root = (
|
||||
folder_paths.get_temp_directory()
|
||||
if anim is not None
|
||||
else folder_paths.get_output_directory()
|
||||
)
|
||||
os.makedirs(media_root, exist_ok=True)
|
||||
target = generate_timestamp_filename(
|
||||
output_folder=media_root,
|
||||
prefix="gpt_image",
|
||||
extension=".gif" if anim is not None else ".svg",
|
||||
)
|
||||
if anim is not None:
|
||||
# Durable copy lives in output via the dedicated「保存 GIF」node.
|
||||
# Temp here only backs the「文件路径」output — no in-node preview
|
||||
# (user request: gpt image itself should not preview GIFs).
|
||||
write_bytes_atomic(target, anim)
|
||||
file_path = target
|
||||
preview = None
|
||||
print(
|
||||
f"[o1key GPT Image] GIF 已写入 temp(持久保存请接「保存 GIF」): {file_path}"
|
||||
)
|
||||
else:
|
||||
write_bytes_atomic(target, svg)
|
||||
file_path = target
|
||||
print(f"[o1key GPT Image] SVG 已保存: {file_path}")
|
||||
|
||||
output_tensor = GptImageClient._pil_list_to_tensor(all_pil_images)
|
||||
|
||||
# ── 8. 完成日志 ───────────────────────────────────────────────────
|
||||
@@ -412,7 +511,7 @@ class O1keyGPTImage(io.ComfyNode):
|
||||
f"{output_tensor.shape[2]}×{output_tensor.shape[1]}"
|
||||
)
|
||||
|
||||
return (output_tensor,)
|
||||
return (output_tensor, file_path, preview)
|
||||
|
||||
finally:
|
||||
cls._print_balance(client)
|
||||
|
||||
+88
-14
@@ -29,8 +29,22 @@ from ..utils.file_utils import (
|
||||
from ..utils.image_utils import parse_batch_prompts, pil_to_tensor, tensor_to_pil
|
||||
from ..utils.o1key_image_catalog import (
|
||||
GPT_IMAGE_BACKGROUND_OPTIONS,
|
||||
GPT_IMAGE_COMPLEXITY_OPTIONS,
|
||||
GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MAX,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MIN,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MAX,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MIN,
|
||||
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,
|
||||
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
|
||||
)
|
||||
from ..utils.gpt_image_media import animation_bytes_from_images, svg_bytes_from_image, write_bytes_atomic
|
||||
|
||||
try:
|
||||
from comfy.model_management import InterruptProcessingException
|
||||
@@ -134,14 +148,18 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
tooltip="可用独占一行的 --- 分隔多条提示词。"),
|
||||
io.Combo.Input(
|
||||
"模型", options=GPT_IMAGE_MODEL_OPTIONS,
|
||||
default="gpt-image-2.5-sunburst",
|
||||
default="gpt-image-2.6-sunburst",
|
||||
),
|
||||
io.Combo.Input("模型线路", options=GPT_IMAGE_ROUTE_OPTIONS, default="畅速"),
|
||||
io.Combo.Input(
|
||||
"复杂度", options=GPT_IMAGE_COMPLEXITY_OPTIONS, default="高",
|
||||
tooltip="仅 GPT Image 2.6 生效:低 / 中 / 高;越高规划越充分、耗时越长。",
|
||||
),
|
||||
io.Combo.Input("分辨率", options=_RESOLUTION_OPTIONS, default="智能"),
|
||||
io.Int.Input("生图数量", default=1, min=1, max=8, step=1),
|
||||
io.Combo.Input(
|
||||
"质量", options=GPT_IMAGE_25_QUALITY_OPTIONS, default="自动",
|
||||
tooltip="GPT Image 2.5 另支持超高=xhigh、最高=max。",
|
||||
tooltip="GPT Image 2.5 / 2.6 另支持超高=xhigh、最高=max。",
|
||||
),
|
||||
io.DynamicCombo.Input(
|
||||
"图片路径数量",
|
||||
@@ -151,7 +169,7 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
io.Mask.Input("遮罩", optional=True,
|
||||
tooltip="应用到每个任务的第一张参考图。"),
|
||||
references,
|
||||
io.Combo.Input("图片输出格式", options=["原始", "JPEG", "PNG", "WebP"],
|
||||
io.Combo.Input("图片输出格式", options=["原始", "JPEG", "PNG", "WebP", "SVG", "GIF"],
|
||||
default="原始"),
|
||||
io.Combo.Input(
|
||||
"背景",
|
||||
@@ -173,6 +191,24 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
"seed", default=0, min=0, max=2**31 - 1, step=1,
|
||||
control_after_generate=io.ControlAfterGenerate.randomize,
|
||||
),
|
||||
io.Int.Input(
|
||||
"帧数",
|
||||
default=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
min=GPT_IMAGE_GIF_FRAME_COUNT_MIN,
|
||||
max=GPT_IMAGE_GIF_FRAME_COUNT_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="仅图片输出格式为 GIF 时生效。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"帧时长ms",
|
||||
default=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
min=GPT_IMAGE_GIF_FRAME_DURATION_MIN,
|
||||
max=GPT_IMAGE_GIF_FRAME_DURATION_MAX,
|
||||
step=10,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="仅图片输出格式为 GIF 时生效;按 10ms 取整。",
|
||||
),
|
||||
],
|
||||
outputs=[io.Image.Output(display_name="输出图像")],
|
||||
accept_all_inputs=True,
|
||||
@@ -238,13 +274,33 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
naming_rule: str, task_index: int, base_filename: Optional[str],
|
||||
) -> List[str]:
|
||||
saved = []
|
||||
anim = animation_bytes_from_images(images)
|
||||
svg = svg_bytes_from_image(images[0]) if images else None
|
||||
if anim is not None or svg is not None:
|
||||
ext = ".gif" if anim is not None else ".svg"
|
||||
data = anim if anim is not None else svg
|
||||
if naming_rule == "自然数字":
|
||||
stem = str(task_index + 1)
|
||||
else:
|
||||
stem = base_filename or f"task_{task_index + 1}"
|
||||
path = os.path.join(folder, f"{stem}{ext}")
|
||||
collision = 1
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(folder, f"{stem}+{collision}{ext}")
|
||||
collision += 1
|
||||
write_bytes_atomic(path, data)
|
||||
saved.append(path)
|
||||
if svg is not None:
|
||||
# also save raster preview frames/image next to svg
|
||||
pass
|
||||
return saved
|
||||
for image_index, image in enumerate(images, 1):
|
||||
if image_format == "原始":
|
||||
fmt = str(getattr(image, "format", None) or "PNG").upper()
|
||||
fmt = "JPEG" if fmt in ("JPG", "JPEG") else "WEBP" if fmt == "WEBP" else "PNG"
|
||||
else:
|
||||
fmt = image_format.upper()
|
||||
ext = {"JPEG": ".jpg", "WEBP": ".webp"}.get(fmt, ".png")
|
||||
ext = {"JPEG": ".jpg", "WEBP": ".webp", "GIF": ".gif", "SVG": ".svg"}.get(fmt, ".png")
|
||||
if naming_rule == "自然数字":
|
||||
stem = str(task_index + 1)
|
||||
if image_index > 1:
|
||||
@@ -284,7 +340,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
cls, client, pair, task_prompt, task_index, total_tasks,
|
||||
model, quality, size, image_count, seed, mask, output_format,
|
||||
background, resize_mode,
|
||||
folder, naming_rule, save_lock, progress_callback,
|
||||
folder, naming_rule, save_lock, progress_callback, complexity=None,
|
||||
frame_count=None, frame_duration_ms=None,
|
||||
) -> dict:
|
||||
try:
|
||||
task_started = time.time()
|
||||
@@ -294,6 +351,7 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
image_tensor=[pil_to_tensor([item.image]) for item in pair],
|
||||
mask_tensor=mask, output_format=output_format,
|
||||
background=background,
|
||||
**({"complexity": complexity} if complexity is not None else {}),
|
||||
progress_callback=progress_callback,
|
||||
special_price_parallel=True,
|
||||
log_downloads=True,
|
||||
@@ -328,7 +386,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
async def _process_async(
|
||||
cls, client, task_defs, model, quality, size, image_count, seed,
|
||||
mask, output_format, background, resize_mode,
|
||||
folder, naming_rule, pbar,
|
||||
folder, naming_rule, pbar, complexity=None,
|
||||
frame_count=None, frame_duration_ms=None,
|
||||
) -> List[dict]:
|
||||
total = len(task_defs)
|
||||
progress_values = [0] * total
|
||||
@@ -338,7 +397,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
client, pair, prompt, index, total, model, quality, size,
|
||||
image_count, seed, mask, output_format, background,
|
||||
resize_mode, folder, naming_rule,
|
||||
save_lock, cls._progress_callback(progress_values, index, pbar),
|
||||
save_lock, cls._progress_callback(progress_values, index, pbar), complexity,
|
||||
frame_count, frame_duration_ms,
|
||||
))
|
||||
for index, pair, prompt in task_defs
|
||||
]
|
||||
@@ -357,10 +417,11 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
|
||||
@classmethod
|
||||
def execute(
|
||||
cls, prompt, 模型="gpt-image-2.5-sunburst", 模型线路="畅速", 分辨率="智能", 生图数量=1,
|
||||
cls, prompt, 模型="gpt-image-2.6-sunburst", 模型线路="畅速", 分辨率="智能", 生图数量=1,
|
||||
质量="自动", 图片路径数量=None, 遮罩=None, seed=0,
|
||||
图片输出格式="原始", 图片保存命名规则="和原始图片名保持一致",
|
||||
图片保存路径="", 缩放图片="智能缩放", 背景="auto", **kwargs,
|
||||
图片保存路径="", 缩放图片="智能缩放", 背景="auto", 复杂度="高",
|
||||
帧数=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, 帧时长ms=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, **kwargs,
|
||||
) -> io.NodeOutput:
|
||||
if not prompt or not str(prompt).strip():
|
||||
raise ValueError("提示词不能为空")
|
||||
@@ -369,6 +430,7 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS:
|
||||
raise ValueError("GPT Image 背景参数无效")
|
||||
|
||||
complexity = resolve_gpt_image_complexity(模型, 复杂度)
|
||||
actual_model = resolve_gpt_image_model(模型, 模型线路)
|
||||
|
||||
# 兼容旧节点通过命名参数调用时使用的字段名。
|
||||
@@ -419,11 +481,22 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
|
||||
folder = cls._output_folder(图片保存路径)
|
||||
quality = resolve_gpt_image_quality(模型, 质量)
|
||||
output_format = {"原始": "png", "JPEG": "jpeg", "PNG": "png", "WebP": "webp"}.get(图片输出格式, "png")
|
||||
if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS:
|
||||
raise ValueError("GPT Image 输出格式无效")
|
||||
if 背景 == "transparent" and output_format == "jpeg":
|
||||
output_format = {
|
||||
"原始": "png", "JPEG": "jpeg", "PNG": "png", "WebP": "webp",
|
||||
"SVG": "svg", "GIF": "gif",
|
||||
"jpeg": "jpeg", "png": "png", "webp": "webp", "svg": "svg", "gif": "gif",
|
||||
}.get(图片输出格式, "png")
|
||||
output_format = resolve_gpt_image_output_format(模型, output_format)
|
||||
if 背景 == "transparent" and output_format not in {"png", "webp"}:
|
||||
raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式")
|
||||
frame_count = resolve_gpt_image_frame_count(output_format, 帧数)
|
||||
frame_duration_ms = resolve_gpt_image_frame_duration_ms(output_format, 帧时长ms)
|
||||
validate_gpt_image_vector_output(
|
||||
模型,
|
||||
output_format,
|
||||
has_images=True,
|
||||
has_mask=遮罩 is not None,
|
||||
)
|
||||
client = GptImageClient()
|
||||
client.base_url = get_base_url_by_route()
|
||||
client.response_log_enabled = False
|
||||
@@ -443,7 +516,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
|
||||
client, task_defs, actual_model, quality, _resolve_size(分辨率),
|
||||
生图数量, seed, 遮罩, output_format, 背景,
|
||||
缩放图片, folder,
|
||||
图片保存命名规则, pbar,
|
||||
图片保存命名规则, pbar, complexity,
|
||||
frame_count, frame_duration_ms,
|
||||
)
|
||||
return loop.run_until_complete(client._run_with_interrupt(coro))
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""o1key MJ图片生成节点(Midjourney v8.2)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import List
|
||||
|
||||
from comfy_api.latest import io
|
||||
|
||||
from ..clients.mj_image_client import (
|
||||
MJ_DEFAULT_TIMEOUT_SECONDS,
|
||||
MJ_NODE_LABEL,
|
||||
MjImageClient,
|
||||
pil_images_to_output_tensor,
|
||||
tensors_to_reference_images,
|
||||
)
|
||||
from ..utils.mj_prompt import (
|
||||
MJ_ASPECT_RATIO_OPTIONS,
|
||||
MJ_CHAOS_DEFAULT,
|
||||
MJ_CHAOS_MAX,
|
||||
MJ_CHAOS_MIN,
|
||||
MJ_CONTENT_REF_MAX,
|
||||
MJ_EXP_DEFAULT,
|
||||
MJ_EXP_MAX,
|
||||
MJ_EXP_MIN,
|
||||
MJ_IW_DEFAULT,
|
||||
MJ_IW_MAX,
|
||||
MJ_IW_MIN,
|
||||
MJ_QUALITY_DEFAULT,
|
||||
MJ_QUALITY_MAX,
|
||||
MJ_QUALITY_MIN,
|
||||
MJ_STYLE_REF_MAX,
|
||||
MJ_STYLIZE_DEFAULT,
|
||||
MJ_STYLIZE_MAX,
|
||||
MJ_STYLIZE_MIN,
|
||||
MJ_SW_DEFAULT,
|
||||
MJ_SW_MAX,
|
||||
MJ_SW_MIN,
|
||||
MJ_WEIRD_DEFAULT,
|
||||
MJ_WEIRD_MAX,
|
||||
MJ_WEIRD_MIN,
|
||||
)
|
||||
|
||||
try:
|
||||
from comfy.model_management import InterruptProcessingException, processing_interrupted
|
||||
|
||||
_INTERRUPT_AVAILABLE = True
|
||||
except ImportError:
|
||||
_INTERRUPT_AVAILABLE = False
|
||||
|
||||
def processing_interrupted():
|
||||
return False
|
||||
|
||||
InterruptProcessingException = RuntimeError
|
||||
|
||||
try:
|
||||
from comfy.utils import ProgressBar
|
||||
|
||||
_PROGRESS_BAR_AVAILABLE = True
|
||||
except ImportError:
|
||||
_PROGRESS_BAR_AVAILABLE = False
|
||||
|
||||
|
||||
def _check_interrupt() -> None:
|
||||
if _INTERRUPT_AVAILABLE and processing_interrupted():
|
||||
raise InterruptProcessingException()
|
||||
|
||||
|
||||
def _collect_autogrow_inputs(value) -> list:
|
||||
"""收集已连接的 Autogrow 输入,并兼容单个旧值。"""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, dict):
|
||||
return [item for item in value.values() if item is not None]
|
||||
return [value]
|
||||
|
||||
|
||||
def _collect_reference_images(
|
||||
*,
|
||||
group_value,
|
||||
kwargs: dict,
|
||||
max_count: int,
|
||||
label: str,
|
||||
numbered_prefix: str,
|
||||
legacy_key: str,
|
||||
) -> List:
|
||||
"""从 Autogrow 组收集参考图;为空时兼容编号口与旧单口。"""
|
||||
tensors = _collect_autogrow_inputs(group_value)
|
||||
if not tensors:
|
||||
tensors = [
|
||||
kwargs[f"{numbered_prefix}{i}"]
|
||||
for i in range(1, max_count + 1)
|
||||
if kwargs.get(f"{numbered_prefix}{i}") is not None
|
||||
]
|
||||
if not tensors and kwargs.get(legacy_key) is not None:
|
||||
tensors = [kwargs.get(legacy_key)]
|
||||
|
||||
images: List = []
|
||||
for tensor in tensors:
|
||||
part = tensors_to_reference_images(
|
||||
tensor,
|
||||
max_count=max_count,
|
||||
label=label,
|
||||
)
|
||||
images.extend(part)
|
||||
if len(images) > max_count:
|
||||
raise ValueError(
|
||||
f"{label}最多 {max_count} 张(当前输入为 {len(images)} 张)"
|
||||
)
|
||||
return images
|
||||
|
||||
|
||||
class O1keyMJImage(io.ComfyNode):
|
||||
"""独立 Midjourney 生图节点;非草稿固定 4 张,草稿模式接受任意数量。"""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
content_references = io.Autogrow.Input(
|
||||
"参考图组",
|
||||
template=io.Autogrow.TemplateNames(
|
||||
input=io.Image.Input("参考图"),
|
||||
names=[f"参考图{i}" for i in range(1, MJ_CONTENT_REF_MAX + 1)],
|
||||
min=0,
|
||||
),
|
||||
tooltip=(
|
||||
f"内容/构图参考(对应图生图):约束主体姿势、构图与物体。"
|
||||
f"接好一张后自动出现下一张;最多 {MJ_CONTENT_REF_MAX} 张。"
|
||||
f"可与「风格参考图」同时使用;不传则为纯文生图。"
|
||||
),
|
||||
)
|
||||
style_references = io.Autogrow.Input(
|
||||
"风格参考图组",
|
||||
template=io.Autogrow.TemplateNames(
|
||||
input=io.Image.Input("风格参考图"),
|
||||
names=[f"风格参考图{i}" for i in range(1, MJ_STYLE_REF_MAX + 1)],
|
||||
min=0,
|
||||
),
|
||||
tooltip=(
|
||||
f"风格/画风参考(写入 --sref):只学色彩、笔触、氛围,不强制同一构图。"
|
||||
f"接好一张后自动出现下一张;最多 {MJ_STYLE_REF_MAX} 张。"
|
||||
f"强度由「风格权重」控制。"
|
||||
),
|
||||
)
|
||||
return io.Schema(
|
||||
node_id="O1keyMJImage",
|
||||
display_name="o1key MJ图片生成",
|
||||
category="o1key/image",
|
||||
inputs=[
|
||||
io.String.Input(
|
||||
"提示词",
|
||||
default="",
|
||||
multiline=True,
|
||||
tooltip="画面描述。Midjourney 参数由下方控件写入 prompt;若手写同名参数会被控件值覆盖。",
|
||||
),
|
||||
content_references,
|
||||
style_references,
|
||||
io.Float.Input(
|
||||
"参考图权重",
|
||||
default=MJ_IW_DEFAULT,
|
||||
min=MJ_IW_MIN,
|
||||
max=MJ_IW_MAX,
|
||||
step=0.1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="写入 --iw;仅在有内容参考图时生效,越高越贴合参考结构。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"风格权重",
|
||||
default=MJ_SW_DEFAULT,
|
||||
min=MJ_SW_MIN,
|
||||
max=MJ_SW_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="写入 --sw;仅在有风格参考图时生效,范围 0–1000,默认 100。",
|
||||
),
|
||||
io.String.Input(
|
||||
"排除内容",
|
||||
default="",
|
||||
multiline=False,
|
||||
tooltip="有内容时写入 --no ...;控件优先,会覆盖提示词里手写的 --no。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"画面比例",
|
||||
options=list(MJ_ASPECT_RATIO_OPTIONS),
|
||||
default="1:1",
|
||||
tooltip="写入 --ar;控制比例,不承诺精确像素。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"渲染质量",
|
||||
default=MJ_QUALITY_DEFAULT,
|
||||
min=MJ_QUALITY_MIN,
|
||||
max=MJ_QUALITY_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="写入 --q;v8.2 支持 1–4。",
|
||||
),
|
||||
io.Boolean.Input(
|
||||
"高清",
|
||||
default=False,
|
||||
label_on="开启",
|
||||
label_off="关闭",
|
||||
tooltip="开启后写入 --hd;长边约翻倍到 2048。",
|
||||
),
|
||||
io.Boolean.Input(
|
||||
"草稿模式",
|
||||
default=False,
|
||||
label_on="开启",
|
||||
label_off="关闭",
|
||||
tooltip="开启后写入 --draft;更快更便宜,出图数量可能不是 4 张。",
|
||||
),
|
||||
io.Boolean.Input(
|
||||
"原生模式",
|
||||
default=False,
|
||||
label_on="开启",
|
||||
label_off="关闭",
|
||||
tooltip="开启后写入 --raw;弱化默认美化滤镜。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"风格化",
|
||||
default=MJ_STYLIZE_DEFAULT,
|
||||
min=MJ_STYLIZE_MIN,
|
||||
max=MJ_STYLIZE_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="写入 --s;0–1000,默认 250,越高越艺术化。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"差异度",
|
||||
default=MJ_CHAOS_DEFAULT,
|
||||
min=MJ_CHAOS_MIN,
|
||||
max=MJ_CHAOS_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="写入 --c;仅当大于 0 时写入。越高四张候选差异越大。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"怪异度",
|
||||
default=MJ_WEIRD_DEFAULT,
|
||||
min=MJ_WEIRD_MIN,
|
||||
max=MJ_WEIRD_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="写入 --weird;仅当大于 0 时写入,范围 0–3000。",
|
||||
),
|
||||
io.Boolean.Input(
|
||||
"无缝平铺纹理",
|
||||
default=False,
|
||||
label_on="开启",
|
||||
label_off="关闭",
|
||||
tooltip="开启后写入 --tile;适合壁纸、贴图等可无限拼接的无缝纹理。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"实验值",
|
||||
default=MJ_EXP_DEFAULT,
|
||||
min=MJ_EXP_MIN,
|
||||
max=MJ_EXP_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="写入 --exp;仅当大于 0 时写入,范围 0–100。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"种子",
|
||||
default=-1,
|
||||
min=-1,
|
||||
max=2**31 - 1,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="-1 表示不指定;≥0 时写入 --seed。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"超时秒数",
|
||||
default=MJ_DEFAULT_TIMEOUT_SECONDS,
|
||||
min=30,
|
||||
max=900,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="仅客户端轮询超时;单次任务通常 60–170 秒。",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(display_name="IMAGE"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(
|
||||
cls,
|
||||
提示词: str,
|
||||
画面比例: str = "1:1",
|
||||
渲染质量: int = MJ_QUALITY_DEFAULT,
|
||||
高清: bool = False,
|
||||
参考图权重: float = MJ_IW_DEFAULT,
|
||||
风格权重: int = MJ_SW_DEFAULT,
|
||||
原生模式: bool = False,
|
||||
风格化: int = MJ_STYLIZE_DEFAULT,
|
||||
差异度: int = MJ_CHAOS_DEFAULT,
|
||||
怪异度: int = MJ_WEIRD_DEFAULT,
|
||||
无缝平铺纹理: bool = False,
|
||||
实验值: int = MJ_EXP_DEFAULT,
|
||||
草稿模式: bool = False,
|
||||
排除内容: str = "",
|
||||
种子: int = -1,
|
||||
超时秒数: int = MJ_DEFAULT_TIMEOUT_SECONDS,
|
||||
**kwargs,
|
||||
) -> io.NodeOutput:
|
||||
start_time = time.time()
|
||||
_check_interrupt()
|
||||
|
||||
try:
|
||||
reference_images = _collect_reference_images(
|
||||
group_value=kwargs.get("参考图组"),
|
||||
kwargs=kwargs,
|
||||
max_count=MJ_CONTENT_REF_MAX,
|
||||
label="参考图",
|
||||
numbered_prefix="参考图",
|
||||
legacy_key="参考图",
|
||||
)
|
||||
style_images = _collect_reference_images(
|
||||
group_value=kwargs.get("风格参考图组"),
|
||||
kwargs=kwargs,
|
||||
max_count=MJ_STYLE_REF_MAX,
|
||||
label="风格参考图",
|
||||
numbered_prefix="风格参考图",
|
||||
legacy_key="风格参考图",
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValueError(str(exc)) from None
|
||||
|
||||
progress_bar = ProgressBar(100) if _PROGRESS_BAR_AVAILABLE else None
|
||||
last_pct = {"value": -1}
|
||||
|
||||
def _progress(fraction: float) -> None:
|
||||
if progress_bar is None:
|
||||
return
|
||||
try:
|
||||
pct = int(round(max(0.0, min(1.0, float(fraction))) * 100))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if pct < last_pct["value"]:
|
||||
return
|
||||
last_pct["value"] = pct
|
||||
progress_bar.update_absolute(pct, 100)
|
||||
|
||||
try:
|
||||
client = MjImageClient()
|
||||
except ValueError as exc:
|
||||
if str(exc) == "未授权!":
|
||||
print(f"[{MJ_NODE_LABEL}] 请联系作者授权后方可使用。")
|
||||
raise ValueError("未授权!") from None
|
||||
raise
|
||||
|
||||
opened = list(reference_images) + list(style_images)
|
||||
try:
|
||||
pil_images = client.generate_sync(
|
||||
prompt=提示词,
|
||||
aspect_ratio=画面比例,
|
||||
quality=渲染质量,
|
||||
hd=bool(高清),
|
||||
image_weight=参考图权重,
|
||||
raw=bool(原生模式),
|
||||
stylize=风格化,
|
||||
chaos=差异度,
|
||||
seed=种子,
|
||||
weird=怪异度,
|
||||
tile=bool(无缝平铺纹理),
|
||||
exp=实验值,
|
||||
draft=bool(草稿模式),
|
||||
no_text=排除内容 or "",
|
||||
style_weight=风格权重,
|
||||
images=reference_images,
|
||||
style_images=style_images,
|
||||
timeout_seconds=超时秒数,
|
||||
check_interrupt=_check_interrupt,
|
||||
progress_callback=_progress,
|
||||
)
|
||||
except InterruptProcessingException:
|
||||
print(f"[{MJ_NODE_LABEL}] 用户取消")
|
||||
raise
|
||||
except Exception as exc:
|
||||
message = str(exc).split("\n")[0]
|
||||
print(f"[{MJ_NODE_LABEL}] 失败:{message}")
|
||||
raise RuntimeError(message) from None
|
||||
finally:
|
||||
for image in opened:
|
||||
try:
|
||||
image.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if progress_bar is not None:
|
||||
progress_bar.update_absolute(100, 100)
|
||||
|
||||
output = pil_images_to_output_tensor(pil_images)
|
||||
elapsed = time.time() - start_time
|
||||
print(
|
||||
f"[{MJ_NODE_LABEL}] 节点完成 | 耗时 {elapsed:.1f}s | "
|
||||
f"输出 {output.shape[0]} 张 {output.shape[2]}x{output.shape[1]}"
|
||||
)
|
||||
return io.NodeOutput(output)
|
||||
|
||||
|
||||
__all__ = ["O1keyMJImage"]
|
||||
@@ -23,6 +23,7 @@ from ..clients.seedream_image_client import (
|
||||
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 (
|
||||
IMAGE_BATCH_MODE_ALIASES,
|
||||
IMAGE_BATCH_MODE_GROUP_TO_MODELS,
|
||||
IMAGE_BATCH_MODE_SINGLE_REFERENCES,
|
||||
IMAGE_BATCH_MODES,
|
||||
@@ -36,6 +37,19 @@ from ..utils.o1key_image_catalog import (
|
||||
BANANA_RESOLUTION_OPTIONS,
|
||||
GPT_IMAGE_ASPECT_RATIO_OPTIONS,
|
||||
GPT_IMAGE_BACKGROUND_OPTIONS,
|
||||
GPT_IMAGE_COMPLEXITY_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,
|
||||
GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MAX,
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MIN,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MAX,
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MIN,
|
||||
GPT_IMAGE_COUNTS,
|
||||
GPT_IMAGE_EXACT_SIZE_OPTIONS,
|
||||
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
|
||||
@@ -258,6 +272,9 @@ async def _generate_gpt_images(
|
||||
resize_mode: str,
|
||||
output_format: str,
|
||||
background: str,
|
||||
complexity: str | None = None,
|
||||
frame_count: int | None = None,
|
||||
frame_duration_ms: int | None = None,
|
||||
):
|
||||
if mask is not None and not references:
|
||||
raise ValueError("提供了蒙版但未提供参考图,请同时上传参考图")
|
||||
@@ -295,6 +312,9 @@ async def _generate_gpt_images(
|
||||
mask_tensor=mask,
|
||||
output_format=output_format,
|
||||
background=background,
|
||||
**({"complexity": complexity} if complexity is not None else {}),
|
||||
**({"frame_count": frame_count} if frame_count is not None else {}),
|
||||
**({"frame_duration_ms": frame_duration_ms} if frame_duration_ms is not None else {}),
|
||||
resize_mode=resize_mode,
|
||||
special_price_parallel=False,
|
||||
log_downloads=True,
|
||||
@@ -542,7 +562,7 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
io.Combo.Input(
|
||||
"思考等级",
|
||||
options=["低", "高"],
|
||||
default="低",
|
||||
default="高",
|
||||
socketless=True,
|
||||
),
|
||||
io.Combo.Input(
|
||||
@@ -566,6 +586,7 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
),
|
||||
io.Int.Input(
|
||||
"seed",
|
||||
display_name="种子",
|
||||
default=0,
|
||||
min=0,
|
||||
max=0xFFFFFFFFFFFFFFFF,
|
||||
@@ -587,7 +608,7 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
),
|
||||
io.Combo.Input(
|
||||
"输出格式",
|
||||
options=GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
|
||||
options=GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS,
|
||||
default="jpeg",
|
||||
socketless=True,
|
||||
),
|
||||
@@ -600,7 +621,7 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
io.Combo.Input(
|
||||
"缩放图片",
|
||||
options=["不缩放", "智能缩放"],
|
||||
default="不缩放",
|
||||
default="智能缩放",
|
||||
tooltip="Nano Banana 与 GPT Image 生效;智能缩放可能发生像素偏移。",
|
||||
socketless=True,
|
||||
),
|
||||
@@ -616,14 +637,19 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
default=False,
|
||||
label_on="开启",
|
||||
label_off="关闭",
|
||||
tooltip="关闭时保持普通参考图生成;开启后按素材图和目标图展开组合。",
|
||||
tooltip="关闭时按普通参考图生成;开启后把素材图按所选模式与目标图组合,一次排队生成多张。",
|
||||
socketless=True,
|
||||
),
|
||||
io.Combo.Input(
|
||||
"批量模式",
|
||||
options=list(IMAGE_BATCH_MODES),
|
||||
default=IMAGE_BATCH_MODE_GROUP_TO_MODELS,
|
||||
tooltip="整组素材:全部素材图作为一组并依次应用到多个目标;全匹配:每张素材图分别与每张目标图组合。",
|
||||
tooltip=(
|
||||
"素材图与目标图的配对方式。"
|
||||
"整组素材→多个目标:整组素材作为一套,依次套用到每张目标图;"
|
||||
"每张素材×每张目标:两两组合,覆盖最全;"
|
||||
"每张素材单独出图:不需要目标图,每张素材各自生成。"
|
||||
),
|
||||
socketless=True,
|
||||
),
|
||||
io.String.Input(
|
||||
@@ -659,13 +685,6 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
tooltip="留空保存到 ComfyUI output 根目录;相对路径是 output 内的子文件夹;绝对路径可保存到任意磁盘目录。",
|
||||
socketless=True,
|
||||
),
|
||||
io.Combo.Input(
|
||||
"在线搜索",
|
||||
options=["关闭", "打开"],
|
||||
default="关闭",
|
||||
tooltip="仅 Nano Banana 2 / 2.1 生效;打开时发送 google_search=true。",
|
||||
socketless=True,
|
||||
),
|
||||
io.Boolean.Input(
|
||||
"图层拆分",
|
||||
default=False,
|
||||
@@ -674,6 +693,31 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
tooltip="仅 Seedream 生效;必须且只能上传1张参考图,返回底图和最多16个透明图层。",
|
||||
socketless=True,
|
||||
),
|
||||
io.Combo.Input(
|
||||
"复杂度", options=GPT_IMAGE_COMPLEXITY_OPTIONS, default="高",
|
||||
tooltip="仅 GPT Image 2.6 生效;越高规划越充分、耗时越长。",
|
||||
socketless=True,
|
||||
),
|
||||
io.Int.Input(
|
||||
"帧数",
|
||||
default=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
min=GPT_IMAGE_GIF_FRAME_COUNT_MIN,
|
||||
max=GPT_IMAGE_GIF_FRAME_COUNT_MAX,
|
||||
step=1,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="仅 GPT Image 2.6 且输出 GIF 时生效。",
|
||||
socketless=True,
|
||||
),
|
||||
io.Int.Input(
|
||||
"帧时长ms",
|
||||
default=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
min=GPT_IMAGE_GIF_FRAME_DURATION_MIN,
|
||||
max=GPT_IMAGE_GIF_FRAME_DURATION_MAX,
|
||||
step=10,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
tooltip="仅 GPT Image 2.6 且输出 GIF 时生效;按 10ms 取整。",
|
||||
socketless=True,
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output("IMAGE", display_name="IMAGE"),
|
||||
@@ -690,7 +734,7 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
prompt: str,
|
||||
模型: str = "Nano Banana 2.1",
|
||||
模型线路: str = "畅速",
|
||||
思考等级: str = "低",
|
||||
思考等级: str = "高",
|
||||
分辨率: str = UNIFIED_IMAGE_SMART_RESOLUTION,
|
||||
宽高比: str = "智能",
|
||||
生图数量: str | int = "1",
|
||||
@@ -708,8 +752,10 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
filename_prefix: str = "o1key",
|
||||
格式: str = "原始",
|
||||
保存位置: str = "",
|
||||
在线搜索: str = "关闭",
|
||||
图层拆分: bool = False,
|
||||
复杂度: str = "高",
|
||||
帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
|
||||
帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
|
||||
) -> io.NodeOutput:
|
||||
layer_decomposition = _is_enabled(图层拆分)
|
||||
if (not prompt or not prompt.strip()) and not (
|
||||
@@ -719,7 +765,7 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
if 输出格式 is None:
|
||||
输出格式 = "png" if is_gpt_image_model(模型) else "jpeg"
|
||||
if 缩放图片 is None:
|
||||
缩放图片 = "智能缩放" if is_gpt_image_model(模型) else "不缩放"
|
||||
缩放图片 = "智能缩放"
|
||||
save_settings = _normalized_save_settings(
|
||||
模型,
|
||||
filename_prefix,
|
||||
@@ -729,9 +775,8 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
)
|
||||
if 缩放图片 not in {"不缩放", "智能缩放"}:
|
||||
raise ValueError("缩放图片参数无效")
|
||||
if 在线搜索 not in {"关闭", "打开"}:
|
||||
raise ValueError("在线搜索参数无效")
|
||||
google_search = 模型 in {"Nano Banana 2.1", "Nano Banana 2"} and 在线搜索 == "打开"
|
||||
# 在线搜索已下线:下游客户端仍支持 google_search,这里固定关闭。
|
||||
google_search = False
|
||||
|
||||
image_count = int(生图数量)
|
||||
if is_gpt_image_model(模型):
|
||||
@@ -740,6 +785,8 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
elif image_count not in UNIFIED_IMAGE_COUNTS:
|
||||
raise ValueError("生图数量仅支持:1、2、4、9")
|
||||
batch_enabled = _is_enabled(批量出图)
|
||||
# Accept the pre-rename labels so workflows saved with them still run.
|
||||
批量模式 = IMAGE_BATCH_MODE_ALIASES.get(批量模式, 批量模式)
|
||||
if 批量模式 not in IMAGE_BATCH_MODES:
|
||||
raise ValueError("批量模式无效")
|
||||
|
||||
@@ -874,13 +921,21 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
raise ValueError("GPT Image 分辨率无效")
|
||||
if 宽高比 not in GPT_IMAGE_ASPECT_RATIO_OPTIONS:
|
||||
raise ValueError("GPT Image 宽高比无效")
|
||||
complexity = resolve_gpt_image_complexity(模型, 复杂度)
|
||||
resolve_gpt_image_quality(模型, 质量)
|
||||
if 输出格式 not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS:
|
||||
raise ValueError("GPT Image 输出格式无效")
|
||||
输出格式 = resolve_gpt_image_output_format(模型, 输出格式)
|
||||
if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS:
|
||||
raise ValueError("GPT Image 背景参数无效")
|
||||
if 背景 == "transparent" and 输出格式 == "jpeg":
|
||||
if 背景 == "transparent" and 输出格式 not in {"png", "webp"}:
|
||||
raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式")
|
||||
validate_gpt_image_vector_output(
|
||||
模型,
|
||||
输出格式,
|
||||
has_images=bool(references) or bool(model_references),
|
||||
has_mask=_parse_mask_manifest(蒙版清单) is not None,
|
||||
)
|
||||
frame_count = resolve_gpt_image_frame_count(输出格式, 帧数)
|
||||
frame_duration_ms = resolve_gpt_image_frame_duration_ms(输出格式, 帧时长ms)
|
||||
images_with_references: list[tuple[Image.Image, list[Any]]] = []
|
||||
try:
|
||||
images_with_references = await _generate_gpt_images(
|
||||
@@ -897,6 +952,9 @@ class O1keyImageGenerator(io.ComfyNode):
|
||||
resize_mode=缩放图片,
|
||||
output_format=输出格式,
|
||||
background=背景,
|
||||
complexity=complexity,
|
||||
frame_count=frame_count,
|
||||
frame_duration_ms=frame_duration_ms,
|
||||
)
|
||||
except Exception as exc:
|
||||
message = format_o1key_image_error(exc)
|
||||
@@ -1009,18 +1067,27 @@ class O1keyImageSave(io.ComfyNode):
|
||||
save_location=settings.get("save_location", ""),
|
||||
naming_rule=settings.get("naming_rule", DEFAULT_SAVE_NAMING_RULE),
|
||||
)
|
||||
saved = ui.SavedImages([
|
||||
ui.SavedResult(
|
||||
item["filename"],
|
||||
item["subfolder"],
|
||||
(
|
||||
io.FolderType.temp
|
||||
if item.get("type") == "temp"
|
||||
else io.FolderType.output
|
||||
),
|
||||
)
|
||||
animated = any(
|
||||
str(item.get("filename") or "").lower().endswith(".gif")
|
||||
or item.get("media") == "gif"
|
||||
or item.get("animated") is True
|
||||
for item in descriptors
|
||||
])
|
||||
)
|
||||
saved = ui.SavedImages(
|
||||
[
|
||||
ui.SavedResult(
|
||||
item["filename"],
|
||||
item["subfolder"],
|
||||
(
|
||||
io.FolderType.temp
|
||||
if item.get("type") == "temp"
|
||||
else io.FolderType.output
|
||||
),
|
||||
)
|
||||
for item in descriptors
|
||||
],
|
||||
is_animated=animated,
|
||||
)
|
||||
return io.NodeOutput(images, ui=saved)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""o1key 保存 GIF 节点:写入 output,并带可播放动图预览。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from io import BytesIO
|
||||
|
||||
import folder_paths
|
||||
from comfy_api.latest import io, ui
|
||||
from comfy_api.latest._io import _UIOutput
|
||||
from PIL import Image
|
||||
|
||||
from ..utils.gpt_image_media import (
|
||||
animation_bytes_from_images,
|
||||
encode_gif_from_pil_images,
|
||||
is_gif_bytes,
|
||||
read_gif_bytes_from_path,
|
||||
resolve_gif_frame_duration_ms,
|
||||
write_bytes_atomic,
|
||||
)
|
||||
from ..utils.image_utils import pil_to_tensor, tensor_to_pil
|
||||
|
||||
|
||||
def _tensor_batch_to_pil(images) -> list:
|
||||
if images is None:
|
||||
return []
|
||||
batch = tensor_to_pil(images)
|
||||
if isinstance(batch, list):
|
||||
return batch
|
||||
return [batch]
|
||||
|
||||
|
||||
def _gif_size_hint(data: bytes) -> tuple[int, int]:
|
||||
try:
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
return int(image.size[0]), int(image.size[1])
|
||||
except Exception:
|
||||
return 0, 0
|
||||
|
||||
|
||||
def _pil_frames_from_gif_bytes(data: bytes) -> list:
|
||||
frames = []
|
||||
with Image.open(BytesIO(data)) as opened:
|
||||
try:
|
||||
n = int(getattr(opened, "n_frames", 1) or 1)
|
||||
except Exception:
|
||||
n = 1
|
||||
for index in range(n):
|
||||
try:
|
||||
opened.seek(index)
|
||||
except EOFError:
|
||||
break
|
||||
frames.append(opened.copy().convert("RGBA"))
|
||||
if not frames:
|
||||
frames = [opened.convert("RGBA")]
|
||||
return frames
|
||||
|
||||
|
||||
class SavedGifPreview(_UIOutput):
|
||||
"""GIF preview payload under a custom UI key.
|
||||
|
||||
Must NOT use ``ui.SavedImages`` / the ``images`` key. Comfy frontend
|
||||
``unsafeUpdatePreviews`` reads ``getNodeOutputs(node).images``, loads
|
||||
them via ``useNodeImage`` into ``node.imgs``, then
|
||||
``showCanvasImagePreview`` mounts ``$$canvas-image-preview``
|
||||
(IMAGE_PREVIEW) which paints a static frame + ``W x H`` under our
|
||||
DOM widget. A custom key is ignored by that path; ``gifPreview.js``
|
||||
mounts a single playable ``<img>`` from ``o1key_gif``.
|
||||
"""
|
||||
|
||||
UI_KEY = "o1key_gif"
|
||||
|
||||
def __init__(self, results: list[ui.SavedResult]):
|
||||
super().__init__()
|
||||
self.results = results
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {self.UI_KEY: self.results}
|
||||
|
||||
|
||||
def _preview_ui(file_name: str, subfolder: str) -> SavedGifPreview:
|
||||
return SavedGifPreview(
|
||||
[ui.SavedResult(file_name, subfolder, io.FolderType.output)],
|
||||
)
|
||||
|
||||
|
||||
class O1keySaveGIF(io.ComfyNode):
|
||||
"""将成品 GIF 保存到 ComfyUI output,并在节点上播放预览。
|
||||
|
||||
优先透传 gpt image「文件路径」指向的原始 GIF 字节(不重编码)。
|
||||
其次从 IMAGE 批帧上的原始 GIF 元数据透传(接「图像」也能避免重编码)。
|
||||
若只有普通 IMAGE 批帧,则按 fps / 帧时长ms 编码为 GIF。
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="O1keySaveGIF",
|
||||
display_name="保存 GIF",
|
||||
category="o1key/image",
|
||||
description=(
|
||||
"保存 GIF 到 output 目录,并显示可播放动图预览。"
|
||||
"推荐连接 gpt image 的「文件路径」;只接「图像」时也会尽量透传原始 GIF。"
|
||||
),
|
||||
is_output_node=True,
|
||||
inputs=[
|
||||
io.String.Input(
|
||||
"文件路径",
|
||||
default="",
|
||||
optional=True,
|
||||
tooltip="优先:连接 gpt image 的「文件路径」输出,原样复制 GIF 到 output。",
|
||||
),
|
||||
io.Image.Input(
|
||||
"图像",
|
||||
optional=True,
|
||||
tooltip=(
|
||||
"可选:IMAGE 批帧。若帧上带有原始 GIF 字节则仍透传;"
|
||||
"否则按 fps/帧时长编码。推荐优先接「文件路径」。"
|
||||
),
|
||||
),
|
||||
io.String.Input(
|
||||
"文件名前缀",
|
||||
default="ComfyUI",
|
||||
tooltip="保存到 output 时的文件名前缀(带计数器)。",
|
||||
),
|
||||
io.Float.Input(
|
||||
"fps",
|
||||
default=5.0,
|
||||
min=0.01,
|
||||
max=1000.0,
|
||||
step=0.01,
|
||||
tooltip="仅编码回退路径使用。默认 5 ≈ 200ms/帧。",
|
||||
),
|
||||
io.Int.Input(
|
||||
"帧时长ms",
|
||||
default=0,
|
||||
min=0,
|
||||
max=2000,
|
||||
step=10,
|
||||
tooltip="仅编码回退路径使用。>0 时覆盖 fps(单位毫秒);0 表示按 fps 计算。",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.String.Output("FILE", display_name="文件路径"),
|
||||
io.Image.Output("IMAGE", display_name="图像"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(
|
||||
cls,
|
||||
文件路径: str = "",
|
||||
图像=None,
|
||||
文件名前缀: str = "ComfyUI",
|
||||
fps: float = 5.0,
|
||||
帧时长ms: int = 0,
|
||||
) -> io.NodeOutput:
|
||||
source_path = str(文件路径 or "").strip().strip('"').strip("'")
|
||||
gif_bytes = read_gif_bytes_from_path(source_path)
|
||||
mode = "原样透传" if gif_bytes is not None else None
|
||||
pil_frames = _tensor_batch_to_pil(图像) if 图像 is not None else []
|
||||
|
||||
if gif_bytes is None and pil_frames:
|
||||
embedded = animation_bytes_from_images(pil_frames)
|
||||
if embedded is not None:
|
||||
gif_bytes = embedded
|
||||
mode = "元数据透传"
|
||||
|
||||
if gif_bytes is None:
|
||||
if source_path and os.path.isfile(source_path) and not pil_frames:
|
||||
raise ValueError(f"文件不是 GIF,且未提供图像帧: {source_path}")
|
||||
if not pil_frames:
|
||||
if source_path:
|
||||
raise ValueError(f"GIF 文件不存在: {source_path}")
|
||||
raise ValueError("请连接「文件路径」(推荐)或「图像」批帧")
|
||||
duration_ms = resolve_gif_frame_duration_ms(fps=fps, frame_duration_ms=帧时长ms)
|
||||
gif_bytes = encode_gif_from_pil_images(pil_frames, duration_ms=duration_ms)
|
||||
mode = "帧编码"
|
||||
if source_path:
|
||||
print(
|
||||
"[o1key 保存 GIF] 提示: 已接「图像」且走帧编码;"
|
||||
"若同时有 gpt image「文件路径」,改接文件路径可避免重编码变大。"
|
||||
)
|
||||
|
||||
if not is_gif_bytes(gif_bytes):
|
||||
raise RuntimeError("内部错误:待保存数据不是 GIF")
|
||||
|
||||
width, height = _gif_size_hint(gif_bytes)
|
||||
output_dir = folder_paths.get_output_directory()
|
||||
full_output_folder, filename, counter, subfolder, _prefix = folder_paths.get_save_image_path(
|
||||
文件名前缀 or "ComfyUI",
|
||||
output_dir,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
os.makedirs(full_output_folder, exist_ok=True)
|
||||
while True:
|
||||
file_name = f"{filename}_{counter:05}_.gif"
|
||||
target = os.path.join(full_output_folder, file_name)
|
||||
if not os.path.exists(target):
|
||||
break
|
||||
counter += 1
|
||||
|
||||
write_bytes_atomic(target, gif_bytes)
|
||||
size_kb = os.path.getsize(target) / 1024.0
|
||||
print(f"[o1key 保存 GIF] {mode}: {target} ({size_kb:.0f}KB)")
|
||||
|
||||
preview = _preview_ui(file_name, subfolder)
|
||||
|
||||
if 图像 is not None:
|
||||
image_out = 图像
|
||||
elif pil_frames:
|
||||
image_out = pil_to_tensor(pil_frames)
|
||||
else:
|
||||
image_out = pil_to_tensor(_pil_frames_from_gif_bytes(gif_bytes))
|
||||
|
||||
return io.NodeOutput(target, image_out, ui=preview)
|
||||
|
||||
|
||||
__all__ = ["O1keySaveGIF", "SavedGifPreview"]
|
||||
Reference in New Issue
Block a user