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:
@@ -3,6 +3,8 @@
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from io import BytesIO
|
||||
from types import ModuleType
|
||||
@@ -64,15 +66,16 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
|
||||
|
||||
self.assertEqual(inputs["缩放图片"].options, ["不缩放", "智能缩放"])
|
||||
self.assertEqual(inputs["缩放图片"].default, "智能缩放")
|
||||
self.assertEqual(inputs["模型"].default, "gpt-image-2.5-sunburst")
|
||||
self.assertEqual(inputs["模型"].default, "gpt-image-2.6-sunburst")
|
||||
self.assertNotIn("色彩纠正", inputs)
|
||||
self.assertEqual(inputs["背景"].options, ["auto", "transparent", "opaque"])
|
||||
self.assertNotIn("内容审查强度", inputs)
|
||||
self.assertEqual(
|
||||
[item.id for item in schema.inputs],
|
||||
[
|
||||
"prompt", "模型", "模型线路", "分辨率", "生图数量", "质量",
|
||||
"prompt", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量",
|
||||
"输出格式", "背景", "遮罩", "参考图组", "缩放图片", "seed",
|
||||
"帧数", "帧时长ms",
|
||||
],
|
||||
)
|
||||
self.assertEqual(
|
||||
@@ -106,7 +109,7 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
|
||||
self.assert_combo_values_are_strings(schema)
|
||||
inputs = {item.id: item for item in schema.inputs}
|
||||
|
||||
self.assertEqual(inputs["模型"].default, "gpt-image-2.5-sunburst")
|
||||
self.assertEqual(inputs["模型"].default, "gpt-image-2.6-sunburst")
|
||||
self.assertEqual(inputs["缩放图片"].default, "智能缩放")
|
||||
self.assertEqual(inputs["质量"].options, ["高", "中", "低", "自动", "超高", "最高"])
|
||||
self.assertNotIn("色彩纠正", inputs)
|
||||
@@ -114,9 +117,10 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
|
||||
self.assertEqual(
|
||||
[item.id for item in schema.inputs],
|
||||
[
|
||||
"prompt", "模型", "模型线路", "分辨率", "生图数量", "质量",
|
||||
"prompt", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量",
|
||||
"图片路径数量", "遮罩", "参考图组", "图片输出格式",
|
||||
"背景", "图片保存命名规则", "图片保存路径", "缩放图片", "seed",
|
||||
"帧数", "帧时长ms",
|
||||
],
|
||||
)
|
||||
self.assertNotIn("并发数", inputs)
|
||||
@@ -139,6 +143,114 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
|
||||
):
|
||||
self.assertFalse(inputs[input_name].advanced, input_name)
|
||||
|
||||
class GPTImage26Tests(unittest.IsolatedAsyncioTestCase):
|
||||
def test_schema_and_all_six_routes_preserve_existing_defaults(self):
|
||||
for node in (O1keyGPTImage, O1keyGPTImageBatch):
|
||||
inputs = {item.id: item for item in node.define_schema().inputs}
|
||||
self.assertEqual(inputs["模型"].default, "gpt-image-2.6-sunburst")
|
||||
self.assertEqual(list(inputs)[3], "复杂度")
|
||||
self.assertEqual(list(inputs)[-2], "帧数")
|
||||
self.assertEqual(list(inputs)[-1], "帧时长ms")
|
||||
self.assertEqual(inputs["复杂度"].default, "高")
|
||||
self.assertEqual(inputs["复杂度"].options, ["高", "中", "低"])
|
||||
self.assertEqual(inputs["帧数"].default, 9)
|
||||
self.assertEqual(inputs["帧时长ms"].default, 200)
|
||||
for variant in ("sunburst", "flare"):
|
||||
model = f"gpt-image-2.6-{variant}"
|
||||
self.assertIn(model, inputs["模型"].options)
|
||||
self.assertEqual(resolve_gpt_image_quality(model, "超高"), "xhigh")
|
||||
self.assertEqual(resolve_gpt_image_quality(model, "最高"), "max")
|
||||
for route, suffix in (("畅速", "-sp"), ("直连", "-sd"), ("专线", "")):
|
||||
with self.subTest(node=node.__name__, model=model, route=route):
|
||||
self.assertEqual(resolve_gpt_image_model(model, route), model + suffix)
|
||||
|
||||
def test_payload_complexity_is_validated_for_every_26_route_only(self):
|
||||
client = object.__new__(GptImageClient)
|
||||
for variant in ("sunburst", "flare"):
|
||||
for suffix in ("-sp", "-sd", ""):
|
||||
model = f"gpt-image-2.6-{variant}{suffix}"
|
||||
for value in (None, "low", "medium", "high"):
|
||||
with self.subTest(model=model, complexity=value):
|
||||
body = client._build_async_generate_body(
|
||||
"test", model, "max", None, 1, complexity=value,
|
||||
)
|
||||
self.assertEqual(body["complexity"], value or "high")
|
||||
self.assertEqual(body["model"], model)
|
||||
self.assertEqual(body["n"], 1)
|
||||
self.assertNotIn("size", body)
|
||||
self.assertNotIn("input_fidelity", body)
|
||||
with self.assertRaisesRegex(ValueError, "复杂度"):
|
||||
client._build_async_generate_body("test", model, "high", None, 1, complexity="invalid")
|
||||
for model in ("gpt-image-2-c-sp", "gpt-image-2.5-sunburst-sp", "gpt-image-2.5-flare"):
|
||||
body = client._build_async_generate_body("test", model, "high", None, 1, complexity="low")
|
||||
self.assertNotIn("complexity", body)
|
||||
for output_format in ("svg", "gif"):
|
||||
body = client._build_async_generate_body(
|
||||
"test", "gpt-image-2.6-flare", "high", None, 1, output_format=output_format,
|
||||
)
|
||||
self.assertEqual(body["output_format"], output_format)
|
||||
if output_format == "gif":
|
||||
self.assertEqual(body["frame_count"], 9)
|
||||
self.assertEqual(body["frame_duration_ms"], 200)
|
||||
else:
|
||||
self.assertNotIn("frame_count", body)
|
||||
self.assertNotIn("frame_duration_ms", body)
|
||||
with self.assertRaisesRegex(ValueError, "仅支持 GPT Image 2.6"):
|
||||
client._build_async_generate_body(
|
||||
"test", "gpt-image-2.5-flare", "high", None, 1, output_format=output_format,
|
||||
)
|
||||
|
||||
async def test_single_and_parallel_client_requests_keep_complexity_and_n_one(self):
|
||||
client = object.__new__(GptImageClient)
|
||||
generated = Image.new("RGB", (6, 4), "green")
|
||||
with patch.object(client, "_generate_image_task_async", new=AsyncMock(return_value=[generated])) as generate:
|
||||
for count in (1, 3):
|
||||
generate.reset_mock()
|
||||
images = await client.generate_image_async(
|
||||
prompt="test", model="gpt-image-2.6-flare-sd", quality="xhigh",
|
||||
size=None, n=count, seed=0, complexity="medium", log_request_start=False,
|
||||
)
|
||||
self.assertEqual(len(images), count)
|
||||
self.assertEqual(generate.await_count, count)
|
||||
for call in generate.await_args_list:
|
||||
self.assertEqual(call.kwargs["complexity"], "medium")
|
||||
self.assertEqual(call.kwargs["n"], 1)
|
||||
|
||||
def test_standalone_sync_and_batch_prompt_paths_forward_complexity(self):
|
||||
calls = []
|
||||
class FakeClient:
|
||||
def generate_image_async_sync(self, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return [Image.new("RGB", (6, 4), "green")]
|
||||
_pil_list_to_tensor = staticmethod(GptImageClient._pil_list_to_tensor)
|
||||
with patch("comfyui_o1key.nodes.gpt_image.GptImageClient", FakeClient), patch(
|
||||
"comfyui_o1key.nodes.gpt_image.get_base_url_by_route", return_value="https://example.invalid",
|
||||
), patch("builtins.print"):
|
||||
for prompt in ("test", "first\n---\nsecond"):
|
||||
O1keyGPTImage.generate(
|
||||
prompt=prompt, 模型="gpt-image-2.6-sunburst", 模型线路="直连",
|
||||
质量="最高", 复杂度="低",
|
||||
)
|
||||
self.assertEqual(len(calls), 3)
|
||||
self.assertTrue(all(call["model"] == "gpt-image-2.6-sunburst-sd" for call in calls))
|
||||
self.assertTrue(all(call["quality"] == "max" for call in calls))
|
||||
self.assertTrue(all(call["complexity"] == "low" for call in calls))
|
||||
|
||||
async def test_batch_orchestrator_forwards_complexity(self):
|
||||
calls = []
|
||||
class FakeClient:
|
||||
async def generate_image_async(self, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return [Image.new("RGB", (6, 4), "green")]
|
||||
with patch.object(O1keyGPTImageBatch, "_save_images", return_value=["output.png"]), patch("builtins.print"):
|
||||
results = await O1keyGPTImageBatch._process_async(
|
||||
FakeClient(), [(0, (), "test")], "gpt-image-2.6-flare-sp", "xhigh", "auto", 1, 0,
|
||||
None, "png", "auto", "智能缩放", "output", "自然数字", None, "medium",
|
||||
)
|
||||
self.assertTrue(results[0]["success"])
|
||||
self.assertEqual(calls[0]["complexity"], "medium")
|
||||
|
||||
|
||||
class GPTImageNodeExecutionTests(unittest.TestCase):
|
||||
def test_single_node_forwards_request_controls_without_postprocess(self):
|
||||
calls = []
|
||||
@@ -174,7 +286,7 @@ class GPTImageNodeExecutionTests(unittest.TestCase):
|
||||
|
||||
self.assertIs(result[0], generated)
|
||||
self.assertEqual(len(calls), 1)
|
||||
self.assertEqual(calls[0]["model"], "gpt-image-2.5-sunburst-sp")
|
||||
self.assertEqual(calls[0]["model"], "gpt-image-2.6-sunburst-sp")
|
||||
self.assertEqual(calls[0]["resize_mode"], "智能缩放")
|
||||
self.assertEqual(calls[0]["background"], "transparent")
|
||||
self.assertNotIn("moderation", calls[0])
|
||||
@@ -326,19 +438,145 @@ class GPTImageDownloadRetryTests(unittest.IsolatedAsyncioTestCase):
|
||||
),
|
||||
patch("builtins.print") as print_mock,
|
||||
):
|
||||
image, byte_count, _elapsed = await client._download_image_with_response_retry(
|
||||
images, byte_count, _elapsed = await client._download_image_with_response_retry(
|
||||
session,
|
||||
signed_url,
|
||||
"第 1 张图片",
|
||||
)
|
||||
|
||||
self.assertEqual(session.calls, 2)
|
||||
self.assertEqual(image.size, (3, 2))
|
||||
self.assertEqual(images[0].size, (3, 2))
|
||||
self.assertEqual(byte_count, len(image_bytes))
|
||||
rendered = " ".join(str(value) for call in print_mock.call_args_list for value in call.args)
|
||||
self.assertNotIn(signed_url, rendered)
|
||||
self.assertNotIn("signature=secret", rendered)
|
||||
|
||||
|
||||
class GPTImage26SvgGifTests(unittest.TestCase):
|
||||
def test_gif_frame_bounds_and_rounding(self):
|
||||
from comfyui_o1key.utils.o1key_image_catalog import (
|
||||
resolve_gpt_image_frame_count,
|
||||
resolve_gpt_image_frame_duration_ms,
|
||||
)
|
||||
self.assertEqual(resolve_gpt_image_frame_count("gif", None), 9)
|
||||
self.assertEqual(resolve_gpt_image_frame_duration_ms("gif", 205), 200)
|
||||
with self.assertRaisesRegex(ValueError, "帧数"):
|
||||
resolve_gpt_image_frame_count("gif", 1)
|
||||
with self.assertRaisesRegex(ValueError, "帧时长"):
|
||||
resolve_gpt_image_frame_duration_ms("gif", 10)
|
||||
|
||||
def test_svg_gif_reject_edit_inputs(self):
|
||||
import torch
|
||||
client = object.__new__(GptImageClient)
|
||||
fake = torch.zeros((1, 8, 8, 3))
|
||||
for output_format in ("svg", "gif"):
|
||||
with self.assertRaisesRegex(ValueError, "纯文生图"):
|
||||
client._build_async_generate_body(
|
||||
"test", "gpt-image-2.6-sunburst", "high", None, 1,
|
||||
image_list=[fake], output_format=output_format,
|
||||
)
|
||||
|
||||
def test_materialize_gif_expands_frames_and_keeps_bytes(self):
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
from comfyui_o1key.utils.gpt_image_media import (
|
||||
animation_bytes_from_images,
|
||||
materialize_result_images,
|
||||
)
|
||||
buf = BytesIO()
|
||||
frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue", "green")]
|
||||
frames[0].save(buf, format="GIF", save_all=True, append_images=frames[1:], duration=100, loop=0)
|
||||
data = buf.getvalue()
|
||||
images = materialize_result_images(data, requested_format="gif")
|
||||
self.assertEqual(len(images), 3)
|
||||
self.assertEqual(animation_bytes_from_images(images), data)
|
||||
|
||||
def test_gif_preview_ui_uses_custom_key_not_images(self):
|
||||
# Save GIF must NOT emit SavedImages/images — core would mount
|
||||
# $$canvas-image-preview (static frame + "W x H"). Custom o1key_gif
|
||||
# key is read only by web/js/gifPreview.js.
|
||||
from comfy_api.latest import io, ui
|
||||
from comfyui_o1key.nodes.save_gif import SavedGifPreview
|
||||
preview = SavedGifPreview(
|
||||
[ui.SavedResult("demo.gif", "", io.FolderType.output)],
|
||||
)
|
||||
data = preview.as_dict()
|
||||
self.assertNotIn("images", data)
|
||||
self.assertNotIn("animated", data)
|
||||
self.assertIn(SavedGifPreview.UI_KEY, data)
|
||||
self.assertEqual(data[SavedGifPreview.UI_KEY][0]["type"], "output")
|
||||
self.assertTrue(str(data[SavedGifPreview.UI_KEY][0]["filename"]).endswith(".gif"))
|
||||
|
||||
def test_generate_gif_writes_temp_file_without_preview(self):
|
||||
from io import BytesIO
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
from PIL import Image
|
||||
import torch
|
||||
from comfyui_o1key.nodes.gpt_image import O1keyGPTImage
|
||||
|
||||
buf = BytesIO()
|
||||
frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue")]
|
||||
frames[0].save(buf, format="GIF", save_all=True, append_images=frames[1:], duration=100, loop=0)
|
||||
gif_bytes = buf.getvalue()
|
||||
materialized = []
|
||||
from comfyui_o1key.utils.gpt_image_media import materialize_result_images
|
||||
materialized.extend(materialize_result_images(gif_bytes, requested_format="gif"))
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self):
|
||||
self.base_url = ""
|
||||
self.response_log_enabled = True
|
||||
self.poll_log_enabled = True
|
||||
|
||||
def generate_image_async_sync(self, **kwargs):
|
||||
return list(materialized)
|
||||
|
||||
@staticmethod
|
||||
def _pil_list_to_tensor(images):
|
||||
return torch.zeros((len(images), 4, 6, 3), dtype=torch.float32)
|
||||
|
||||
def query_balance_sync(self):
|
||||
return {}
|
||||
|
||||
def format_balance_info(self, _data):
|
||||
return ""
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
folder = SimpleNamespace(
|
||||
get_temp_directory=lambda: temp_dir,
|
||||
get_output_directory=lambda: temp_dir,
|
||||
)
|
||||
with (
|
||||
patch("comfyui_o1key.nodes.gpt_image.GptImageClient", FakeClient),
|
||||
patch(
|
||||
"comfyui_o1key.nodes.gpt_image.get_base_url_by_route",
|
||||
return_value="https://example.invalid",
|
||||
),
|
||||
patch("comfyui_o1key.nodes.gpt_image._FOLDER_PATHS_AVAILABLE", True),
|
||||
patch("comfyui_o1key.nodes.gpt_image.folder_paths", folder),
|
||||
):
|
||||
tensor, file_path, preview = O1keyGPTImage.generate(
|
||||
prompt="gif demo",
|
||||
模型="gpt-image-2.6-flare",
|
||||
输出格式="gif",
|
||||
帧数=2,
|
||||
帧时长ms=100,
|
||||
)
|
||||
self.assertTrue(str(file_path).lower().endswith(".gif"))
|
||||
self.assertTrue(Path(file_path).is_file())
|
||||
self.assertEqual(Path(file_path).read_bytes(), gif_bytes)
|
||||
# gpt image: no node UI preview for GIF (only file path / temp bytes)
|
||||
self.assertIsNone(preview)
|
||||
self.assertEqual(tuple(tensor.shape)[0], 2)
|
||||
|
||||
def test_materialize_svg_returns_preview_with_original_bytes(self):
|
||||
from comfyui_o1key.utils.gpt_image_media import materialize_result_images, svg_bytes_from_image
|
||||
svg = b"""<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" fill="red"/></svg>"""
|
||||
images = materialize_result_images(svg, requested_format="svg")
|
||||
self.assertEqual(len(images), 1)
|
||||
self.assertEqual(svg_bytes_from_image(images[0]), svg)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user