Files
Jony a181cc1768 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.
2026-11-09 09:11:12 +08:00

362 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""Thin Midjourney image client on O1Key's shared async generateImage stack."""
from __future__ import annotations
import asyncio
import io
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Callable, List, Optional, Sequence
from PIL import Image
from ..utils.config import get_api_key_or_raise, get_base_url_by_route
from ..utils.http2_client import create_http_client
from ..utils.image_utils import pil_to_tensor, tensor_to_pil
from ..utils.mj_prompt import (
MJ_CONTENT_REF_MAX,
MJ_MODEL_ID,
MJ_STYLE_REF_MAX,
MJ_SW_DEFAULT,
build_mj_prompt,
)
from ..utils.nano_banana_async import (
parse_completed_async_image_task,
poll_async_image_task,
submit_async_image_task,
upload_images_to_temp_urls,
)
MJ_EXPECTED_IMAGE_COUNT = 4
MJ_REFERENCE_MAX_BYTES = 7 * 1024 * 1024
MJ_DEFAULT_TIMEOUT_SECONDS = 180
MJ_NODE_LABEL = "o1key MJ图片生成"
def build_mj_submit_body(
*,
prompt: str,
image_urls: Optional[Sequence[str]] = None,
model: str = MJ_MODEL_ID,
) -> dict[str, Any]:
"""Build the paid Midjourney request body.
API only accepts at most one URL in ``images[]``. Extra content references
must already be embedded in the prompt text.
"""
normalized_prompt = str(prompt or "").strip()
if not normalized_prompt:
raise ValueError("提示词不能为空")
if model != MJ_MODEL_ID:
raise ValueError(f"Midjourney 模型无效:{model}")
urls = [str(url or "").strip() for url in (image_urls or ())]
urls = [url for url in urls if url]
if len(urls) > 1:
raise ValueError("Midjourney images[] 最多 1 张(多内容参考请写入 Prompt)")
if any(not url.startswith("https://") for url in urls):
raise ValueError("Midjourney 参考图必须使用临时素材 HTTPS URL")
body: dict[str, Any] = {
"model": model,
"prompt": normalized_prompt,
}
if urls:
body["images"] = urls
return body
def validate_mj_reference_image(image: Image.Image, *, label: str = "参考图") -> None:
"""Validate Midjourney reference limits before upload."""
if image is None:
raise ValueError(f"{label}为空")
width, height = int(image.width), int(image.height)
if width <= 0 or height <= 0:
raise ValueError(f"{label}尺寸无效:{width}×{height}")
buf = io.BytesIO()
image.save(buf, format="PNG")
size = len(buf.getvalue())
if size > MJ_REFERENCE_MAX_BYTES:
raise ValueError(
f"{label}不能超过 7MB,当前为 {size / 1024 / 1024:.2f}MB"
)
class MjImageClient:
"""Upload content/style refs, submit one MJ task, poll, decode images."""
def __init__(self, *, base_url: Optional[str] = None, api_key: Optional[str] = None):
self.base_url = str(base_url or get_base_url_by_route()).rstrip("/")
self.api_key = api_key or get_api_key_or_raise("O1KEY_API_KEY")
async def generate_async(
self,
*,
session: Any,
prompt: str,
aspect_ratio: str = "1:1",
quality: int = 2,
hd: bool = False,
image_weight: float = 1.0,
raw: bool = False,
stylize: int = 250,
chaos: int = 0,
seed: int = -1,
weird: int = 0,
tile: bool = False,
exp: int = 0,
draft: bool = False,
no_text: str = "",
style_weight: int = MJ_SW_DEFAULT,
images: Optional[Sequence[Image.Image]] = None,
style_images: Optional[Sequence[Image.Image]] = None,
timeout_seconds: int = MJ_DEFAULT_TIMEOUT_SECONDS,
check_interrupt: Optional[Callable[[], None]] = None,
progress_callback: Optional[Callable[[float], None]] = None,
log_downloads: bool = True,
log_task_success: bool = True,
) -> List[Image.Image]:
content_images = list(images or ())
style_refs = list(style_images or ())
if len(content_images) > MJ_CONTENT_REF_MAX:
raise ValueError(f"内容参考图最多 {MJ_CONTENT_REF_MAX} 张")
if len(style_refs) > MJ_STYLE_REF_MAX:
raise ValueError(f"风格参考图最多 {MJ_STYLE_REF_MAX} 张")
for index, image in enumerate(content_images, start=1):
validate_mj_reference_image(image, label=f"参考图{index}")
for index, image in enumerate(style_refs, start=1):
validate_mj_reference_image(image, label=f"风格参考图{index}")
started = time.time()
timeout = max(30, int(timeout_seconds))
def _guard() -> None:
if check_interrupt:
check_interrupt()
elapsed = time.time() - started
if elapsed > timeout:
raise TimeoutError(
f"{MJ_NODE_LABEL} 超时({timeout}秒),请稍后重试或调大「超时秒数」"
)
_guard()
upload_batch = content_images + style_refs
uploaded_urls = await upload_images_to_temp_urls(
session=session,
base_url=self.base_url,
api_key=self.api_key,
images=upload_batch,
node_label=MJ_NODE_LABEL,
check_interrupt=_guard,
log_success=log_task_success,
)
content_urls = list(uploaded_urls[: len(content_images)])
style_urls = list(uploaded_urls[len(content_images) :])
# API images[] accepts only 1 URL; remaining content refs go into prompt.
images_field = content_urls[:1]
prompt_content_urls = content_urls[1:]
assembled = build_mj_prompt(
prompt,
aspect_ratio=aspect_ratio,
quality=quality,
hd=hd,
image_weight=image_weight,
raw=raw,
stylize=stylize,
chaos=chaos,
seed=seed,
has_reference_image=bool(content_urls),
content_ref_urls=prompt_content_urls,
style_ref_urls=style_urls,
style_weight=style_weight,
weird=weird,
tile=tile,
exp=exp,
draft=draft,
no_text=no_text,
)
body = build_mj_submit_body(prompt=assembled, image_urls=images_field)
if log_task_success:
if content_urls and style_urls:
mode = "内容+风格参考"
elif content_urls:
mode = "图生图"
elif style_urls:
mode = "风格参考"
else:
mode = "文生图"
print(
f"[{MJ_NODE_LABEL}] {mode} | model={MJ_MODEL_ID} | "
f"timeout={timeout}s | content_refs={len(content_urls)} | "
f"style_refs={len(style_urls)} | prompt={assembled[:120]}"
f"{'…' if len(assembled) > 120 else ''}"
)
task_id = await submit_async_image_task(
session,
self.base_url,
self.api_key,
body,
MJ_NODE_LABEL,
log_body_enabled=False,
log_success=log_task_success,
)
task_payload = await poll_async_image_task(
session,
self.base_url,
self.api_key,
task_id,
MJ_NODE_LABEL,
check_interrupt=_guard,
log_body_enabled=False,
progress_callback=progress_callback,
log_success=log_task_success,
)
_guard()
task_payload, parsed = await parse_completed_async_image_task(
task_payload,
session,
self.base_url,
self.api_key,
task_id,
MJ_NODE_LABEL,
check_interrupt=_guard,
result_url_callback=None,
log_downloads=log_downloads,
)
if isinstance(parsed, tuple) and len(parsed) == 2:
result_images = parsed[0]
else:
result_images = parsed
if draft:
if len(result_images) < 1:
raise RuntimeError(
f"{MJ_NODE_LABEL} 草稿模式应至少返回 1 张图,"
f"实际返回 {len(result_images)} 张(task_id={task_id})"
)
elif len(result_images) != MJ_EXPECTED_IMAGE_COUNT:
raise RuntimeError(
f"{MJ_NODE_LABEL} 应返回 {MJ_EXPECTED_IMAGE_COUNT} 张图,"
f"实际返回 {len(result_images)} 张(task_id={task_id})"
)
if log_task_success:
print(
f"[{MJ_NODE_LABEL}] 完成 | task_id={task_id} | "
f"生成={len(result_images)} 张 | 耗时={time.time() - started:.1f}s"
)
return list(result_images)
def generate_sync(
self,
*,
prompt: str,
aspect_ratio: str = "1:1",
quality: int = 2,
hd: bool = False,
image_weight: float = 1.0,
raw: bool = False,
stylize: int = 250,
chaos: int = 0,
seed: int = -1,
weird: int = 0,
tile: bool = False,
exp: int = 0,
draft: bool = False,
no_text: str = "",
style_weight: int = MJ_SW_DEFAULT,
images: Optional[Sequence[Image.Image]] = None,
style_images: Optional[Sequence[Image.Image]] = None,
timeout_seconds: int = MJ_DEFAULT_TIMEOUT_SECONDS,
check_interrupt: Optional[Callable[[], None]] = None,
progress_callback: Optional[Callable[[float], None]] = None,
) -> List[Image.Image]:
timeout = max(30, int(timeout_seconds))
async def _run_async() -> List[Image.Image]:
async with create_http_client(
http2=True,
max_connections=8,
max_keepalive_connections=4,
) as session:
return await self.generate_async(
session=session,
prompt=prompt,
aspect_ratio=aspect_ratio,
quality=quality,
hd=hd,
image_weight=image_weight,
raw=raw,
stylize=stylize,
chaos=chaos,
seed=seed,
weird=weird,
tile=tile,
exp=exp,
draft=draft,
no_text=no_text,
style_weight=style_weight,
images=images,
style_images=style_images,
timeout_seconds=timeout,
check_interrupt=check_interrupt,
progress_callback=progress_callback,
)
def _run() -> List[Image.Image]:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(_run_async())
finally:
loop.close()
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(_run)
try:
return future.result(timeout=timeout + 60)
except TimeoutError as exc:
raise TimeoutError(
f"{MJ_NODE_LABEL} 超时({timeout}秒),请稍后重试或调大「超时秒数」"
) from exc
def tensors_to_reference_images(
image_tensor,
*,
max_count: int = MJ_CONTENT_REF_MAX,
label: str = "参考图",
) -> List[Image.Image]:
"""Convert an optional Comfy IMAGE tensor into up to ``max_count`` PIL images."""
if image_tensor is None:
return []
images = tensor_to_pil(image_tensor)
if not images:
return []
if len(images) > max_count:
raise ValueError(f"{label}最多 {max_count} 张(当前输入为 {len(images)} 张)")
return list(images)
def pil_images_to_output_tensor(images: Sequence[Image.Image]):
return pil_to_tensor(list(images))
__all__ = [
"MJ_DEFAULT_TIMEOUT_SECONDS",
"MJ_EXPECTED_IMAGE_COUNT",
"MJ_NODE_LABEL",
"MJ_REFERENCE_MAX_BYTES",
"MjImageClient",
"build_mj_submit_body",
"pil_images_to_output_tensor",
"tensors_to_reference_images",
"validate_mj_reference_image",
]