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

Ship o1key MJ图片生成 with content/style refs and prompt flags, save-GIF with preview, Kling 4.0 helpers, plus GPT/unified image node polish and docs.
This commit is contained in:
Jony
2026-11-09 09:11:12 +08:00
parent ff1cf830fa
commit a181cc1768
40 changed files with 6711 additions and 675 deletions
+124
View File
@@ -0,0 +1,124 @@
/**
* Regression: GPT Image widgets_values must survive reload after 2.6 fields /
* 复杂度 reorder (above 分辨率) and Chinese labels.
* Legacy migrate rules look at the array tail; seed's control_after_generate
* made "补齐缩放和背景" mis-fire and insert 智能缩放/auto before 复杂度.
*/
import assert from "node:assert/strict";
import test from "node:test";
const CONTROL = new Set(["fixed", "increment", "decrement", "randomize"]);
const RESIZE = new Set(["不缩放", "智能缩放"]);
const BG = new Set(["auto", "transparent", "opaque"]);
const MOD = new Set(["自动", "低"]);
const CX = new Set(["low", "medium", "high", "低", "中", "高"]);
const CX_TO_LABEL = Object.freeze({
low: "低", medium: "中", high: "高", 低: "低", 中: "中", 高: "高",
});
function normalizeComplexity(value) {
if (value == null) return "高";
return CX_TO_LABEL[value] ?? CX_TO_LABEL[String(value).toLowerCase()] ?? "高";
}
function placeComplexity(wv, complexity) {
if (CX.has(wv[3])) {
wv[3] = normalizeComplexity(wv[3]);
return;
}
wv.splice(3, 0, normalizeComplexity(complexity === undefined ? "高" : complexity));
}
/** Mirrors peel/repair/restore + O1keyGPTImage tail rules in migrateWorkflow.js */
function migrateGptImageWidgets(values) {
const wv = [...values];
let frameDuration;
let frameCount;
let complexity;
let controlAfterGenerate;
const maybeDuration = wv.at(-1);
const maybeCount = wv.at(-2);
const maybeComplexity = wv.at(-3);
if (
Number.isInteger(maybeDuration)
&& Number.isInteger(maybeCount)
&& CX.has(maybeComplexity)
) {
frameDuration = wv.pop();
frameCount = wv.pop();
complexity = wv.pop();
} else if (Number.isInteger(maybeDuration) && Number.isInteger(maybeCount)) {
frameDuration = wv.pop();
frameCount = wv.pop();
} else if (["low", "medium", "high"].includes(String(wv.at(-1)).toLowerCase())) {
complexity = wv.pop();
}
if (CONTROL.has(wv.at(-3)) && RESIZE.has(wv.at(-2)) && BG.has(wv.at(-1))) {
wv.splice(wv.length - 2, 2);
}
if (CONTROL.has(wv.at(-1))) {
controlAfterGenerate = wv.pop();
}
const alreadyHasTail = (
(Number.isInteger(wv.at(-3)) && RESIZE.has(wv.at(-2)) && BG.has(wv.at(-1)))
|| (RESIZE.has(wv.at(-3)) && BG.has(wv.at(-2)) && MOD.has(wv.at(-1)))
|| (BG.has(wv.at(-3)) && RESIZE.has(wv.at(-2)) && Number.isInteger(wv.at(-1)))
);
if (!alreadyHasTail) wv.push("智能缩放", "auto", "自动");
if (RESIZE.has(wv.at(-3)) && BG.has(wv.at(-2)) && MOD.has(wv.at(-1))) wv.pop();
if (Number.isInteger(wv.at(-3)) && RESIZE.has(wv.at(-2)) && BG.has(wv.at(-1))) {
const start = wv.length - 3;
const [seed, resize, background] = wv.slice(start);
wv.splice(start, 3, background, resize, seed);
}
if (controlAfterGenerate !== undefined) wv.push(controlAfterGenerate);
placeComplexity(wv, complexity);
if (frameCount !== undefined) wv.push(frameCount);
if (frameDuration !== undefined) wv.push(frameDuration);
return wv;
}
const healthy26 = [
"一个在跳舞的美女", "gpt-image-2.6-sunburst", "专线", "高", "智能", 1, "自动", "gif",
"auto", "智能缩放", 123, "randomize", 9, 200,
];
const old25 = [
"prompt", "gpt-image-2.5-sunburst", "畅速", "高", "智能", 1, "自动", "png",
"auto", "智能缩放", 123, "randomize",
];
const old26TailComplexity = [
"一个在跳舞的美女", "gpt-image-2.6-sunburst", "专线", "智能", 1, "自动", "gif",
"auto", "智能缩放", 123, "randomize", "high", 9, 200,
];
const scrambled = [
"一个在跳舞的美女", "gpt-image-2.6-sunburst", "专线", "智能", 1, "自动", "gif",
"auto", "智能缩放", 123, "randomize", "智能缩放", "auto", "high", 9, 200,
];
test("keeps healthy 2.6 gif widgets_values with mid-list 复杂度", () => {
assert.deepEqual(migrateGptImageWidgets(healthy26), healthy26);
});
test("inserts default 复杂度 for pre-2.6 widgets_values", () => {
const input = [
"prompt", "gpt-image-2.5-sunburst", "畅速", "智能", 1, "自动", "png",
"auto", "智能缩放", 123, "randomize",
];
assert.deepEqual(migrateGptImageWidgets(input), old25);
});
test("moves old tail 复杂度 above 分辨率 and localizes label", () => {
assert.deepEqual(migrateGptImageWidgets(old26TailComplexity), healthy26);
});
test("repairs scrambled 复杂度/帧数/帧时长ms shift", () => {
assert.deepEqual(migrateGptImageWidgets(scrambled), healthy26);
});
test("repair is idempotent", () => {
assert.deepEqual(migrateGptImageWidgets(migrateGptImageWidgets(scrambled)), healthy26);
});
+245 -7
View File
@@ -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()
+55
View File
@@ -108,3 +108,58 @@ assert.equal(backgroundWidget.options.getOptionLabel("transparent"), "透明");
assert.equal(backgroundWidget.options.getOptionLabel("opaque"), "不透明");
assert.equal(backgroundWidget.value, "transparent");
assert.deepEqual(Array.from(backgroundWidget.options.values), ["auto", "transparent", "opaque"]);
for (const nodeType of ["O1keyGPTImage", "O1keyGPTImageBatch"]) {
const node = makeNode("gpt-image-2.6-sunburst", "最高", nodeType);
const size = () => [150, 20];
const complexity = { name: "复杂度", value: "中", options: {}, computeSize: size };
node.widgets.push(complexity);
extension.nodeCreated(node);
const callback = node.modelWidget.callback;
extension.nodeCreated(node);
assert.equal(node.modelWidget.callback, callback, "Extension binding remains idempotent");
assert.equal(node.qualityWidget.value, "最高");
assert.equal(complexity.hidden, false);
assert.equal(complexity.computeSize, size);
node.modelWidget.value = "gpt-image-2.5-flare";
node.modelWidget.callback();
assert.equal(complexity.hidden, true);
assert.equal(complexity.options.hidden, true);
assert.equal(complexity.value, "中");
assert.deepEqual(Array.from(complexity.computeSize()), [0, -4]);
node.modelWidget.value = "gpt-image-2.6-flare";
node.onConfigure({});
extension.loadedGraphNode(node);
assert.equal(complexity.hidden, false);
assert.equal(complexity.computeSize, size);
assert.equal(complexity.value, "中");
assert.equal(node.qualityWidget.value, "最高");
}
for (const nodeType of ["O1keyGPTImage", "O1keyGPTImageBatch"]) {
const node = makeNode("gpt-image-2.6-sunburst", "最高", nodeType);
const size = () => [150, 20];
const complexity = { name: "复杂度", value: "中", options: {}, computeSize: size };
const formatName = nodeType === "O1keyGPTImageBatch" ? "图片输出格式" : "输出格式";
const format = {
name: formatName,
value: nodeType === "O1keyGPTImageBatch" ? "PNG" : "png",
options: { values: [] },
callback() {},
};
const frameCount = { name: "帧数", value: 9, options: {}, computeSize: size };
const frameDuration = { name: "帧时长ms", value: 200, options: {}, computeSize: size };
node.widgets.push(complexity, format, frameCount, frameDuration);
extension.nodeCreated(node);
assert.equal(complexity.hidden, false);
assert.ok(format.options.values.includes(nodeType === "O1keyGPTImageBatch" ? "GIF" : "gif"));
assert.equal(frameCount.hidden, true);
format.value = nodeType === "O1keyGPTImageBatch" ? "GIF" : "gif";
format.callback();
assert.equal(frameCount.hidden, false);
assert.equal(frameDuration.hidden, false);
node.modelWidget.value = "gpt-image-2";
node.modelWidget.callback();
assert.equal(format.options.values.includes(nodeType === "O1keyGPTImageBatch" ? "GIF" : "gif"), false);
assert.equal(frameCount.hidden, true);
}
+117
View File
@@ -0,0 +1,117 @@
"""Offline regression tests for the Kling 4.0 request contract."""
import sys
import types
import unittest
from pathlib import Path
PLUGIN_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PLUGIN_ROOT.parent))
package = types.ModuleType("comfyui_o1key")
package.__path__ = [str(PLUGIN_ROOT)]
sys.modules.setdefault("comfyui_o1key", package)
clients = types.ModuleType("comfyui_o1key.clients")
clients.__path__ = [str(PLUGIN_ROOT / "clients")]
sys.modules.setdefault("comfyui_o1key.clients", clients)
utils = types.ModuleType("comfyui_o1key.utils")
utils.__path__ = [str(PLUGIN_ROOT / "utils")]
sys.modules.setdefault("comfyui_o1key.utils", utils)
from comfyui_o1key.clients.kling_video_client import ( # noqa: E402
build_kling_v4_body,
endpoint_for,
)
from comfyui_o1key.utils.video_task import extract_video_url # noqa: E402
class KlingV4RequestTests(unittest.TestCase):
def test_text_mode_uses_resolution_mode_and_adaptive_ratio(self):
body = build_kling_v4_body(
generation_mode="文生视频",
prompt="A slow dolly shot through a rainy market",
duration=30,
resolution="1080p",
aspect_ratio="智能",
)
self.assertEqual(body["model_name"], "kling-v4")
self.assertEqual(body["duration"], 30)
self.assertEqual(body["mode"], "pro")
self.assertEqual(body["aspect_ratio"], "adaptive")
self.assertNotIn("metadata", body)
self.assertEqual(endpoint_for("文生视频")[0], "/kling/v1/videos/text2video")
def test_keyframes_keep_frame_order_and_omit_aspect_ratio(self):
body = build_kling_v4_body(
generation_mode="关键帧",
prompt="Move continuously between the keyframes",
first_frame="https://cdn.example.invalid/first.png",
middle_frames=[
"https://cdn.example.invalid/middle-1.png",
"https://cdn.example.invalid/middle-2.png",
],
last_frame="https://cdn.example.invalid/last.png",
)
self.assertEqual(body["metadata"], {
"first_frame": "https://cdn.example.invalid/first.png",
"middle_frames": [
"https://cdn.example.invalid/middle-1.png",
"https://cdn.example.invalid/middle-2.png",
],
"last_frame": "https://cdn.example.invalid/last.png",
})
self.assertNotIn("aspect_ratio", body)
self.assertEqual(endpoint_for("关键帧")[0], "/kling/v1/videos/image2video")
def test_omni_mode_uses_reference_metadata_and_caps_inputs(self):
body = build_kling_v4_body(
generation_mode="全能参考",
prompt="Use the character from @Image1 and the movement from @Video1",
reference_images=["https://cdn.example.invalid/character.png"],
reference_videos=["https://cdn.example.invalid/motion.mp4"],
keep_original_sound=True,
aspect_ratio="21:9",
)
self.assertEqual(body["metadata"]["refer_images"], [
"https://cdn.example.invalid/character.png",
])
self.assertEqual(body["metadata"]["videos"], [
"https://cdn.example.invalid/motion.mp4",
])
self.assertTrue(body["keep_original_sound"])
self.assertEqual(body["aspect_ratio"], "21:9")
self.assertEqual(endpoint_for("全能参考")[0], "/kling/v1/videos/omni-video")
def test_modes_reject_invalid_combinations_before_upload(self):
with self.assertRaisesRegex(ValueError, "关键帧模式必须提供"):
build_kling_v4_body(generation_mode="关键帧", prompt="move")
with self.assertRaisesRegex(ValueError, "不能连接图片或视频"):
build_kling_v4_body(
generation_mode="文生视频",
prompt="move",
first_frame="https://cdn.example.invalid/frame.png",
)
with self.assertRaisesRegex(ValueError, "至少需要一张参考图"):
build_kling_v4_body(generation_mode="全能参考", prompt="move")
def test_v4_output_envelope_is_read_by_shared_parser(self):
self.assertEqual(
extract_video_url({
"data": {
"status": "succeeded",
"output": {
"media": [{"type": "video", "url": "https://cdn.example.invalid/result.mp4"}],
},
},
}),
"https://cdn.example.invalid/result.mp4",
)
if __name__ == "__main__":
unittest.main()
+416
View File
@@ -0,0 +1,416 @@
# -*- coding: utf-8 -*-
"""Offline tests for Midjourney prompt assembly and MJ client body/mocks."""
from __future__ import annotations
import asyncio
import os
import sys
import unittest
from types import ModuleType
from unittest.mock import AsyncMock, patch
from PIL import Image
PLUGIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CUSTOM_NODES_DIR = os.path.dirname(PLUGIN_DIR)
COMFY_ROOT = os.path.dirname(CUSTOM_NODES_DIR)
for child in ("nodes", "utils", "clients"):
package = ModuleType(f"comfyui_o1key.{child}")
package.__path__ = [os.path.join(PLUGIN_DIR, child)]
sys.modules[package.__name__] = package
plugin_package = ModuleType("comfyui_o1key")
plugin_package.__path__ = [PLUGIN_DIR]
sys.modules[plugin_package.__name__] = plugin_package
model_management = ModuleType("comfy.model_management")
model_management.processing_interrupted = lambda: False
model_management.InterruptProcessingException = RuntimeError
sys.modules[model_management.__name__] = model_management
sys.path.insert(0, COMFY_ROOT)
sys.path.insert(0, CUSTOM_NODES_DIR)
from comfyui_o1key.utils.mj_prompt import ( # noqa: E402
MJ_MODEL_ID,
build_mj_prompt,
strip_controlled_mj_flags,
)
from comfyui_o1key.clients import mj_image_client as CLIENT # noqa: E402
class MjPromptTests(unittest.TestCase):
def test_strips_duplicate_user_flags_and_appends_stable_order(self):
prompt = build_mj_prompt(
"a cat --ar 9:16 --q 1 --hd --iw 3 --raw --s 999 --c 50 --seed 7 "
"--weird 10 --tile --exp 5 --draft --no cars --sref https://x/a.png --sw 50",
aspect_ratio="16:9",
quality=2,
hd=True,
image_weight=1.5,
raw=True,
stylize=250,
chaos=12,
seed=42,
has_reference_image=True,
weird=100,
tile=True,
exp=20,
draft=True,
no_text="dogs",
style_ref_urls=["https://upload.example/style.png"],
style_weight=200,
)
self.assertEqual(
prompt,
"a cat --no dogs --ar 16:9 --q 2 --hd --iw 1.5 "
"--sref https://upload.example/style.png --sw 200 "
"--raw --s 250 --c 12 --weird 100 --tile --exp 20 --draft --seed 42",
)
def test_omits_optional_flags_when_disabled(self):
prompt = build_mj_prompt(
" sunset harbor ",
aspect_ratio="1:1",
quality=2,
hd=False,
raw=False,
stylize=250,
chaos=0,
seed=-1,
has_reference_image=False,
weird=0,
tile=False,
exp=0,
draft=False,
no_text="",
)
self.assertEqual(prompt, "sunset harbor --ar 1:1 --q 2 --s 250")
self.assertNotIn("--hd", prompt)
self.assertNotIn("--iw", prompt)
self.assertNotIn("--raw", prompt)
self.assertNotIn("--c ", prompt)
self.assertNotIn("--seed", prompt)
self.assertNotIn("--weird", prompt)
self.assertNotIn("--tile", prompt)
self.assertNotIn("--exp", prompt)
self.assertNotIn("--draft", prompt)
self.assertNotIn("--no", prompt)
self.assertNotIn("--sref", prompt)
self.assertNotIn("--sw", prompt)
def test_conditional_weird_exp_tile_draft_no_sw(self):
base = build_mj_prompt("scene", weird=0, exp=0, tile=False, draft=False, no_text=" ")
self.assertNotIn("--weird", base)
self.assertNotIn("--exp", base)
self.assertNotIn("--tile", base)
self.assertNotIn("--draft", base)
self.assertNotIn("--no", base)
on = build_mj_prompt(
"scene",
weird=1,
exp=1,
tile=True,
draft=True,
no_text="blur",
style_ref_urls=["https://upload.example/s.png"],
style_weight=100,
)
self.assertIn("--weird 1", on)
self.assertIn("--exp 1", on)
self.assertIn("--tile", on)
self.assertIn("--draft", on)
self.assertIn("--no blur", on)
self.assertIn("--sref https://upload.example/s.png", on)
self.assertIn("--sw 100", on)
no_style = build_mj_prompt("scene", style_weight=500)
self.assertNotIn("--sw", no_style)
self.assertNotIn("--sref", no_style)
def test_iw_only_when_reference_present(self):
without_ref = build_mj_prompt(
"portrait",
image_weight=2,
has_reference_image=False,
)
with_ref = build_mj_prompt(
"portrait",
image_weight=2,
has_reference_image=True,
)
self.assertNotIn("--iw", without_ref)
self.assertIn("--iw 2", with_ref)
def test_content_ref_urls_prefixed_and_deduped(self):
url_a = "https://upload.example/a.png"
url_b = "https://upload.example/b.png"
prompt = build_mj_prompt(
f"city night {url_b}",
has_reference_image=True,
content_ref_urls=[url_a, url_b],
image_weight=1.0,
)
self.assertTrue(prompt.startswith(f"{url_a} city night {url_b}"))
self.assertEqual(prompt.count(url_a), 1)
self.assertEqual(prompt.count(url_b), 1)
self.assertIn("--iw 1", prompt)
def test_rejects_empty_prompt_after_strip(self):
with self.assertRaisesRegex(ValueError, "提示词不能为空"):
build_mj_prompt(" --ar 1:1 --q 2 ")
self.assertEqual(strip_controlled_mj_flags("hello --stylize 100"), "hello")
self.assertEqual(
strip_controlled_mj_flags("x --weird 9 --tile --exp 2 --draft --no a,b --sref https://u/a --sw 1"),
"x",
)
class MjClientBodyTests(unittest.TestCase):
def test_body_text_only(self):
body = CLIENT.build_mj_submit_body(prompt="a cat --ar 1:1 --q 2 --s 250")
self.assertEqual(
body,
{
"model": MJ_MODEL_ID,
"prompt": "a cat --ar 1:1 --q 2 --s 250",
},
)
def test_body_with_one_https_reference(self):
body = CLIENT.build_mj_submit_body(
prompt="edit outfit --ar 4:5 --q 2 --iw 2 --s 250",
image_urls=["https://upload.example/ref.png"],
)
self.assertEqual(
body["images"],
["https://upload.example/ref.png"],
)
def test_body_rejects_http_and_multiple_refs(self):
with self.assertRaisesRegex(ValueError, "HTTPS URL"):
CLIENT.build_mj_submit_body(
prompt="x",
image_urls=["http://upload.example/ref.png"],
)
with self.assertRaisesRegex(ValueError, "最多 1 张"):
CLIENT.build_mj_submit_body(
prompt="x",
image_urls=[
"https://upload.example/a.png",
"https://upload.example/b.png",
],
)
class MjClientGenerateMocks(unittest.TestCase):
def test_generate_async_returns_four_images(self):
fake_images = [Image.new("RGB", (64, 64), color=i) for i in range(4)]
async def _run():
client = CLIENT.MjImageClient(
base_url="https://example.invalid",
api_key="test-key",
)
session = object()
with patch(
"comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls",
new=AsyncMock(return_value=[]),
) as upload_mock, patch(
"comfyui_o1key.clients.mj_image_client.submit_async_image_task",
new=AsyncMock(return_value="task_mj_1"),
) as submit_mock, patch(
"comfyui_o1key.clients.mj_image_client.poll_async_image_task",
new=AsyncMock(return_value={"status": "SUCCESS"}),
), patch(
"comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task",
new=AsyncMock(
return_value=(
{"status": "SUCCESS"},
(fake_images, {"download_bytes": 0, "download_seconds": 0.0, "download_wall_seconds": 0.0, "inline_images": 0}),
)
),
):
result = await client.generate_async(
session=session,
prompt="a small orange cat",
aspect_ratio="1:1",
quality=1,
timeout_seconds=120,
log_task_success=False,
log_downloads=False,
)
upload_mock.assert_awaited()
submit_mock.assert_awaited()
body = submit_mock.await_args.args[3]
self.assertEqual(body["model"], MJ_MODEL_ID)
self.assertIn("--ar 1:1", body["prompt"])
self.assertIn("--q 1", body["prompt"])
self.assertEqual(len(result), 4)
return result
asyncio.run(_run())
def test_generate_async_rejects_wrong_image_count(self):
fake_images = [Image.new("RGB", (32, 32), color=0)]
async def _run():
client = CLIENT.MjImageClient(
base_url="https://example.invalid",
api_key="test-key",
)
with patch(
"comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls",
new=AsyncMock(return_value=[]),
), patch(
"comfyui_o1key.clients.mj_image_client.submit_async_image_task",
new=AsyncMock(return_value="task_mj_bad"),
), patch(
"comfyui_o1key.clients.mj_image_client.poll_async_image_task",
new=AsyncMock(return_value={"status": "SUCCESS"}),
), patch(
"comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task",
new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)),
):
with self.assertRaisesRegex(RuntimeError, "应返回 4 张图"):
await client.generate_async(
session=object(),
prompt="oops",
log_task_success=False,
log_downloads=False,
)
asyncio.run(_run())
def test_multi_content_and_style_refs_submit_strategy(self):
fake_images = [Image.new("RGB", (48, 48), color=i) for i in range(4)]
content_pils = [Image.new("RGB", (16, 16), color=10), Image.new("RGB", (16, 16), color=20)]
style_pils = [Image.new("RGB", (16, 16), color=30)]
uploaded = [
"https://upload.example/c0.png",
"https://upload.example/c1.png",
"https://upload.example/s0.png",
]
async def _run():
client = CLIENT.MjImageClient(
base_url="https://example.invalid",
api_key="test-key",
)
with patch(
"comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls",
new=AsyncMock(return_value=uploaded),
) as upload_mock, patch(
"comfyui_o1key.clients.mj_image_client.submit_async_image_task",
new=AsyncMock(return_value="task_mj_multi"),
) as submit_mock, patch(
"comfyui_o1key.clients.mj_image_client.poll_async_image_task",
new=AsyncMock(return_value={"status": "SUCCESS"}),
), patch(
"comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task",
new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)),
):
result = await client.generate_async(
session=object(),
prompt="forest cabin",
images=content_pils,
style_images=style_pils,
style_weight=180,
weird=50,
tile=True,
exp=3,
log_task_success=False,
log_downloads=False,
)
upload_mock.assert_awaited()
upload_kwargs = upload_mock.await_args.kwargs
self.assertEqual(len(upload_kwargs["images"]), 3)
body = submit_mock.await_args.args[3]
self.assertEqual(body["images"], ["https://upload.example/c0.png"])
self.assertNotIn("https://upload.example/c1.png", body.get("images", []))
self.assertTrue(body["prompt"].startswith("https://upload.example/c1.png forest cabin"))
self.assertIn("--sref https://upload.example/s0.png", body["prompt"])
self.assertIn("--sw 180", body["prompt"])
self.assertIn("--iw 1", body["prompt"])
self.assertIn("--weird 50", body["prompt"])
self.assertIn("--tile", body["prompt"])
self.assertIn("--exp 3", body["prompt"])
self.assertEqual(len(result), 4)
asyncio.run(_run())
def test_draft_accepts_non_four_images(self):
fake_images = [Image.new("RGB", (24, 512), color=0)]
async def _run():
client = CLIENT.MjImageClient(
base_url="https://example.invalid",
api_key="test-key",
)
with patch(
"comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls",
new=AsyncMock(return_value=[]),
), patch(
"comfyui_o1key.clients.mj_image_client.submit_async_image_task",
new=AsyncMock(return_value="task_mj_draft"),
) as submit_mock, patch(
"comfyui_o1key.clients.mj_image_client.poll_async_image_task",
new=AsyncMock(return_value={"status": "SUCCESS"}),
), patch(
"comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task",
new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)),
):
result = await client.generate_async(
session=object(),
prompt="drafty",
draft=True,
log_task_success=False,
log_downloads=False,
)
body = submit_mock.await_args.args[3]
self.assertIn("--draft", body["prompt"])
self.assertEqual(len(result), 1)
asyncio.run(_run())
def test_non_draft_still_rejects_non_four(self):
fake_images = [Image.new("RGB", (32, 32), color=1) for _ in range(2)]
async def _run():
client = CLIENT.MjImageClient(
base_url="https://example.invalid",
api_key="test-key",
)
with patch(
"comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls",
new=AsyncMock(return_value=[]),
), patch(
"comfyui_o1key.clients.mj_image_client.submit_async_image_task",
new=AsyncMock(return_value="task_mj_two"),
), patch(
"comfyui_o1key.clients.mj_image_client.poll_async_image_task",
new=AsyncMock(return_value={"status": "SUCCESS"}),
), patch(
"comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task",
new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)),
):
with self.assertRaisesRegex(RuntimeError, "应返回 4 张图"):
await client.generate_async(
session=object(),
prompt="two",
draft=False,
log_task_success=False,
log_downloads=False,
)
asyncio.run(_run())
if __name__ == "__main__":
unittest.main()
+150 -19
View File
@@ -20,6 +20,20 @@ COMFY_ROOT = os.path.dirname(CUSTOM_NODES_DIR)
sys.path.insert(0, COMFY_ROOT)
sys.path.insert(0, CUSTOM_NODES_DIR)
import types as _types
# Avoid package-wide node registry (CUDA probe) in the portable CPU torch build.
_plugin = _types.ModuleType("comfyui_o1key")
_plugin.__path__ = [PLUGIN_DIR]
sys.modules["comfyui_o1key"] = _plugin
for _child in ("nodes", "utils", "clients"):
_mod = _types.ModuleType(f"comfyui_o1key.{_child}")
_mod.__path__ = [os.path.join(PLUGIN_DIR, _child)]
sys.modules[_mod.__name__] = _mod
_model_management = _types.ModuleType("comfy.model_management")
_model_management.processing_interrupted = lambda: False
_model_management.InterruptProcessingException = RuntimeError
sys.modules[_model_management.__name__] = _model_management
from comfy_api.latest import io # noqa: E402
from comfyui_o1key.clients.gpt_image_client import GptImageClient # noqa: E402
from comfyui_o1key.nodes.o1key_image_generator import ( # noqa: E402
@@ -29,9 +43,11 @@ from comfyui_o1key.nodes.o1key_image_generator import ( # noqa: E402
_parse_upload_manifest,
)
from comfyui_o1key.utils.image_utils import ( # noqa: E402
IMAGE_BATCH_MODE_ALIASES,
IMAGE_BATCH_MODE_CARTESIAN,
IMAGE_BATCH_MODE_GROUP_TO_MODELS,
IMAGE_BATCH_MODE_SINGLE_REFERENCES,
IMAGE_BATCH_MODES,
expand_image_generation_tasks,
pil_to_tensor,
tensor_to_pil,
@@ -55,15 +71,24 @@ class O1keyImageGeneratorTests(unittest.TestCase):
"Nano Banana 2.1",
"Nano Banana 2",
"Nano Banana Pro",
"gpt-image-2",
"gpt-image-2.6-sunburst",
"gpt-image-2.6-flare",
"gpt-image-2.5-sunburst",
"gpt-image-2.5-flare",
"gpt-image-2",
"Seedream 5.0 Pro",
"Nano Banana 2 Lite",
"Nano Banana",
],
)
schema = O1keyImageGenerator.define_schema()
complexity_input = next(item for item in schema.inputs if item.id == "复杂度")
self.assertEqual(list(complexity_input.options), ["高", "中", "低"])
self.assertEqual(complexity_input.default, "高")
quality_input = next(item for item in schema.inputs if item.id == "质量")
self.assertEqual(list(quality_input.options)[-2:], ["超高", "最高"])
format_input = next(item for item in schema.inputs if item.id == "输出格式")
self.assertEqual(list(format_input.options), ["jpeg", "png", "webp", "svg", "gif"])
def test_schema_is_panel_node_with_image_output(self):
schema = O1keyImageGenerator.define_schema()
schema.validate()
@@ -91,7 +116,7 @@ class O1keyImageGeneratorTests(unittest.TestCase):
"宽高比", "生图数量", "seed", "参考图清单",
"质量", "输出格式", "蒙版清单", "缩放图片", "背景",
"批量出图", "批量模式", "模特图清单",
"命名规则", "filename_prefix", "格式", "保存位置", "在线搜索", "图层拆分",
"命名规则", "filename_prefix", "格式", "保存位置", "图层拆分", "复杂度", "帧数", "帧时长ms",
],
)
count_input = next(item for item in schema.inputs if item.id == "生图数量")
@@ -100,21 +125,25 @@ class O1keyImageGeneratorTests(unittest.TestCase):
model_input = next(item for item in schema.inputs if item.id == "模型")
self.assertEqual(model_input.default, "Nano Banana 2.1")
self.assertIn("gpt-image-2", model_input.options)
self.assertIn("gpt-image-2.6-sunburst", model_input.options)
self.assertIn("gpt-image-2.6-flare", model_input.options)
self.assertIn("gpt-image-2.5-sunburst", model_input.options)
self.assertIn("gpt-image-2.5-flare", model_input.options)
self.assertIn("Seedream 5.0 Pro", model_input.options)
self.assertNotIn("Nano Banana 2 Lite", model_input.options)
self.assertNotIn("Nano Banana", model_input.options)
thinking_input = next(item for item in schema.inputs if item.id == "思考等级")
self.assertEqual(thinking_input.options, ["低", "高"])
self.assertEqual(thinking_input.default, "低")
self.assertEqual(thinking_input.default, "高")
resolution_input = next(item for item in schema.inputs if item.id == "分辨率")
self.assertEqual(resolution_input.options[0], "智能")
self.assertEqual(resolution_input.default, "智能")
resize_input = next(item for item in schema.inputs if item.id == "缩放图片")
self.assertEqual(resize_input.options, ["不缩放", "智能缩放"])
self.assertEqual(resize_input.default, "不缩放")
self.assertEqual(resize_input.default, "智能缩放")
self.assertNotIn("色彩纠正", [item.id for item in schema.inputs])
format_input = next(item for item in schema.inputs if item.id == "输出格式")
self.assertEqual(format_input.options, ["jpeg", "png", "webp"])
self.assertEqual(format_input.options, ["jpeg", "png", "webp", "svg", "gif"])
self.assertEqual(format_input.default, "jpeg")
background_input = next(item for item in schema.inputs if item.id == "背景")
self.assertEqual(background_input.options, ["auto", "transparent", "opaque"])
@@ -122,6 +151,8 @@ class O1keyImageGeneratorTests(unittest.TestCase):
self.assertNotIn("内容审查强度", [item.id for item in schema.inputs])
quality_input = next(item for item in schema.inputs if item.id == "质量")
self.assertEqual(quality_input.options[-2:], ["超高", "最高"])
seed_input = next(item for item in schema.inputs if item.id == "seed")
self.assertEqual(seed_input.display_name, "种子")
prompt_input = next(item for item in schema.inputs if item.id == "prompt")
self.assertEqual(prompt_input.display_name, "提示词")
self.assertTrue(prompt_input.socketless)
@@ -150,9 +181,7 @@ class O1keyImageGeneratorTests(unittest.TestCase):
self.assertEqual(save_format_input.default, "原始")
location_input = next(item for item in schema.inputs if item.id == "保存位置")
self.assertEqual(location_input.default, "")
search_input = next(item for item in schema.inputs if item.id == "在线搜索")
self.assertEqual(search_input.options, ["关闭", "打开"])
self.assertEqual(search_input.default, "关闭")
self.assertNotIn("在线搜索", [item.id for item in schema.inputs])
def test_batch_task_expansion_covers_group_and_cartesian_pairing(self):
grouped = expand_image_generation_tasks(
@@ -213,6 +242,39 @@ class O1keyImageGeneratorTests(unittest.TestCase):
self.assertEqual(len(fifty_single_references), 50)
self.assertEqual(fifty_single_references[-1]["reference_indices"], (49,))
def test_retired_batch_mode_labels_keep_their_pairing(self):
# Labels shipped before the rename must expand exactly like the current ones.
self.assertEqual(len(IMAGE_BATCH_MODE_ALIASES), 3)
for retired, current in IMAGE_BATCH_MODE_ALIASES.items():
with self.subTest(retired=retired):
retired_tasks = expand_image_generation_tasks(
"套用",
2,
batch_enabled=True,
batch_mode=retired,
reference_count=3,
model_reference_count=4,
)
current_tasks = expand_image_generation_tasks(
"套用",
2,
batch_enabled=True,
batch_mode=current,
reference_count=3,
model_reference_count=4,
)
self.assertEqual(retired_tasks, current_tasks)
def test_batch_mode_labels_are_industry_neutral(self):
self.assertEqual(
IMAGE_BATCH_MODES,
(
"整组素材→多个目标",
"每张素材×每张目标",
"每张素材单独出图",
),
)
def test_reference_limit_is_ten(self):
accepted = [
{"name": f"{index}.png", "subfolder": "", "type": "input"}
@@ -341,7 +403,6 @@ class O1keyImageGeneratorTests(unittest.TestCase):
seed=42,
参考图清单="[]",
缩放图片="智能缩放",
在线搜索="打开",
))
self.assertIs(result[0], image)
@@ -350,10 +411,10 @@ class O1keyImageGeneratorTests(unittest.TestCase):
self.assertEqual(execute.call_args.kwargs["生图数量"], 2)
self.assertEqual(execute.call_args.kwargs["参考图组"], {})
self.assertEqual(execute.call_args.kwargs["缩放图片"], "智能缩放")
self.assertIs(execute.call_args.kwargs["_o1key_google_search"], True)
self.assertIs(execute.call_args.kwargs["_o1key_google_search"], False)
self.assertIs(execute.call_args.kwargs["_o1key_unlimited_downloads"], True)
def test_online_search_is_ignored_for_other_models(self):
def test_google_search_is_never_requested(self):
image = torch.zeros((1, 8, 8, 3), dtype=torch.float32)
with patch(
"comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute",
@@ -363,12 +424,11 @@ class O1keyImageGeneratorTests(unittest.TestCase):
prompt="一只宇航猫",
模型="Nano Banana Pro",
分辨率="2K",
在线搜索="打开",
))
self.assertIs(execute.call_args.kwargs["_o1key_google_search"], False)
def test_default_model_delegates_nano_banana_21_with_search_and_thinking(self):
def test_default_model_delegates_nano_banana_21_with_thinking(self):
image = torch.zeros((1, 8, 8, 3), dtype=torch.float32)
with patch(
"comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute",
@@ -376,13 +436,13 @@ class O1keyImageGeneratorTests(unittest.TestCase):
) as execute:
result = asyncio.run(O1keyImageGenerator.execute(
prompt="test", 模型线路="直连", 思考等级="高",
分辨率="4K", 宽高比="1:8", 在线搜索="打开",
分辨率="4K", 宽高比="1:8",
))
self.assertIs(result[0], image)
self.assertEqual(execute.call_args.kwargs["模型"], "Nano Banana 2.1")
self.assertEqual(execute.call_args.kwargs["模型线路"], "直连")
self.assertEqual(execute.call_args.kwargs["思考等级"], "高")
self.assertIs(execute.call_args.kwargs["_o1key_google_search"], True)
self.assertIs(execute.call_args.kwargs["_o1key_google_search"], False)
def test_error_wrappers_apply_to_every_model_family(self):
raw = (
@@ -491,22 +551,24 @@ class O1keyImageGeneratorTests(unittest.TestCase):
):
result = asyncio.run(O1keyImageGenerator.execute(
prompt="一只宇航猫",
模型="gpt-image-2.5-sunburst",
模型="gpt-image-2.6-sunburst",
模型线路="畅速",
分辨率="2K",
宽高比="16:9",
生图数量=4,
质量="最高",
复杂度="中",
输出格式="webp",
背景="transparent",
缩放图片="智能缩放",
))
self.assertEqual(tuple(result[0].shape), (4, 4, 6, 3))
self.assertTrue(all(call["complexity"] == "medium" for call in calls))
self.assertEqual(len(calls), 4)
self.assertGreater(maximum_active, 1)
self.assertTrue(all(call["n"] == 1 for call in calls))
self.assertTrue(all(call["model"] == "gpt-image-2.5-sunburst-sp" for call in calls))
self.assertTrue(all(call["model"] == "gpt-image-2.6-sunburst-sp" for call in calls))
self.assertTrue(all(call["special_price_parallel"] is False for call in calls))
self.assertTrue(all(call["size"] == "3648x2048" for call in calls))
self.assertTrue(all(call["quality"] == "max" for call in calls))
@@ -515,6 +577,75 @@ class O1keyImageGeneratorTests(unittest.TestCase):
self.assertTrue(all("moderation" not in call for call in calls))
self.assertTrue(all(call["resize_mode"] == "智能缩放" for call in calls))
def test_gpt_26_gif_sends_frame_fields_and_rejects_edit(self):
calls = []
class FakeClient:
def __init__(self):
self.base_url = ""
self.response_log_enabled = True
self.poll_log_enabled = True
async def generate_image_async(self, **kwargs):
calls.append(kwargs)
return [Image.new("RGB", (6, 4), "red")]
@staticmethod
def _pil_list_to_tensor(images):
return torch.zeros((len(images), 4, 6, 3), dtype=torch.float32)
with (
patch(
"comfyui_o1key.nodes.o1key_image_generator.GptImageClient",
FakeClient,
),
patch(
"comfyui_o1key.nodes.o1key_image_generator.get_base_url_by_route",
return_value="https://example.invalid",
),
):
result = asyncio.run(O1keyImageGenerator.execute(
prompt="一只宇航猫",
模型="gpt-image-2.6-flare",
模型线路="畅速",
分辨率="智能",
宽高比="1:1",
生图数量=1,
质量="自动",
复杂度="低",
输出格式="gif",
帧数=12,
帧时长ms=205,
背景="auto",
缩放图片="不缩放",
))
self.assertEqual(tuple(result[0].shape), (1, 4, 6, 3))
self.assertEqual(calls[0]["output_format"], "gif")
self.assertEqual(calls[0]["frame_count"], 12)
self.assertEqual(calls[0]["frame_duration_ms"], 200)
self.assertEqual(calls[0]["complexity"], "low")
fake_ref = torch.zeros((1, 8, 8, 3), dtype=torch.float32)
with (
patch(
"comfyui_o1key.nodes.o1key_image_generator._load_reference_tensors",
return_value={0: fake_ref},
),
self.assertRaisesRegex(ValueError, "纯文生图"),
):
asyncio.run(O1keyImageGenerator.execute(
prompt="一只宇航猫",
模型="gpt-image-2.6-sunburst",
模型线路="畅速",
分辨率="智能",
宽高比="1:1",
生图数量=1,
质量="自动",
输出格式="svg",
参考图清单='[{"name":"a.png","subfolder":"","type":"input"}]',
))
def test_seedream_direct_execution_sends_exact_size_and_output_format(self):
calls = []
session = object()
File diff suppressed because it is too large Load Diff
+201
View File
@@ -0,0 +1,201 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import vm from "node:vm";
import { webcrypto } from "node:crypto";
const sourcePath = new URL("../web/js/o1keyImageGenerator.js", import.meta.url);
const source = fs.readFileSync(sourcePath, "utf8").replace(/^import .*;\s*$/gm, "");
let nextNodeId = 1;
let nextLinkId = 1;
const graph = {
nodes: new Map(),
links: new Map(),
add(node) {
node.id = nextNodeId++;
node.graph = this;
this.nodes.set(node.id, node);
},
getNodeById(id) { return this.nodes.get(id); },
beforeChange() {},
afterChange() {},
setDirtyCanvas() {},
};
const LiteGraph = {
createNode(type) {
return {
type,
comfyClass: type,
pos: [0, 0],
size: [300, 260],
properties: {},
inputs: [{ link: null }],
widgets: [],
};
},
};
const app = {
graph,
ui: { settings: { getSettingValue: () => false } },
registerExtension() {},
};
const api = {
apiURL: (value) => value,
addEventListener() {},
fetchApi: async () => ({ ok: true, json: async () => ({}) }),
};
class Element {
constructor(tagName) {
this.tagName = String(tagName).toUpperCase();
this.children = [];
this.className = "";
this.style = {};
this.dataset = {};
this.listeners = new Map();
}
append(...items) { this.children.push(...items); }
prepend(...items) { this.children.unshift(...items); }
replaceChildren(...items) { this.children = [...items]; }
addEventListener(type, listener) { this.listeners.set(type, listener); }
setAttribute(name, value) { this[name] = value; }
classList = {
values: new Set(),
add(v) { this.values.add(v); },
remove(v) { this.values.delete(v); },
contains(v) { return this.values.has(v); },
toggle(v, force) {
const on = force ?? !this.values.has(v);
if (on) this.values.add(v); else this.values.delete(v);
return on;
},
};
}
const document = {
head: { append() {}, appendChild() {} },
body: { append() {} },
createElement(tag) { return new Element(tag); },
createElementNS(_ns, tag) { return new Element(tag); },
getElementById() { return null; },
querySelector() { return null; },
addEventListener() {},
removeEventListener() {},
};
const context = vm.createContext({
app,
api,
document,
window: { LiteGraph },
URL,
URLSearchParams,
FormData,
Event,
openReferenceImageEditor: async () => null,
crypto: webcrypto,
console,
clearTimeout,
setTimeout,
requestAnimationFrame: (cb) => cb(),
});
vm.runInContext(source, context, { filename: sourcePath.pathname });
const createSaveNodeForBatch = vm.runInContext("createSaveNodeForBatch", context);
const nextHorizontalSaveNodePos = vm.runInContext("nextHorizontalSaveNodePos", context);
const measureNodeExtent = vm.runInContext("measureNodeExtent", context);
const generatorPanelMinHeight = vm.runInContext("generatorPanelMinHeight", context);
const generatorMinimumHeight = vm.runInContext("generatorMinimumHeight", context);
const generatorChromeHeight = vm.runInContext("generatorChromeHeight", context);
const isVueNodesEnabled = vm.runInContext("isVueNodesEnabled", context);
const SAVE_NODE_LAYOUT_GAP_X = vm.runInContext("SAVE_NODE_LAYOUT_GAP_X", context);
const SAVE_NODE_LAYOUT_ORIGIN_GAP_X = vm.runInContext("SAVE_NODE_LAYOUT_ORIGIN_GAP_X", context);
const SAVE_NODE_LAYOUT_SIZE = vm.runInContext("SAVE_NODE_LAYOUT_SIZE", context);
assert.equal(isVueNodesEnabled(), false);
assert.equal(SAVE_NODE_LAYOUT_GAP_X, 50);
assert.equal(SAVE_NODE_LAYOUT_ORIGIN_GAP_X, 70);
{
const generator = { pos: [100, 200], size: [500, 1025] };
const firstPos = nextHorizontalSaveNodePos(generator, []);
assert.equal(firstPos[0], 100 + 500 + SAVE_NODE_LAYOUT_ORIGIN_GAP_X);
assert.equal(firstPos[1], 200 + 30);
const firstPeer = { pos: [700, 230], size: [300, 260] };
const secondPos = nextHorizontalSaveNodePos(generator, [firstPeer]);
assert.equal(secondPos[0], 700 + 300 + SAVE_NODE_LAYOUT_GAP_X);
assert.equal(secondPos[1], 230);
const secondPeer = { pos: [1050, 230], size: [407, 440] };
const thirdPos = nextHorizontalSaveNodePos(generator, [firstPeer, secondPeer]);
assert.equal(thirdPos[0], 1050 + 407 + SAVE_NODE_LAYOUT_GAP_X);
assert.equal(thirdPos[1], 230);
const blocking = {
pos: [700 + 300 + SAVE_NODE_LAYOUT_GAP_X, 230],
size: [...SAVE_NODE_LAYOUT_SIZE],
};
const blockedPos = nextHorizontalSaveNodePos(generator, [firstPeer, blocking]);
assert.equal(blockedPos[0], blocking.pos[0] + blocking.size[0] + SAVE_NODE_LAYOUT_GAP_X);
assert.equal(blockedPos[1], 230);
}
{
LiteGraph.vueNodesMode = true;
assert.equal(isVueNodesEnabled(), true);
assert.equal(generatorChromeHeight(), 16);
const generator = { pos: [10, 20], size: [560, 1035] };
const pos = nextHorizontalSaveNodePos(generator, []);
assert.equal(pos[0], 10 + 560 + SAVE_NODE_LAYOUT_ORIGIN_GAP_X);
assert.equal(pos[1], 20); // no classic +30 offset under Vue Nodes
LiteGraph.vueNodesMode = false;
}
{
assert.equal(generatorMinimumHeight({ _o1igModel: { value: "Nano Banana 2" } }), 1025);
assert.equal(
generatorMinimumHeight({
_o1igModel: { value: "gpt-image-2" },
_o1igBatchEnabled: true,
}),
1300,
);
assert.ok(generatorPanelMinHeight({ _o1igModel: { value: "Nano Banana 2" } }) >= 292);
assert.equal(measureNodeExtent({ pos: [1, 2], size: [0, 0] }).width, SAVE_NODE_LAYOUT_SIZE[0]);
assert.equal(measureNodeExtent({ pos: [1, 2], size: [410, 500] }).right, 411);
}
{
const generator = {
id: 100,
graph,
pos: [20, 30],
size: [410, 340],
outputs: [{ links: [] }],
connect(_originSlot, target) {
const linkId = nextLinkId++;
graph.links.set(linkId, { origin_id: this.id, target_id: target.id });
this.outputs[0].links.push(linkId);
target.inputs[0].link = linkId;
},
};
graph.nodes.set(generator.id, generator);
const first = createSaveNodeForBatch(generator, "11111111-1111-4111-8111-111111111111");
const second = createSaveNodeForBatch(generator, "22222222-2222-4222-8222-222222222222");
assert.equal(first.pos[0], generator.pos[0] + generator.size[0] + SAVE_NODE_LAYOUT_ORIGIN_GAP_X);
assert.equal(first.pos[1], generator.pos[1] + 30);
assert.equal(second.pos[0], first.pos[0] + first.size[0] + SAVE_NODE_LAYOUT_GAP_X);
assert.equal(second.pos[1], first.pos[1]);
assert.ok(second.pos[0] > first.pos[0]);
}
assert.doesNotMatch(source, /batchIndex % 3/);
assert.match(source, /function nextHorizontalSaveNodePos\(/);
assert.match(source, /getMinHeight: \(\) => generatorPanelMinHeight\(node\)/);
assert.match(source, /Comfy\.VueNodes\.Enabled/);
console.log("layout placement tests passed");
+91 -18
View File
@@ -18,6 +18,20 @@ COMFY_ROOT = CUSTOM_NODES_ROOT.parent
sys.path.insert(0, str(COMFY_ROOT))
sys.path.insert(0, str(CUSTOM_NODES_ROOT))
import types as _types
# Avoid package-wide node registry (CUDA probe) in the portable CPU torch build.
_plugin = _types.ModuleType("comfyui_o1key")
_plugin.__path__ = [str(ROOT)]
sys.modules["comfyui_o1key"] = _plugin
for _child in ("nodes", "utils", "clients"):
_mod = _types.ModuleType(f"comfyui_o1key.{_child}")
_mod.__path__ = [str(ROOT / _child)]
sys.modules[_mod.__name__] = _mod
_model_management = _types.ModuleType("comfy.model_management")
_model_management.processing_interrupted = lambda: False
_model_management.InterruptProcessingException = RuntimeError
sys.modules[_model_management.__name__] = _model_management
from comfyui_o1key.utils import o1key_image_jobs as JOBS # noqa: E402
@@ -70,12 +84,12 @@ class PayloadTests(unittest.TestCase):
self.assertEqual(job["generator_node_id"], 1)
self.assertEqual(job["save_node_id"], 2)
def test_missing_thinking_level_defaults_to_low(self):
def test_missing_thinking_level_and_resize_defaults(self):
payload = _payload()
payload.pop("thinking_level")
job = JOBS.normalize_job_payload(payload)
self.assertEqual(job["thinking_level"], "低")
self.assertEqual(job["resize_mode"], "不缩放")
self.assertEqual(job["thinking_level"], "高")
self.assertEqual(job["resize_mode"], "智能缩放")
self.assertNotIn("color_correction", job)
self.assertEqual(job["filename_prefix"], "o1key")
self.assertEqual(job["save_format"], "原始")
@@ -110,6 +124,62 @@ class PayloadTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "Nano Banana 2"):
JOBS.normalize_job_payload(payload)
def test_26_complexity_normalizes_default_and_rejects_invalid_values(self):
for variant in ("sunburst", "flare"):
model = f"gpt-image-2.6-{variant}"
job = JOBS.normalize_job_payload({**_payload(), "model": model})
self.assertEqual(job["complexity"], "high")
for value, expected in (("low", "low"), ("medium", "medium"), ("high", "high"),
("低", "low"), ("中", "medium"), ("高", "high")):
job = JOBS.normalize_job_payload({**_payload(), "model": model, "complexity": value})
self.assertEqual(job["complexity"], expected)
for value in ("invalid", "", [], 1):
with self.subTest(model=model, value=value), self.assertRaisesRegex(ValueError, "复杂度"):
JOBS.normalize_job_payload({**_payload(), "model": model, "complexity": value})
job = JOBS.normalize_job_payload({**_payload(), "model": "gpt-image-2.5-sunburst", "complexity": "low"})
self.assertNotIn("complexity", job)
def test_26_svg_gif_normalize_and_reject_edit(self):
for output_format in ("svg", "gif"):
job = JOBS.normalize_job_payload({
**_payload(),
"batch_id": str(__import__("uuid").uuid4()),
"model": "gpt-image-2.6-sunburst",
"output_format": output_format,
"frame_count": 12 if output_format == "gif" else 9,
"frame_duration_ms": 205 if output_format == "gif" else 200,
})
self.assertEqual(job["output_format"], output_format)
if output_format == "gif":
self.assertEqual(job["frame_count"], 12)
self.assertEqual(job["frame_duration_ms"], 200)
else:
self.assertNotIn("frame_count", job)
self.assertNotIn("frame_duration_ms", job)
with self.assertRaisesRegex(ValueError, "仅支持 GPT Image 2.6"):
JOBS.normalize_job_payload({
**_payload(),
"batch_id": str(__import__("uuid").uuid4()),
"model": "gpt-image-2.5-sunburst",
"output_format": output_format,
})
with self.assertRaisesRegex(ValueError, "纯文生图"):
JOBS.normalize_job_payload({
**_payload(),
"batch_id": str(__import__("uuid").uuid4()),
"model": "gpt-image-2.6-flare",
"output_format": output_format,
"references": [{"name": "a.png", "subfolder": "", "type": "input"}],
})
with self.assertRaisesRegex(ValueError, "帧数"):
JOBS.normalize_job_payload({
**_payload(),
"batch_id": str(__import__("uuid").uuid4()),
"model": "gpt-image-2.6-flare",
"output_format": "gif",
"frame_count": 1,
})
def test_unified_limits_and_gpt_parameters(self):
payload = _payload()
payload.update({
@@ -146,7 +216,8 @@ class PayloadTests(unittest.TestCase):
self.assertEqual(default_gpt["resize_mode"], "智能缩放")
self.assertEqual(default_gpt["save_format"], "原始")
for model in ("gpt-image-2.5-sunburst", "gpt-image-2.5-flare"):
for model in ("gpt-image-2.5-sunburst", "gpt-image-2.5-flare",
"gpt-image-2.6-sunburst", "gpt-image-2.6-flare"):
with self.subTest(model=model):
gpt_25 = JOBS.normalize_job_payload({
**_payload(),
@@ -353,7 +424,7 @@ class PayloadTests(unittest.TestCase):
grouped = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "一组搭配+多模特",
"batch_mode": "整组素材→多个目标",
"references": outfits[:9],
"model_references": models,
})
@@ -364,7 +435,7 @@ class PayloadTests(unittest.TestCase):
cartesian = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "全部搭配×全部模特",
"batch_mode": "每张素材×每张目标",
"references": outfits,
"model_references": models,
})
@@ -376,7 +447,7 @@ class PayloadTests(unittest.TestCase):
single_references = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "单图素材批量",
"batch_mode": "每张素材单独出图",
"references": outfits[:3],
"model_references": models[:1],
})
@@ -404,7 +475,7 @@ class PayloadTests(unittest.TestCase):
single_fifty = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "单图素材批量",
"batch_mode": "每张素材单独出图",
"references": fifty_references,
})
self.assertEqual(single_fifty["total_task_count"], 50)
@@ -412,7 +483,7 @@ class PayloadTests(unittest.TestCase):
grouped_fifty_targets = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "一组搭配+多模特",
"batch_mode": "整组素材→多个目标",
"references": outfits[:1],
"model_references": fifty_models,
})
@@ -422,7 +493,7 @@ class PayloadTests(unittest.TestCase):
JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "单图素材批量",
"batch_mode": "每张素材单独出图",
"references": [
*fifty_references,
{"name": "overflow.png", "subfolder": "", "type": "input"},
@@ -433,7 +504,7 @@ class PayloadTests(unittest.TestCase):
JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "一组搭配+多模特",
"batch_mode": "整组素材→多个目标",
"references": outfits,
"model_references": models[:1],
})
@@ -641,7 +712,7 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
"model": "gpt-image-2",
"resolution": "1K",
"batch_enabled": True,
"batch_mode": "单图素材批量",
"batch_mode": "每张素材单独出图",
"references": references,
})
job["reference_paths"] = tuple(item["name"] for item in references)
@@ -700,7 +771,7 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
"model": "gpt-image-2",
"resolution": "1K",
"batch_enabled": True,
"batch_mode": "全部搭配×全部模特",
"batch_mode": "每张素材×每张目标",
"references": [
{"name": os.path.basename(path), "subfolder": "", "type": "input"}
for path in outfit_paths
@@ -769,7 +840,8 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
job = JOBS.normalize_job_payload({
**_payload(),
"model": "gpt-image-2.5-sunburst",
"model": "gpt-image-2.6-sunburst",
"complexity": "low",
"resolution": "4K",
"aspect_ratio": "智能",
"prompt": "紫色方块\n---\n绿色圆形",
@@ -802,7 +874,8 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
self.assertGreater(maximum_active, 1)
self.assertTrue(all(call["n"] == 1 for call in calls))
self.assertTrue(all(call["quality"] == "xhigh" for call in calls))
self.assertTrue(all(call["model"] == "gpt-image-2.5-sunburst-sp" for call in calls))
self.assertTrue(all(call["model"] == "gpt-image-2.6-sunburst-sp" for call in calls))
self.assertTrue(all(call["complexity"] == "low" for call in calls))
self.assertTrue(all(call["special_price_parallel"] is False for call in calls))
self.assertTrue(all(call["size"] == "2880x2880" for call in calls))
self.assertTrue(all(call["output_format"] == "webp" for call in calls))
@@ -902,7 +975,7 @@ class NanoExecutionTests(unittest.IsolatedAsyncioTestCase):
job = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "单图素材批量",
"batch_mode": "每张素材单独出图",
"references": references,
})
job["reference_paths"] = tuple(item["name"] for item in references)
@@ -969,7 +1042,7 @@ class NanoExecutionTests(unittest.IsolatedAsyncioTestCase):
job = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "全部搭配×全部模特",
"batch_mode": "每张素材×每张目标",
"references": [
{"name": os.path.basename(path), "subfolder": "", "type": "input"}
for path in outfit_paths
@@ -1162,7 +1235,7 @@ class IsolationTests(unittest.TestCase):
job = JOBS.normalize_job_payload({
**_payload(),
"batch_enabled": True,
"batch_mode": "全部搭配×全部模特",
"batch_mode": "每张素材×每张目标",
"references": [{"name": "outfit.png", "subfolder": "", "type": "input"}],
"model_references": [{"name": "model.png", "subfolder": "", "type": "input"}],
})
+67
View File
@@ -334,5 +334,72 @@ class O1keyImageSaveTests(unittest.TestCase):
self.assertEqual(Path(output_dir, "1.png").read_bytes(), b"keep-existing")
def test_original_gif_preserves_bytes_and_marks_animated(self):
frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue", "green")]
buffer = BytesIO()
frames[0].save(
buffer,
format="GIF",
save_all=True,
append_images=frames[1:],
duration=120,
loop=0,
)
raw = buffer.getvalue()
for image in frames:
image.close()
with tempfile.TemporaryDirectory() as temp_dir, tempfile.TemporaryDirectory() as output_dir:
source = os.path.join(temp_dir, "provider.gif")
Path(source).write_bytes(raw)
results = save_temp_images(
[source],
"o1key-gif",
"原始",
output_dir,
_folder_paths(output_dir),
naming_rule="自定义前缀",
)
self.assertEqual(len(results), 1)
self.assertTrue(results[0]["filename"].endswith(".gif"))
self.assertEqual(results[0].get("media"), "gif")
self.assertTrue(results[0].get("animated"))
saved = Path(output_dir, results[0]["filename"]).read_bytes()
self.assertEqual(detect_image_format(saved), "GIF")
self.assertEqual(saved, raw)
def test_forced_png_from_gif_reencodes_first_frame(self):
frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue")]
buffer = BytesIO()
frames[0].save(
buffer,
format="GIF",
save_all=True,
append_images=frames[1:],
duration=100,
loop=0,
)
raw = buffer.getvalue()
for image in frames:
image.close()
with tempfile.TemporaryDirectory() as temp_dir, tempfile.TemporaryDirectory() as output_dir:
source = os.path.join(temp_dir, "provider.gif")
Path(source).write_bytes(raw)
results = save_temp_images(
[source],
"o1key-gif-png",
"png",
output_dir,
_folder_paths(output_dir),
naming_rule="自定义前缀",
)
self.assertTrue(results[0]["filename"].endswith(".png"))
self.assertNotEqual(results[0].get("media"), "gif")
self.assertEqual(
detect_image_format(Path(output_dir, results[0]["filename"]).read_bytes()),
"PNG",
)
if __name__ == "__main__":
unittest.main(verbosity=2)
+188
View File
@@ -0,0 +1,188 @@
"""Tests for O1keySaveGIF — output save + custom-key GIF preview + passthrough."""
from __future__ import annotations
import os
import sys
import tempfile
import unittest
from io import BytesIO
from pathlib import Path
from types import ModuleType, SimpleNamespace
from unittest.mock import patch
import torch
from PIL import Image
PLUGIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CUSTOM_NODES_DIR = os.path.dirname(PLUGIN_DIR)
COMFY_ROOT = os.path.dirname(CUSTOM_NODES_DIR)
for child in ("nodes", "utils", "clients"):
package = ModuleType(f"comfyui_o1key.{child}")
package.__path__ = [os.path.join(PLUGIN_DIR, child)]
sys.modules[package.__name__] = package
plugin_package = ModuleType("comfyui_o1key")
plugin_package.__path__ = [PLUGIN_DIR]
sys.modules[plugin_package.__name__] = plugin_package
model_management = ModuleType("comfy.model_management")
model_management.processing_interrupted = lambda: False
model_management.InterruptProcessingException = RuntimeError
sys.modules[model_management.__name__] = model_management
sys.path.insert(0, COMFY_ROOT)
sys.path.insert(0, CUSTOM_NODES_DIR)
def _make_gif_bytes(colors=("red", "blue", "green"), duration=100) -> bytes:
frames = [Image.new("RGB", (6, 4), color) for color in colors]
buf = BytesIO()
frames[0].save(
buf,
format="GIF",
save_all=True,
append_images=frames[1:],
duration=duration,
loop=0,
)
return buf.getvalue()
class SaveGifHelperTests(unittest.TestCase):
def test_read_and_duration_helpers(self):
from comfyui_o1key.utils.gpt_image_media import (
encode_gif_from_pil_images,
is_gif_bytes,
read_gif_bytes_from_path,
resolve_gif_frame_duration_ms,
)
self.assertEqual(resolve_gif_frame_duration_ms(fps=5.0, frame_duration_ms=0), 200)
self.assertEqual(resolve_gif_frame_duration_ms(fps=5.0, frame_duration_ms=120), 120)
data = _make_gif_bytes()
self.assertTrue(is_gif_bytes(data))
with tempfile.TemporaryDirectory() as temp_dir:
path = os.path.join(temp_dir, "demo.gif")
Path(path).write_bytes(data)
self.assertEqual(read_gif_bytes_from_path(path), data)
self.assertIsNone(read_gif_bytes_from_path(os.path.join(temp_dir, "missing.gif")))
png = os.path.join(temp_dir, "x.png")
Image.new("RGB", (2, 2), "white").save(png)
self.assertIsNone(read_gif_bytes_from_path(png))
frames = [Image.new("RGB", (4, 4), c) for c in ("red", "blue")]
encoded = encode_gif_from_pil_images(frames, duration_ms=80)
self.assertTrue(is_gif_bytes(encoded))
class SaveGifNodeTests(unittest.TestCase):
def test_passthrough_writes_output_and_preview_payload(self):
from comfyui_o1key.nodes.save_gif import O1keySaveGIF, SavedGifPreview
gif_bytes = _make_gif_bytes()
with tempfile.TemporaryDirectory() as source_dir, tempfile.TemporaryDirectory() as output_dir:
source = os.path.join(source_dir, "provider.gif")
Path(source).write_bytes(gif_bytes)
def get_save_image_path(prefix, root, _w, _h):
return root, prefix, 1, "", prefix
folder = SimpleNamespace(
get_output_directory=lambda: output_dir,
get_save_image_path=get_save_image_path,
)
with patch("comfyui_o1key.nodes.save_gif.folder_paths", folder):
result = O1keySaveGIF.execute(文件路径=source, 文件名前缀="ComfyUI")
target = result.args[0]
ui_obj = result.ui
self.assertTrue(str(target).lower().endswith(".gif"))
self.assertTrue(Path(target).is_file())
self.assertEqual(Path(target).read_bytes(), gif_bytes)
self.assertTrue(str(target).startswith(output_dir))
self.assertIsInstance(ui_obj, SavedGifPreview)
data = ui_obj.as_dict()
# Custom key only — core must NOT see ``images`` or it will mount
# $$canvas-image-preview (static frame + "W x H") under our <img>.
self.assertNotIn("images", data)
self.assertNotIn("animated", data)
self.assertIn(SavedGifPreview.UI_KEY, data)
entry = data[SavedGifPreview.UI_KEY][0]
self.assertEqual(entry["type"], "output")
self.assertTrue(str(entry["filename"]).lower().endswith(".gif"))
self.assertEqual(entry["filename"], Path(target).name)
self.assertEqual(entry["subfolder"], "")
def test_image_metadata_passthrough_avoids_reencode(self):
from comfyui_o1key.nodes.save_gif import O1keySaveGIF, SavedGifPreview
from comfyui_o1key.utils.image_utils import pil_to_tensor
from comfyui_o1key.utils.gpt_image_media import expand_gif_frames
gif_bytes = _make_gif_bytes()
with Image.open(BytesIO(gif_bytes)) as opened:
frames = expand_gif_frames(opened, gif_bytes)
tensor = pil_to_tensor(frames)
with tempfile.TemporaryDirectory() as output_dir:
def get_save_image_path(prefix, root, _w, _h):
return root, prefix, 7, "", prefix
folder = SimpleNamespace(
get_output_directory=lambda: output_dir,
get_save_image_path=get_save_image_path,
)
with patch("comfyui_o1key.nodes.save_gif.folder_paths", folder):
result = O1keySaveGIF.execute(图像=tensor, fps=5.0, 文件名前缀="meta")
target = result.args[0]
self.assertEqual(Path(target).read_bytes(), gif_bytes)
data = result.ui.as_dict()
self.assertNotIn("images", data)
self.assertNotIn("animated", data)
self.assertTrue(
str(data[SavedGifPreview.UI_KEY][0]["filename"]).lower().endswith(".gif")
)
def test_image_batch_fallback_encodes_gif(self):
from comfyui_o1key.nodes.save_gif import O1keySaveGIF, SavedGifPreview
from comfyui_o1key.utils.image_utils import pil_to_tensor
from comfyui_o1key.utils.gpt_image_media import is_gif_bytes
frames = [Image.new("RGB", (5, 3), c) for c in ("red", "green", "blue")]
tensor = pil_to_tensor(frames)
with tempfile.TemporaryDirectory() as output_dir:
def get_save_image_path(prefix, root, _w, _h):
return root, prefix, 3, "", prefix
folder = SimpleNamespace(
get_output_directory=lambda: output_dir,
get_save_image_path=get_save_image_path,
)
with patch("comfyui_o1key.nodes.save_gif.folder_paths", folder):
result = O1keySaveGIF.execute(图像=tensor, fps=10.0, 文件名前缀="anim")
target = result.args[0]
ui_obj = result.ui
data = Path(target).read_bytes()
self.assertTrue(is_gif_bytes(data))
payload = ui_obj.as_dict()
self.assertNotIn("images", payload)
self.assertNotIn("animated", payload)
self.assertIn(SavedGifPreview.UI_KEY, payload)
self.assertIsInstance(tensor, torch.Tensor)
def test_schema_registers_chinese_labels(self):
from comfyui_o1key.nodes.save_gif import O1keySaveGIF
schema = O1keySaveGIF.define_schema()
schema.validate()
self.assertEqual(schema.node_id, "O1keySaveGIF")
self.assertEqual(schema.display_name, "保存 GIF")
ids = [item.id for item in schema.inputs]
self.assertIn("文件路径", ids)
self.assertIn("图像", ids)
self.assertIn("文件名前缀", ids)
self.assertTrue(schema.is_output_node)
if __name__ == "__main__":
unittest.main()