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:
@@ -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