610 lines
26 KiB
Python
610 lines
26 KiB
Python
"""Offline regression tests for the standalone GPT Image nodes."""
|
|
|
|
import asyncio
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
import unittest
|
|
from io import BytesIO
|
|
from types import ModuleType
|
|
from unittest.mock import AsyncMock, 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)
|
|
|
|
from comfyui_o1key.clients.gpt_image_client import ( # noqa: E402
|
|
GptImageClient,
|
|
resolve_gpt_image_model,
|
|
)
|
|
from comfyui_o1key.nodes.gpt_image import ( # noqa: E402
|
|
O1keyGPTImage,
|
|
resolve_gpt_image_quality,
|
|
)
|
|
from comfyui_o1key.nodes.gpt_image_batch import ( # noqa: E402
|
|
O1keyGPTImageBatch,
|
|
_path_option,
|
|
)
|
|
from comfyui_o1key.utils.file_utils import ImageInfo # noqa: E402
|
|
|
|
|
|
class GPTImageNodeSchemaTests(unittest.TestCase):
|
|
def assert_combo_values_are_strings(self, schema):
|
|
for item in schema.inputs:
|
|
if item.io_type != "COMBO":
|
|
continue
|
|
self.assertTrue(
|
|
all(isinstance(option, str) for option in item.options),
|
|
item.id,
|
|
)
|
|
if item.default is not None:
|
|
self.assertIsInstance(item.default, str, item.id)
|
|
|
|
def test_single_node_keeps_request_controls_without_color_correction(self):
|
|
schema = O1keyGPTImage.define_schema()
|
|
schema.validate()
|
|
self.assert_combo_values_are_strings(schema)
|
|
inputs = {item.id: item for item in schema.inputs}
|
|
|
|
self.assertEqual(inputs["缩放图片"].options, ["不缩放", "智能缩放"])
|
|
self.assertEqual(inputs["缩放图片"].default, "智能缩放")
|
|
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", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量",
|
|
"输出格式", "背景", "遮罩", "参考图组", "缩放图片", "seed",
|
|
"帧数", "帧时长ms",
|
|
],
|
|
)
|
|
self.assertEqual(
|
|
inputs["质量"].options,
|
|
["高", "中", "低", "自动", "超高", "最高"],
|
|
)
|
|
|
|
def test_25_quality_values_are_model_specific(self):
|
|
self.assertEqual(resolve_gpt_image_quality("gpt-image-2.5-sunburst", "超高"), "xhigh")
|
|
self.assertEqual(resolve_gpt_image_quality("gpt-image-2.5-flare", "最高"), "max")
|
|
self.assertEqual(resolve_gpt_image_quality("gpt-image-2", "高"), "high")
|
|
with self.assertRaisesRegex(ValueError, "仅支持 GPT Image 2.5"):
|
|
resolve_gpt_image_quality("gpt-image-2", "超高")
|
|
|
|
def test_gpt_image_25_models_resolve_all_route_ids(self):
|
|
expected = {
|
|
("gpt-image-2.5-sunburst", "畅速"): "gpt-image-2.5-sunburst-sp",
|
|
("gpt-image-2.5-sunburst", "直连"): "gpt-image-2.5-sunburst-sd",
|
|
("gpt-image-2.5-sunburst", "专线"): "gpt-image-2.5-sunburst",
|
|
("gpt-image-2.5-flare", "畅速"): "gpt-image-2.5-flare-sp",
|
|
("gpt-image-2.5-flare", "直连"): "gpt-image-2.5-flare-sd",
|
|
("gpt-image-2.5-flare", "专线"): "gpt-image-2.5-flare",
|
|
}
|
|
for (model, route), actual_model in expected.items():
|
|
with self.subTest(model=model, route=route):
|
|
self.assertEqual(resolve_gpt_image_model(model, route), actual_model)
|
|
|
|
def test_batch_node_keeps_operational_controls_outside_advanced_inputs(self):
|
|
schema = O1keyGPTImageBatch.define_schema()
|
|
schema.validate()
|
|
self.assert_combo_values_are_strings(schema)
|
|
inputs = {item.id: item for item in schema.inputs}
|
|
|
|
self.assertEqual(inputs["模型"].default, "gpt-image-2.6-sunburst")
|
|
self.assertEqual(inputs["缩放图片"].default, "智能缩放")
|
|
self.assertEqual(inputs["质量"].options, ["高", "中", "低", "自动", "超高", "最高"])
|
|
self.assertNotIn("色彩纠正", inputs)
|
|
self.assertNotIn("内容审查强度", inputs)
|
|
self.assertEqual(
|
|
[item.id for item in schema.inputs],
|
|
[
|
|
"prompt", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量",
|
|
"图片路径数量", "遮罩", "参考图组", "图片输出格式",
|
|
"背景", "图片保存命名规则", "图片保存路径", "缩放图片", "seed",
|
|
"帧数", "帧时长ms",
|
|
],
|
|
)
|
|
self.assertNotIn("并发数", inputs)
|
|
self.assertEqual(
|
|
[item.id for item in _path_option(1).inputs],
|
|
["参考图1(主图)"],
|
|
)
|
|
self.assertEqual(
|
|
[item.id for item in _path_option(2).inputs],
|
|
["参考图1(主图)", "参考图2", "图片配对模式"],
|
|
)
|
|
|
|
for input_name in (
|
|
"seed",
|
|
"图片输出格式",
|
|
"图片保存命名规则",
|
|
"图片保存路径",
|
|
"缩放图片",
|
|
"背景",
|
|
):
|
|
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 = []
|
|
generated = torch.ones((1, 4, 6, 3), dtype=torch.float32)
|
|
|
|
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):
|
|
calls.append(kwargs)
|
|
return [Image.new("RGB", (6, 4), "green")]
|
|
|
|
@staticmethod
|
|
def _pil_list_to_tensor(_images):
|
|
return generated
|
|
|
|
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",
|
|
),
|
|
):
|
|
result = O1keyGPTImage.generate(
|
|
prompt="测试",
|
|
输出格式="webp",
|
|
缩放图片="智能缩放",
|
|
背景="transparent",
|
|
)
|
|
|
|
self.assertIs(result[0], generated)
|
|
self.assertEqual(len(calls), 1)
|
|
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])
|
|
|
|
def test_single_node_forwards_25_quality_api_values(self):
|
|
calls = []
|
|
generated = torch.ones((1, 4, 6, 3), dtype=torch.float32)
|
|
|
|
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):
|
|
calls.append(kwargs)
|
|
return [Image.new("RGB", (6, 4), "green")]
|
|
|
|
@staticmethod
|
|
def _pil_list_to_tensor(_images):
|
|
return generated
|
|
|
|
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",
|
|
),
|
|
):
|
|
for display_quality, api_quality in (("超高", "xhigh"), ("最高", "max")):
|
|
O1keyGPTImage.generate(
|
|
prompt="测试",
|
|
模型="gpt-image-2.5-sunburst",
|
|
质量=display_quality,
|
|
)
|
|
|
|
self.assertEqual([call["quality"] for call in calls], ["xhigh", "max"])
|
|
|
|
|
|
class GPTImageBatchExecutionTests(unittest.IsolatedAsyncioTestCase):
|
|
async def test_batch_task_forwards_request_controls_without_removed_options(self):
|
|
calls = []
|
|
reference = Image.new("RGB", (6, 4), "red")
|
|
generated = Image.new("RGB", (6, 4), "green")
|
|
pair = (ImageInfo(reference, "source", ".png", ""),)
|
|
|
|
class FakeClient:
|
|
async def generate_image_async(self, **kwargs):
|
|
calls.append(kwargs)
|
|
return [generated]
|
|
|
|
with (
|
|
patch.object(
|
|
O1keyGPTImageBatch,
|
|
"_save_images",
|
|
return_value=["output.png"],
|
|
) as save_images,
|
|
patch("builtins.print"),
|
|
):
|
|
result = await O1keyGPTImageBatch._run_task(
|
|
FakeClient(), pair, "测试", 0, 1,
|
|
"gpt-image-2-c-sp", "auto", "1024x1024", 1, 0, None, "webp",
|
|
"transparent", "智能缩放",
|
|
"output", "和原始图片名保持一致", asyncio.Lock(), None,
|
|
)
|
|
|
|
self.assertTrue(result["success"])
|
|
self.assertEqual(calls[0]["resize_mode"], "智能缩放")
|
|
self.assertEqual(calls[0]["background"], "transparent")
|
|
self.assertNotIn("moderation", calls[0])
|
|
self.assertIs(save_images.call_args.args[0][0], generated)
|
|
|
|
async def test_batch_starts_all_tasks_together(self):
|
|
task_count = 4
|
|
started = []
|
|
all_started = asyncio.Event()
|
|
|
|
async def fake_run_task(cls, *_args):
|
|
task_index = _args[3]
|
|
started.append(task_index)
|
|
if len(started) == task_count:
|
|
all_started.set()
|
|
await asyncio.wait_for(all_started.wait(), timeout=1)
|
|
return {
|
|
"task_index": task_index,
|
|
"success": True,
|
|
"generated_count": 1,
|
|
"saved_files": [],
|
|
"error": None,
|
|
}
|
|
|
|
task_defs = [(index, tuple(), f"prompt {index}") for index in range(task_count)]
|
|
with patch.object(O1keyGPTImageBatch, "_run_task", classmethod(fake_run_task)), patch("builtins.print"):
|
|
results = await O1keyGPTImageBatch._process_async(
|
|
object(), task_defs, "model", "auto", "auto", 1, 0,
|
|
None, "png", "auto", "智能缩放", "output",
|
|
"自然数字", None,
|
|
)
|
|
|
|
self.assertEqual(sorted(started), list(range(task_count)))
|
|
self.assertEqual(len(results), task_count)
|
|
self.assertTrue(all(item["success"] for item in results))
|
|
|
|
|
|
class GPTImageDownloadRetryTests(unittest.IsolatedAsyncioTestCase):
|
|
async def test_result_download_retries_transient_http_status_without_logging_url(self):
|
|
buffer = BytesIO()
|
|
Image.new("RGB", (3, 2), "purple").save(buffer, format="PNG")
|
|
image_bytes = buffer.getvalue()
|
|
|
|
class Content:
|
|
def __init__(self, body):
|
|
self.body = body
|
|
|
|
async def iter_chunked(self, _chunk_size):
|
|
yield self.body
|
|
|
|
class Response:
|
|
http_version = "HTTP/1.1"
|
|
|
|
def __init__(self, status, body):
|
|
self.status = status
|
|
self.headers = {"Content-Length": str(len(body))}
|
|
self.content = Content(body)
|
|
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, _exc_type, _exc, _tb):
|
|
return None
|
|
|
|
class Session:
|
|
def __init__(self):
|
|
self.responses = [Response(503, b"busy"), Response(200, image_bytes)]
|
|
self.calls = 0
|
|
|
|
def get(self, _url, **_kwargs):
|
|
response = self.responses[self.calls]
|
|
self.calls += 1
|
|
return response
|
|
|
|
client = object.__new__(GptImageClient)
|
|
session = Session()
|
|
signed_url = "https://example.invalid/private?signature=secret"
|
|
with (
|
|
patch(
|
|
"comfyui_o1key.clients.gpt_image_client.asyncio.sleep",
|
|
new=AsyncMock(),
|
|
),
|
|
patch("builtins.print") as print_mock,
|
|
):
|
|
images, byte_count, _elapsed = await client._download_image_with_response_retry(
|
|
session,
|
|
signed_url,
|
|
"第 1 张图片",
|
|
)
|
|
|
|
self.assertEqual(session.calls, 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
|
|
from comfyui_o1key.utils.o1key_image_catalog import validate_gpt_image_vector_output
|
|
|
|
client = object.__new__(GptImageClient)
|
|
fake = torch.zeros((1, 8, 8, 3))
|
|
with self.assertRaisesRegex(ValueError, "纯文生图"):
|
|
client._build_async_generate_body(
|
|
"test", "gpt-image-2.6-sunburst", "high", None, 1,
|
|
image_list=[fake], output_format="svg",
|
|
)
|
|
# GIF + reference images is allowed (OpenAI image edit guidance).
|
|
validate_gpt_image_vector_output(
|
|
"gpt-image-2.6-sunburst",
|
|
"gif",
|
|
has_images=True,
|
|
has_mask=False,
|
|
)
|
|
with self.assertRaisesRegex(ValueError, "纯文生图"):
|
|
validate_gpt_image_vector_output(
|
|
"gpt-image-2.6-sunburst",
|
|
"svg",
|
|
has_images=False,
|
|
has_mask=True,
|
|
)
|
|
with self.assertRaisesRegex(ValueError, "不支持蒙版"):
|
|
validate_gpt_image_vector_output(
|
|
"gpt-image-2.6-sunburst",
|
|
"gif",
|
|
has_images=True,
|
|
has_mask=True,
|
|
)
|
|
with self.assertRaisesRegex(ValueError, "不支持蒙版"):
|
|
client._build_async_generate_body(
|
|
"test", "gpt-image-2.6-sunburst", "high", None, 1,
|
|
image_list=[fake], mask_tensor=fake, output_format="gif",
|
|
)
|
|
|
|
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()
|