Add MJ image node, GIF save, and Kling/image generator updates
Ship o1key MJ图片生成 with content/style refs and prompt flags, save-GIF with preview, Kling 4.0 helpers, plus GPT/unified image node polish and docs.
This commit is contained in:
@@ -0,0 +1,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()
|
||||
Reference in New Issue
Block a user