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,294 @@
|
||||
"""GPT Image 2.6 SVG/GIF result helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from io import BytesIO
|
||||
from typing import Iterable, List, Optional, Sequence
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
|
||||
|
||||
|
||||
def is_svg_bytes(data: bytes) -> bool:
|
||||
if not data:
|
||||
return False
|
||||
head = data.lstrip()[:256].lower()
|
||||
return head.startswith(b"<svg") or head.startswith(b"<?xml") and b"<svg" in head
|
||||
|
||||
|
||||
def is_gif_bytes(data: bytes) -> bool:
|
||||
return bool(data) and (data.startswith(b"GIF87a") or data.startswith(b"GIF89a"))
|
||||
|
||||
|
||||
def expand_gif_frames(image: Image.Image, original_bytes: Optional[bytes] = None) -> List[Image.Image]:
|
||||
"""Return every GIF frame as a standalone RGBA image; keep container bytes on frame 0."""
|
||||
raw = original_bytes if isinstance(original_bytes, bytes) else getattr(image, "_o1key_original_bytes", None)
|
||||
frames: List[Image.Image] = []
|
||||
try:
|
||||
n_frames = int(getattr(image, "n_frames", 1) or 1)
|
||||
except Exception:
|
||||
n_frames = 1
|
||||
if n_frames <= 1 and not getattr(image, "is_animated", False):
|
||||
frame = image.convert("RGBA")
|
||||
if isinstance(raw, bytes):
|
||||
setattr(frame, "_o1key_original_bytes", raw)
|
||||
setattr(frame, "_o1key_original_format", "GIF")
|
||||
frame.format = "GIF"
|
||||
frames.append(frame)
|
||||
return frames
|
||||
|
||||
for index in range(n_frames):
|
||||
try:
|
||||
image.seek(index)
|
||||
except EOFError:
|
||||
break
|
||||
frame = image.copy().convert("RGBA")
|
||||
frame.format = "GIF"
|
||||
if index == 0 and isinstance(raw, bytes):
|
||||
setattr(frame, "_o1key_original_bytes", raw)
|
||||
setattr(frame, "_o1key_original_format", "GIF")
|
||||
setattr(frame, "_o1key_animation_bytes", raw)
|
||||
frames.append(frame)
|
||||
if not frames:
|
||||
raise RuntimeError("GIF 结果无法解码为帧")
|
||||
return frames
|
||||
|
||||
|
||||
def animation_bytes_from_images(images: Iterable[Image.Image]) -> Optional[bytes]:
|
||||
for image in images:
|
||||
raw = getattr(image, "_o1key_animation_bytes", None)
|
||||
if isinstance(raw, bytes) and is_gif_bytes(raw):
|
||||
return raw
|
||||
raw = getattr(image, "_o1key_original_bytes", None)
|
||||
fmt = str(getattr(image, "_o1key_original_format", "") or getattr(image, "format", "") or "").upper()
|
||||
if isinstance(raw, bytes) and (fmt == "GIF" or is_gif_bytes(raw)):
|
||||
return raw
|
||||
return None
|
||||
|
||||
|
||||
def read_gif_bytes_from_path(path: str) -> Optional[bytes]:
|
||||
"""Return GIF bytes from a filesystem path, or None if missing/not a GIF."""
|
||||
text = str(path or "").strip().strip('"').strip("'")
|
||||
if not text:
|
||||
return None
|
||||
if not os.path.isfile(text):
|
||||
return None
|
||||
with open(text, "rb") as handle:
|
||||
data = handle.read()
|
||||
if not is_gif_bytes(data):
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def resolve_gif_frame_duration_ms(fps: float = 5.0, frame_duration_ms: int = 0) -> int:
|
||||
"""Prefer explicit ms; otherwise derive from fps. Clamp to a usable GIF delay."""
|
||||
try:
|
||||
explicit = int(frame_duration_ms or 0)
|
||||
except (TypeError, ValueError):
|
||||
explicit = 0
|
||||
if explicit > 0:
|
||||
return max(20, explicit)
|
||||
try:
|
||||
fps_value = float(fps)
|
||||
except (TypeError, ValueError):
|
||||
fps_value = 5.0
|
||||
if fps_value <= 0:
|
||||
fps_value = 5.0
|
||||
return max(20, int(round(1000.0 / fps_value)))
|
||||
|
||||
|
||||
def encode_gif_from_pil_images(
|
||||
images: Sequence[Image.Image],
|
||||
*,
|
||||
duration_ms: int = 200,
|
||||
loop: int = 0,
|
||||
) -> bytes:
|
||||
"""Encode a batch of PIL images into one animated GIF (fallback path)."""
|
||||
frames = [img.convert("RGBA") for img in images if img is not None]
|
||||
if not frames:
|
||||
raise ValueError("没有可用于编码 GIF 的图像帧")
|
||||
duration = max(20, int(duration_ms or 200))
|
||||
buffer = BytesIO()
|
||||
frames[0].save(
|
||||
buffer,
|
||||
format="GIF",
|
||||
save_all=True,
|
||||
append_images=frames[1:],
|
||||
duration=duration,
|
||||
loop=loop,
|
||||
disposal=2,
|
||||
)
|
||||
data = buffer.getvalue()
|
||||
if not is_gif_bytes(data):
|
||||
raise RuntimeError("GIF 编码失败")
|
||||
return data
|
||||
|
||||
|
||||
def svg_bytes_from_image(image: Image.Image) -> Optional[bytes]:
|
||||
raw = getattr(image, "_o1key_original_bytes", None)
|
||||
fmt = str(getattr(image, "_o1key_original_format", "") or getattr(image, "format", "") or "").upper()
|
||||
if isinstance(raw, bytes) and (fmt == "SVG" or is_svg_bytes(raw)):
|
||||
return raw
|
||||
return None
|
||||
|
||||
|
||||
def _svg_placeholder(svg_bytes: bytes, size: tuple[int, int] = (1024, 1024)) -> Image.Image:
|
||||
image = Image.new("RGBA", size, (245, 247, 250, 255))
|
||||
draw = ImageDraw.Draw(image)
|
||||
draw.rectangle((32, 32, size[0] - 32, size[1] - 32), outline=(80, 110, 180, 255), width=4)
|
||||
try:
|
||||
font = ImageFont.load_default()
|
||||
except Exception:
|
||||
font = None
|
||||
text = "SVG 已保存\n(本机未安装矢量栅格化依赖,显示占位预览)"
|
||||
draw.multiline_text((64, 72), text, fill=(40, 50, 70, 255), font=font, spacing=8)
|
||||
preview = image
|
||||
setattr(preview, "_o1key_original_bytes", svg_bytes)
|
||||
setattr(preview, "_o1key_original_format", "SVG")
|
||||
preview.format = "SVG"
|
||||
return preview
|
||||
|
||||
|
||||
def _rasterize_cairosvg(svg_bytes: bytes) -> Image.Image:
|
||||
import cairosvg # type: ignore
|
||||
|
||||
png_bytes = cairosvg.svg2png(bytestring=svg_bytes)
|
||||
image = Image.open(BytesIO(png_bytes))
|
||||
image.load()
|
||||
return image.convert("RGBA")
|
||||
|
||||
|
||||
def _rasterize_with_cli(svg_bytes: bytes, command_builder) -> Image.Image:
|
||||
with tempfile.TemporaryDirectory(prefix="o1key_svg_") as temp_dir:
|
||||
src = os.path.join(temp_dir, "input.svg")
|
||||
dst = os.path.join(temp_dir, "output.png")
|
||||
with open(src, "wb") as handle:
|
||||
handle.write(svg_bytes)
|
||||
command = command_builder(src, dst)
|
||||
completed = subprocess.run(
|
||||
command,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
timeout=60,
|
||||
)
|
||||
if completed.returncode != 0 or not os.path.isfile(dst):
|
||||
stderr = (completed.stderr or b"").decode("utf-8", errors="replace")
|
||||
raise RuntimeError(stderr or "svg rasterize failed")
|
||||
with Image.open(dst) as image:
|
||||
image.load()
|
||||
return image.convert("RGBA")
|
||||
|
||||
|
||||
def _rasterize_magick(svg_bytes: bytes) -> Image.Image:
|
||||
magick = shutil.which("magick") or shutil.which("convert")
|
||||
if not magick:
|
||||
raise RuntimeError("ImageMagick not found")
|
||||
|
||||
def build(src: str, dst: str):
|
||||
return [magick, src, dst]
|
||||
|
||||
return _rasterize_with_cli(svg_bytes, build)
|
||||
|
||||
|
||||
def _rasterize_inkscape(svg_bytes: bytes) -> Image.Image:
|
||||
inkscape = shutil.which("inkscape")
|
||||
if not inkscape:
|
||||
raise RuntimeError("Inkscape not found")
|
||||
|
||||
def build(src: str, dst: str):
|
||||
return [inkscape, src, "--export-type=png", f"--export-filename={dst}"]
|
||||
|
||||
return _rasterize_with_cli(svg_bytes, build)
|
||||
|
||||
|
||||
def rasterize_svg(svg_bytes: bytes) -> Image.Image:
|
||||
"""Rasterize SVG for IMAGE preview; always preserve original SVG bytes on the result."""
|
||||
if not isinstance(svg_bytes, (bytes, bytearray)) or not svg_bytes:
|
||||
raise ValueError("SVG 数据为空")
|
||||
data = bytes(svg_bytes)
|
||||
last_error: Exception | None = None
|
||||
for renderer in (_rasterize_cairosvg, _rasterize_magick, _rasterize_inkscape):
|
||||
try:
|
||||
image = renderer(data)
|
||||
setattr(image, "_o1key_original_bytes", data)
|
||||
setattr(image, "_o1key_original_format", "SVG")
|
||||
image.format = "SVG"
|
||||
return image
|
||||
except Exception as exc: # pragma: no cover - environment dependent
|
||||
last_error = exc
|
||||
continue
|
||||
preview = _svg_placeholder(data)
|
||||
if last_error is not None:
|
||||
setattr(preview, "_o1key_svg_rasterize_error", str(last_error))
|
||||
return preview
|
||||
|
||||
|
||||
def materialize_result_images(
|
||||
data: bytes,
|
||||
*,
|
||||
requested_format: Optional[str] = None,
|
||||
content_type: Optional[str] = None,
|
||||
) -> List[Image.Image]:
|
||||
"""Turn provider bytes into one or more PIL images for Comfy IMAGE tensors."""
|
||||
if not isinstance(data, (bytes, bytearray)) or not data:
|
||||
raise ValueError("结果图像数据为空")
|
||||
payload = bytes(data)
|
||||
fmt = str(requested_format or "").strip().lower()
|
||||
ctype = str(content_type or "").strip().lower()
|
||||
treat_as_svg = fmt == "svg" or "svg" in ctype or is_svg_bytes(payload)
|
||||
if treat_as_svg:
|
||||
return [rasterize_svg(payload)]
|
||||
|
||||
try:
|
||||
image = Image.open(BytesIO(payload))
|
||||
image.load()
|
||||
except (OSError, UnidentifiedImageError) as exc:
|
||||
if is_svg_bytes(payload):
|
||||
return [rasterize_svg(payload)]
|
||||
raise RuntimeError(f"结果图像无法解码: {exc}") from None
|
||||
|
||||
image_format = str(image.format or "").upper()
|
||||
if image_format == "JPG":
|
||||
image_format = "JPEG"
|
||||
setattr(image, "_o1key_original_bytes", payload)
|
||||
setattr(image, "_o1key_original_format", image_format or None)
|
||||
if image_format:
|
||||
image.format = image_format
|
||||
|
||||
treat_as_gif = fmt == "gif" or image_format == "GIF" or is_gif_bytes(payload)
|
||||
if treat_as_gif:
|
||||
return expand_gif_frames(image, payload)
|
||||
return [image]
|
||||
|
||||
|
||||
def write_bytes_atomic(path: str, data: bytes) -> None:
|
||||
temporary_path = f"{path}.tmp"
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
try:
|
||||
with open(temporary_path, "wb") as handle:
|
||||
handle.write(data)
|
||||
os.replace(temporary_path, path)
|
||||
finally:
|
||||
if os.path.exists(temporary_path):
|
||||
try:
|
||||
os.remove(temporary_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
__all__ = [
|
||||
"animation_bytes_from_images",
|
||||
"encode_gif_from_pil_images",
|
||||
"expand_gif_frames",
|
||||
"is_gif_bytes",
|
||||
"is_svg_bytes",
|
||||
"materialize_result_images",
|
||||
"rasterize_svg",
|
||||
"read_gif_bytes_from_path",
|
||||
"resolve_gif_frame_duration_ms",
|
||||
"svg_bytes_from_image",
|
||||
"write_bytes_atomic",
|
||||
]
|
||||
+13
-4
@@ -404,14 +404,21 @@ def expand_batch_prompt_tasks(prompt: str, images_per_prompt: int) -> List[str]:
|
||||
return [task_prompt for task_prompt in prompts for _ in range(count)]
|
||||
|
||||
|
||||
IMAGE_BATCH_MODE_GROUP_TO_MODELS = "一组搭配+多模特"
|
||||
IMAGE_BATCH_MODE_CARTESIAN = "全部搭配×全部模特"
|
||||
IMAGE_BATCH_MODE_SINGLE_REFERENCES = "单图素材批量"
|
||||
IMAGE_BATCH_MODE_GROUP_TO_MODELS = "整组素材→多个目标"
|
||||
IMAGE_BATCH_MODE_CARTESIAN = "每张素材×每张目标"
|
||||
IMAGE_BATCH_MODE_SINGLE_REFERENCES = "每张素材单独出图"
|
||||
IMAGE_BATCH_MODES = (
|
||||
IMAGE_BATCH_MODE_GROUP_TO_MODELS,
|
||||
IMAGE_BATCH_MODE_CARTESIAN,
|
||||
IMAGE_BATCH_MODE_SINGLE_REFERENCES,
|
||||
)
|
||||
# Labels shipped before the rename. They are accepted so old workflows and queued
|
||||
# jobs keep running, but only the current labels are offered in the combo widget.
|
||||
IMAGE_BATCH_MODE_ALIASES = {
|
||||
"一组搭配+多模特": IMAGE_BATCH_MODE_GROUP_TO_MODELS,
|
||||
"全部搭配×全部模特": IMAGE_BATCH_MODE_CARTESIAN,
|
||||
"单图素材批量": IMAGE_BATCH_MODE_SINGLE_REFERENCES,
|
||||
}
|
||||
|
||||
|
||||
def expand_image_generation_tasks(
|
||||
@@ -436,6 +443,8 @@ def expand_image_generation_tasks(
|
||||
count = int(images_per_pair)
|
||||
if count < 1:
|
||||
raise ValueError("每个组合的生图数量必须大于 0")
|
||||
# Retired labels stay accepted so queued and saved workflows keep running.
|
||||
batch_mode = IMAGE_BATCH_MODE_ALIASES.get(batch_mode, batch_mode)
|
||||
prompts = parse_batch_prompts(prompt) or [prompt.strip()]
|
||||
if not batch_enabled:
|
||||
pairings = [{
|
||||
@@ -451,7 +460,7 @@ def expand_image_generation_tasks(
|
||||
model_total = max(0, int(model_reference_count))
|
||||
if batch_mode == IMAGE_BATCH_MODE_SINGLE_REFERENCES:
|
||||
if outfit_total < 1:
|
||||
raise ValueError("单图批量至少需要上传1张素材图")
|
||||
raise ValueError("每张素材单独出图至少需要上传1张素材图")
|
||||
pairings = [
|
||||
{
|
||||
"reference_indices": (outfit_index,),
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Midjourney prompt helpers for o1key MJ image generation.
|
||||
|
||||
Controlled flags are appended in a stable order. Duplicate user-written copies
|
||||
of the same flags are stripped first so widget values win.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Optional, Sequence
|
||||
|
||||
MJ_MODEL_ID = "mj-v8.2"
|
||||
|
||||
MJ_ASPECT_RATIO_OPTIONS = [
|
||||
"1:1",
|
||||
"16:9",
|
||||
"9:16",
|
||||
"4:5",
|
||||
"3:2",
|
||||
"2:3",
|
||||
"4:3",
|
||||
"21:9",
|
||||
]
|
||||
|
||||
MJ_QUALITY_MIN = 1
|
||||
MJ_QUALITY_MAX = 4
|
||||
MJ_QUALITY_DEFAULT = 2
|
||||
|
||||
MJ_STYLIZE_MIN = 0
|
||||
MJ_STYLIZE_MAX = 1000
|
||||
MJ_STYLIZE_DEFAULT = 250
|
||||
|
||||
MJ_CHAOS_MIN = 0
|
||||
MJ_CHAOS_MAX = 100
|
||||
MJ_CHAOS_DEFAULT = 0
|
||||
|
||||
MJ_IW_MIN = 0.0
|
||||
MJ_IW_MAX = 3.0
|
||||
MJ_IW_DEFAULT = 1.0
|
||||
|
||||
MJ_WEIRD_MIN = 0
|
||||
MJ_WEIRD_MAX = 3000
|
||||
MJ_WEIRD_DEFAULT = 0
|
||||
|
||||
MJ_EXP_MIN = 0
|
||||
MJ_EXP_MAX = 100
|
||||
MJ_EXP_DEFAULT = 0
|
||||
|
||||
MJ_SW_MIN = 0
|
||||
MJ_SW_MAX = 1000
|
||||
MJ_SW_DEFAULT = 100
|
||||
|
||||
MJ_CONTENT_REF_MAX = 4
|
||||
MJ_STYLE_REF_MAX = 4
|
||||
|
||||
# Strip both short and long Midjourney spellings before we append ours.
|
||||
_STRIP_PATTERNS = (
|
||||
re.compile(r"(?i)(?:^|\s)--ar(?:atio)?\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--q(?:uality)?\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--hd\b"),
|
||||
re.compile(r"(?i)(?:^|\s)--iw\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--raw\b"),
|
||||
re.compile(r"(?i)(?:^|\s)--s(?:tylize)?\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--c(?:haos)?\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--seed\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--weird\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--tile\b"),
|
||||
re.compile(r"(?i)(?:^|\s)--exp\s+\S+"),
|
||||
re.compile(r"(?i)(?:^|\s)--draft\b"),
|
||||
re.compile(r"(?i)(?:^|\s)--no(?:\s+(?!--)\S+)+"),
|
||||
re.compile(r"(?i)(?:^|\s)--sref(?:\s+(?!--)\S+)+"),
|
||||
re.compile(r"(?i)(?:^|\s)--sw\s+\S+"),
|
||||
)
|
||||
|
||||
_SPACE_RE = re.compile(r"[ \t]{2,}")
|
||||
|
||||
|
||||
def strip_controlled_mj_flags(prompt: str) -> str:
|
||||
"""Remove controlled Midjourney flags from free-form prompt text."""
|
||||
text = str(prompt or "")
|
||||
for pattern in _STRIP_PATTERNS:
|
||||
text = pattern.sub(" ", text)
|
||||
text = _SPACE_RE.sub(" ", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _format_iw(value: float) -> str:
|
||||
number = float(value)
|
||||
if number.is_integer():
|
||||
return str(int(number))
|
||||
text = f"{number:.3f}".rstrip("0").rstrip(".")
|
||||
return text or "0"
|
||||
|
||||
|
||||
def _normalize_https_urls(urls: Optional[Sequence[str]], *, label: str) -> list[str]:
|
||||
cleaned: list[str] = []
|
||||
for raw in urls or ():
|
||||
url = str(raw or "").strip()
|
||||
if not url:
|
||||
continue
|
||||
if not url.startswith("https://"):
|
||||
raise ValueError(f"{label}必须使用临时素材 HTTPS URL")
|
||||
cleaned.append(url)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _prefix_content_ref_urls(base: str, urls: Sequence[str]) -> str:
|
||||
"""Prepend content-reference URLs that are not already present in the text."""
|
||||
extras: list[str] = []
|
||||
for url in urls:
|
||||
if url and url not in base:
|
||||
extras.append(url)
|
||||
if not extras:
|
||||
return base
|
||||
if not base:
|
||||
return " ".join(extras)
|
||||
return " ".join(extras + [base])
|
||||
|
||||
|
||||
def build_mj_prompt(
|
||||
prompt: str,
|
||||
*,
|
||||
aspect_ratio: str = "1:1",
|
||||
quality: int = MJ_QUALITY_DEFAULT,
|
||||
hd: bool = False,
|
||||
image_weight: Optional[float] = None,
|
||||
raw: bool = False,
|
||||
stylize: int = MJ_STYLIZE_DEFAULT,
|
||||
chaos: int = MJ_CHAOS_DEFAULT,
|
||||
seed: int = -1,
|
||||
has_reference_image: bool = False,
|
||||
content_ref_urls: Optional[Sequence[str]] = None,
|
||||
style_ref_urls: Optional[Sequence[str]] = None,
|
||||
style_weight: int = MJ_SW_DEFAULT,
|
||||
weird: int = MJ_WEIRD_DEFAULT,
|
||||
tile: bool = False,
|
||||
exp: int = MJ_EXP_DEFAULT,
|
||||
draft: bool = False,
|
||||
no_text: str = "",
|
||||
) -> str:
|
||||
"""Assemble the final Midjourney prompt with controlled trailing flags.
|
||||
|
||||
Stable order:
|
||||
``[content_ref_urls...] [base_prompt] [--no ...] --ar --q [--hd] [--iw]
|
||||
[--sref ...] [--sw] [--raw] --s [--c] [--weird] [--tile] [--exp]
|
||||
[--draft] [--seed]``
|
||||
"""
|
||||
base = strip_controlled_mj_flags(prompt)
|
||||
if not base:
|
||||
raise ValueError("提示词不能为空")
|
||||
|
||||
ratio = str(aspect_ratio or "").strip()
|
||||
if ratio not in MJ_ASPECT_RATIO_OPTIONS:
|
||||
raise ValueError(f"画面比例无效:{aspect_ratio}")
|
||||
|
||||
quality_value = int(quality)
|
||||
if quality_value < MJ_QUALITY_MIN or quality_value > MJ_QUALITY_MAX:
|
||||
raise ValueError(f"渲染质量须为 {MJ_QUALITY_MIN}–{MJ_QUALITY_MAX}")
|
||||
|
||||
stylize_value = int(stylize)
|
||||
if stylize_value < MJ_STYLIZE_MIN or stylize_value > MJ_STYLIZE_MAX:
|
||||
raise ValueError(f"风格化须为 {MJ_STYLIZE_MIN}–{MJ_STYLIZE_MAX}")
|
||||
|
||||
chaos_value = int(chaos)
|
||||
if chaos_value < MJ_CHAOS_MIN or chaos_value > MJ_CHAOS_MAX:
|
||||
raise ValueError(f"差异度须为 {MJ_CHAOS_MIN}–{MJ_CHAOS_MAX}")
|
||||
|
||||
weird_value = int(weird)
|
||||
if weird_value < MJ_WEIRD_MIN or weird_value > MJ_WEIRD_MAX:
|
||||
raise ValueError(f"怪异度须为 {MJ_WEIRD_MIN}–{MJ_WEIRD_MAX}")
|
||||
|
||||
exp_value = int(exp)
|
||||
if exp_value < MJ_EXP_MIN or exp_value > MJ_EXP_MAX:
|
||||
raise ValueError(f"实验值须为 {MJ_EXP_MIN}–{MJ_EXP_MAX}")
|
||||
|
||||
prompt_content_urls = _normalize_https_urls(
|
||||
content_ref_urls, label="内容参考图"
|
||||
)
|
||||
style_urls = _normalize_https_urls(style_ref_urls, label="风格参考图")
|
||||
|
||||
text_body = _prefix_content_ref_urls(base, prompt_content_urls)
|
||||
|
||||
no_value = str(no_text or "").strip()
|
||||
parts: list[str] = [text_body]
|
||||
if no_value:
|
||||
parts.append(f"--no {no_value}")
|
||||
|
||||
parts.extend([f"--ar {ratio}", f"--q {quality_value}"])
|
||||
if hd:
|
||||
parts.append("--hd")
|
||||
|
||||
if has_reference_image or prompt_content_urls:
|
||||
if image_weight is None:
|
||||
iw_value = MJ_IW_DEFAULT
|
||||
else:
|
||||
iw_value = float(image_weight)
|
||||
if iw_value < MJ_IW_MIN or iw_value > MJ_IW_MAX:
|
||||
raise ValueError(f"参考图权重须为 {MJ_IW_MIN:g}–{MJ_IW_MAX:g}")
|
||||
parts.append(f"--iw {_format_iw(iw_value)}")
|
||||
|
||||
if style_urls:
|
||||
parts.append("--sref " + " ".join(style_urls))
|
||||
sw_value = int(style_weight)
|
||||
if sw_value < MJ_SW_MIN or sw_value > MJ_SW_MAX:
|
||||
raise ValueError(f"风格权重须为 {MJ_SW_MIN}–{MJ_SW_MAX}")
|
||||
parts.append(f"--sw {sw_value}")
|
||||
|
||||
if raw:
|
||||
parts.append("--raw")
|
||||
|
||||
parts.append(f"--s {stylize_value}")
|
||||
|
||||
if chaos_value > 0:
|
||||
parts.append(f"--c {chaos_value}")
|
||||
|
||||
if weird_value > 0:
|
||||
parts.append(f"--weird {weird_value}")
|
||||
|
||||
if tile:
|
||||
parts.append("--tile")
|
||||
|
||||
if exp_value > 0:
|
||||
parts.append(f"--exp {exp_value}")
|
||||
|
||||
if draft:
|
||||
parts.append("--draft")
|
||||
|
||||
seed_value = int(seed)
|
||||
if seed_value >= 0:
|
||||
parts.append(f"--seed {seed_value}")
|
||||
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MJ_ASPECT_RATIO_OPTIONS",
|
||||
"MJ_CHAOS_DEFAULT",
|
||||
"MJ_CHAOS_MAX",
|
||||
"MJ_CHAOS_MIN",
|
||||
"MJ_CONTENT_REF_MAX",
|
||||
"MJ_EXP_DEFAULT",
|
||||
"MJ_EXP_MAX",
|
||||
"MJ_EXP_MIN",
|
||||
"MJ_IW_DEFAULT",
|
||||
"MJ_IW_MAX",
|
||||
"MJ_IW_MIN",
|
||||
"MJ_MODEL_ID",
|
||||
"MJ_QUALITY_DEFAULT",
|
||||
"MJ_QUALITY_MAX",
|
||||
"MJ_QUALITY_MIN",
|
||||
"MJ_STYLE_REF_MAX",
|
||||
"MJ_STYLIZE_DEFAULT",
|
||||
"MJ_STYLIZE_MAX",
|
||||
"MJ_STYLIZE_MIN",
|
||||
"MJ_SW_DEFAULT",
|
||||
"MJ_SW_MAX",
|
||||
"MJ_SW_MIN",
|
||||
"MJ_WEIRD_DEFAULT",
|
||||
"MJ_WEIRD_MAX",
|
||||
"MJ_WEIRD_MIN",
|
||||
"build_mj_prompt",
|
||||
"strip_controlled_mj_flags",
|
||||
]
|
||||
@@ -9,16 +9,17 @@ from .nano_banana_models import (
|
||||
|
||||
|
||||
GPT_IMAGE_MODEL_OPTIONS = [
|
||||
"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_MODEL_OPTIONS = ["Seedream 5.0 Pro"]
|
||||
UNIFIED_IMAGE_MODEL_OPTIONS = [
|
||||
*NANO_BANANA_MODEL_OPTIONS[:3],
|
||||
*GPT_IMAGE_MODEL_OPTIONS,
|
||||
*SEEDREAM_MODEL_OPTIONS,
|
||||
*NANO_BANANA_MODEL_OPTIONS[3:],
|
||||
]
|
||||
UNIFIED_IMAGE_ROUTE_OPTIONS = list(NANO_BANANA_ROUTE_OPTIONS)
|
||||
|
||||
@@ -65,8 +66,30 @@ GPT_IMAGE_EXACT_SIZE_OPTIONS = [
|
||||
]
|
||||
GPT_IMAGE_QUALITY_OPTIONS = ["高", "中", "低", "自动"]
|
||||
GPT_IMAGE_25_QUALITY_OPTIONS = [*GPT_IMAGE_QUALITY_OPTIONS, "超高", "最高"]
|
||||
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS = ["jpeg", "png", "webp"]
|
||||
GPT_IMAGE_COMPLEXITY_OPTIONS = ["高", "中", "低"]
|
||||
GPT_IMAGE_COMPLEXITY_API_VALUES = ("low", "medium", "high")
|
||||
GPT_IMAGE_COMPLEXITY_LABEL_TO_API = {
|
||||
"高": "high",
|
||||
"中": "medium",
|
||||
"低": "low",
|
||||
"high": "high",
|
||||
"medium": "medium",
|
||||
"low": "low",
|
||||
}
|
||||
GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS = ["jpeg", "png", "webp"]
|
||||
GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS = ["svg", "gif"]
|
||||
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS = list(GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS)
|
||||
GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS = [
|
||||
*GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS,
|
||||
*GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS,
|
||||
]
|
||||
GPT_IMAGE_BACKGROUND_OPTIONS = ["auto", "transparent", "opaque"]
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT = 9
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MIN = 2
|
||||
GPT_IMAGE_GIF_FRAME_COUNT_MAX = 64
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT = 200
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MIN = 20
|
||||
GPT_IMAGE_GIF_FRAME_DURATION_MAX = 2000
|
||||
GPT_IMAGE_SIZE_MATRIX = {
|
||||
("1K", "1:1"): "1024x1024",
|
||||
("1K", "3:2"): "1536x1024",
|
||||
@@ -117,6 +140,80 @@ SEEDREAM_SIZE_MATRIX = {
|
||||
}
|
||||
|
||||
|
||||
|
||||
def is_gpt_image_26_model(model: str) -> bool:
|
||||
name = str(model or "").strip()
|
||||
if name in GPT_IMAGE_MODEL_OPTIONS:
|
||||
return name.startswith("gpt-image-2.6-")
|
||||
for base in GPT_IMAGE_MODEL_OPTIONS:
|
||||
if name in {base, f"{base}-sp", f"{base}-sd"}:
|
||||
return base.startswith("gpt-image-2.6-")
|
||||
return name.startswith("gpt-image-2.6-")
|
||||
|
||||
|
||||
def gpt_image_output_formats_for_model(model: str) -> list[str]:
|
||||
if is_gpt_image_26_model(model):
|
||||
return list(GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS)
|
||||
return list(GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS)
|
||||
|
||||
|
||||
def resolve_gpt_image_output_format(model: str, output_format: str | None) -> str:
|
||||
value = str(output_format or "png").strip().lower()
|
||||
allowed = gpt_image_output_formats_for_model(model)
|
||||
if value not in allowed:
|
||||
if value in GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS:
|
||||
raise ValueError("SVG / GIF 输出仅支持 GPT Image 2.6 系列模型")
|
||||
raise ValueError("GPT Image 输出格式无效")
|
||||
return value
|
||||
|
||||
|
||||
def resolve_gpt_image_frame_count(output_format: str, frame_count=None) -> int | None:
|
||||
if str(output_format or "").strip().lower() != "gif":
|
||||
return None
|
||||
if frame_count is None or frame_count == "":
|
||||
return GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT
|
||||
try:
|
||||
value = int(frame_count)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("GIF 帧数无效") from exc
|
||||
if value < GPT_IMAGE_GIF_FRAME_COUNT_MIN or value > GPT_IMAGE_GIF_FRAME_COUNT_MAX:
|
||||
raise ValueError(
|
||||
f"GIF 帧数仅支持 {GPT_IMAGE_GIF_FRAME_COUNT_MIN}–{GPT_IMAGE_GIF_FRAME_COUNT_MAX}"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def resolve_gpt_image_frame_duration_ms(output_format: str, frame_duration_ms=None) -> int | None:
|
||||
if str(output_format or "").strip().lower() != "gif":
|
||||
return None
|
||||
if frame_duration_ms is None or frame_duration_ms == "":
|
||||
value = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT
|
||||
else:
|
||||
try:
|
||||
value = int(frame_duration_ms)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("GIF 帧时长无效") from exc
|
||||
if value < GPT_IMAGE_GIF_FRAME_DURATION_MIN or value > GPT_IMAGE_GIF_FRAME_DURATION_MAX:
|
||||
raise ValueError(
|
||||
f"GIF 帧时长仅支持 {GPT_IMAGE_GIF_FRAME_DURATION_MIN}–{GPT_IMAGE_GIF_FRAME_DURATION_MAX} 毫秒"
|
||||
)
|
||||
return int(round(value / 10.0) * 10)
|
||||
|
||||
|
||||
def validate_gpt_image_vector_output(
|
||||
model: str,
|
||||
output_format: str,
|
||||
*,
|
||||
has_images: bool = False,
|
||||
has_mask: bool = False,
|
||||
) -> None:
|
||||
fmt = resolve_gpt_image_output_format(model, output_format)
|
||||
if fmt not in GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS:
|
||||
return
|
||||
if has_images or has_mask:
|
||||
raise ValueError("SVG / GIF 仅支持纯文生图,不能带参考图或蒙版")
|
||||
|
||||
|
||||
def is_gpt_image_model(model: str) -> bool:
|
||||
return model in GPT_IMAGE_MODEL_OPTIONS
|
||||
|
||||
@@ -124,8 +221,8 @@ def is_gpt_image_model(model: str) -> bool:
|
||||
def resolve_gpt_image_quality(model_name: str, quality: str) -> str:
|
||||
"""Resolve a displayed GPT quality for the selected model family."""
|
||||
if quality in {"超高", "最高"}:
|
||||
if model_name not in GPT_IMAGE_MODEL_OPTIONS or not model_name.startswith("gpt-image-2.5-"):
|
||||
raise ValueError("超高和最高质量仅支持 GPT Image 2.5 系列模型")
|
||||
if model_name not in GPT_IMAGE_MODEL_OPTIONS or not model_name.startswith(("gpt-image-2.5-", "gpt-image-2.6-")):
|
||||
raise ValueError("超高和最高质量仅支持 GPT Image 2.5 / 2.6 系列模型")
|
||||
return {"超高": "xhigh", "最高": "max"}[quality]
|
||||
try:
|
||||
return {"高": "high", "中": "medium", "低": "low", "自动": "auto"}[quality]
|
||||
@@ -133,6 +230,19 @@ def resolve_gpt_image_quality(model_name: str, quality: str) -> str:
|
||||
raise ValueError("GPT Image 质量参数无效") from None
|
||||
|
||||
|
||||
def resolve_gpt_image_complexity(model_name: str, complexity: str | None) -> str | None:
|
||||
"""Only 2.6 models send complexity; inactive controls retain their value."""
|
||||
if model_name not in GPT_IMAGE_MODEL_OPTIONS or not model_name.startswith("gpt-image-2.6-"):
|
||||
return None
|
||||
if complexity is None:
|
||||
return "high"
|
||||
raw = str(complexity).strip()
|
||||
value = GPT_IMAGE_COMPLEXITY_LABEL_TO_API.get(raw) or GPT_IMAGE_COMPLEXITY_LABEL_TO_API.get(raw.lower())
|
||||
if value not in GPT_IMAGE_COMPLEXITY_API_VALUES:
|
||||
raise ValueError("GPT Image 复杂度仅支持 低 / 中 / 高")
|
||||
return value
|
||||
|
||||
|
||||
def is_seedream_model(model: str) -> bool:
|
||||
return model in SEEDREAM_MODEL_OPTIONS
|
||||
|
||||
@@ -200,6 +310,10 @@ __all__ = [
|
||||
"GPT_IMAGE_ASPECT_RATIO_OPTIONS",
|
||||
"GPT_IMAGE_BACKGROUND_OPTIONS",
|
||||
"GPT_IMAGE_COUNTS",
|
||||
"GPT_IMAGE_COMPLEXITY_OPTIONS",
|
||||
"GPT_IMAGE_COMPLEXITY_API_VALUES",
|
||||
"GPT_IMAGE_COMPLEXITY_LABEL_TO_API",
|
||||
"resolve_gpt_image_complexity",
|
||||
"GPT_IMAGE_EXACT_SIZE_OPTIONS",
|
||||
"GPT_IMAGE_MODEL_OPTIONS",
|
||||
"GPT_IMAGE_25_QUALITY_OPTIONS",
|
||||
@@ -226,4 +340,19 @@ __all__ = [
|
||||
"resolve_gpt_image_quality",
|
||||
"resolve_seedream_size",
|
||||
"resolve_seedream_layer_size",
|
||||
"GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS",
|
||||
"GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS",
|
||||
"GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT",
|
||||
"GPT_IMAGE_GIF_FRAME_COUNT_MAX",
|
||||
"GPT_IMAGE_GIF_FRAME_COUNT_MIN",
|
||||
"GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT",
|
||||
"GPT_IMAGE_GIF_FRAME_DURATION_MAX",
|
||||
"GPT_IMAGE_GIF_FRAME_DURATION_MIN",
|
||||
"GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS",
|
||||
"gpt_image_output_formats_for_model",
|
||||
"is_gpt_image_26_model",
|
||||
"resolve_gpt_image_frame_count",
|
||||
"resolve_gpt_image_frame_duration_ms",
|
||||
"resolve_gpt_image_output_format",
|
||||
"validate_gpt_image_vector_output",
|
||||
]
|
||||
|
||||
+114
-30
@@ -21,6 +21,11 @@ from .o1key_image_catalog import (
|
||||
BANANA_RESOLUTION_OPTIONS,
|
||||
GPT_IMAGE_ASPECT_RATIO_OPTIONS,
|
||||
GPT_IMAGE_BACKGROUND_OPTIONS,
|
||||
resolve_gpt_image_complexity,
|
||||
resolve_gpt_image_frame_count,
|
||||
resolve_gpt_image_frame_duration_ms,
|
||||
resolve_gpt_image_output_format,
|
||||
validate_gpt_image_vector_output,
|
||||
GPT_IMAGE_EXACT_SIZE_OPTIONS,
|
||||
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
|
||||
GPT_IMAGE_COUNTS,
|
||||
@@ -44,11 +49,13 @@ from .o1key_image_catalog import (
|
||||
)
|
||||
from .http_error import format_o1key_image_error
|
||||
from .image_utils import (
|
||||
IMAGE_BATCH_MODE_ALIASES,
|
||||
IMAGE_BATCH_MODE_GROUP_TO_MODELS,
|
||||
IMAGE_BATCH_MODE_SINGLE_REFERENCES,
|
||||
IMAGE_BATCH_MODES,
|
||||
expand_image_generation_tasks,
|
||||
)
|
||||
from .gpt_image_media import animation_bytes_from_images, svg_bytes_from_image, write_bytes_atomic
|
||||
from .o1key_image_save import (
|
||||
DEFAULT_SAVE_NAMING_RULE,
|
||||
detect_image_format,
|
||||
@@ -341,7 +348,7 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
|
||||
payload.get("resolution") or UNIFIED_IMAGE_SMART_RESOLUTION
|
||||
).strip()
|
||||
aspect_ratio = str(payload.get("aspect_ratio") or "智能").strip()
|
||||
thinking = str(payload.get("thinking_level") or "低").strip()
|
||||
thinking = str(payload.get("thinking_level") or "高").strip()
|
||||
if model not in MODELS:
|
||||
raise ValueError("模型无效")
|
||||
if model_route not in MODEL_ROUTES:
|
||||
@@ -349,7 +356,7 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
|
||||
google_search = model in {"Nano Banana 2.1", "Nano Banana 2"} and payload.get("google_search") is True
|
||||
quality = str(payload.get("quality") or "自动").strip()
|
||||
resize_mode = str(
|
||||
payload.get("resize_mode") or ("智能缩放" if is_gpt_image_model(model) else "不缩放")
|
||||
payload.get("resize_mode") or "智能缩放"
|
||||
).strip()
|
||||
if resize_mode not in {"不缩放", "智能缩放"}:
|
||||
raise ValueError("缩放图片参数无效")
|
||||
@@ -366,13 +373,17 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
|
||||
raise ValueError("GPT Image 分辨率无效")
|
||||
if aspect_ratio not in GPT_IMAGE_ASPECT_RATIO_OPTIONS:
|
||||
raise ValueError("GPT Image 宽高比无效")
|
||||
complexity = resolve_gpt_image_complexity(model, payload.get("complexity"))
|
||||
resolve_gpt_image_quality(model, quality)
|
||||
if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS:
|
||||
raise ValueError("GPT Image 输出格式无效")
|
||||
output_format = resolve_gpt_image_output_format(model, output_format)
|
||||
if background not in GPT_IMAGE_BACKGROUND_OPTIONS:
|
||||
raise ValueError("GPT Image 背景参数无效")
|
||||
if background == "transparent" and output_format == "jpeg":
|
||||
if background == "transparent" and output_format not in {"png", "webp"}:
|
||||
raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式")
|
||||
frame_count = resolve_gpt_image_frame_count(output_format, payload.get("frame_count"))
|
||||
frame_duration_ms = resolve_gpt_image_frame_duration_ms(
|
||||
output_format, payload.get("frame_duration_ms")
|
||||
)
|
||||
elif is_seedream_model(model):
|
||||
output_format = str(
|
||||
payload.get("output_format") or ("png" if layer_decomposition else "jpeg")
|
||||
@@ -437,6 +448,8 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
|
||||
batch_mode = str(
|
||||
payload.get("batch_mode") or IMAGE_BATCH_MODE_GROUP_TO_MODELS
|
||||
).strip()
|
||||
# Retired labels are still accepted so already-queued jobs keep their pairing.
|
||||
batch_mode = IMAGE_BATCH_MODE_ALIASES.get(batch_mode, batch_mode)
|
||||
if batch_enabled and batch_mode not in IMAGE_BATCH_MODES:
|
||||
raise ValueError("批量模式无效")
|
||||
if not batch_enabled:
|
||||
@@ -558,8 +571,20 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
|
||||
"layer_decomposition": layer_decomposition,
|
||||
}
|
||||
if is_gpt_image_model(model):
|
||||
validate_gpt_image_vector_output(
|
||||
model,
|
||||
output_format,
|
||||
has_images=bool(safe_references) or bool(safe_model_references),
|
||||
has_mask=bool(safe_mask),
|
||||
)
|
||||
job["output_format"] = output_format
|
||||
job["background"] = background
|
||||
if complexity is not None:
|
||||
job["complexity"] = complexity
|
||||
if frame_count is not None:
|
||||
job["frame_count"] = frame_count
|
||||
if frame_duration_ms is not None:
|
||||
job["frame_duration_ms"] = frame_duration_ms
|
||||
elif is_seedream_model(model):
|
||||
job["output_format"] = output_format
|
||||
elif google_search:
|
||||
@@ -762,8 +787,13 @@ def _provider_result_format(image: Image.Image) -> str:
|
||||
detected = detect_image_format(raw) if isinstance(raw, bytes) else None
|
||||
if detected == "JPEG":
|
||||
return "jpg"
|
||||
if detected in {"PNG", "WEBP"}:
|
||||
if detected in {"PNG", "WEBP", "GIF", "SVG"}:
|
||||
return detected.lower()
|
||||
hinted = str(getattr(image, "_o1key_original_format", "") or getattr(image, "format", "") or "").upper()
|
||||
if hinted == "JPEG":
|
||||
return "jpg"
|
||||
if hinted in {"PNG", "WEBP", "GIF", "SVG"}:
|
||||
return hinted.lower()
|
||||
return "png"
|
||||
|
||||
|
||||
@@ -773,7 +803,7 @@ def _write_provider_result(image: Image.Image, output_path: str) -> None:
|
||||
detected = detect_image_format(raw) if isinstance(raw, bytes) else None
|
||||
temporary_path = f"{output_path}.tmp"
|
||||
try:
|
||||
if detected in {"PNG", "JPEG", "WEBP"}:
|
||||
if detected in {"PNG", "JPEG", "WEBP", "GIF", "SVG"}:
|
||||
with open(temporary_path, "wb") as handle:
|
||||
handle.write(raw)
|
||||
else:
|
||||
@@ -1066,6 +1096,7 @@ async def _execute_gpt_image_job(
|
||||
|
||||
actual_model = resolve_gpt_image_model(job["model"], job["model_route"])
|
||||
quality = resolve_gpt_image_quality(job["model"], job["quality"])
|
||||
complexity = resolve_gpt_image_complexity(job["model"], job.get("complexity"))
|
||||
client = GptImageClient()
|
||||
client.base_url = get_base_url_by_route()
|
||||
client.response_log_enabled = False
|
||||
@@ -1170,6 +1201,11 @@ async def _execute_gpt_image_job(
|
||||
started_at = time.monotonic()
|
||||
heartbeat = asyncio.create_task(_heartbeat())
|
||||
try:
|
||||
frame_kwargs = {}
|
||||
if job.get("frame_count") is not None:
|
||||
frame_kwargs["frame_count"] = job["frame_count"]
|
||||
if job.get("frame_duration_ms") is not None:
|
||||
frame_kwargs["frame_duration_ms"] = job["frame_duration_ms"]
|
||||
images = await client.generate_image_async(
|
||||
prompt=job["task_prompts"][request_index],
|
||||
model=actual_model,
|
||||
@@ -1187,6 +1223,8 @@ async def _execute_gpt_image_job(
|
||||
mask_tensor=mask_tensor,
|
||||
output_format=job["output_format"],
|
||||
background=job["background"],
|
||||
**({"complexity": complexity} if complexity is not None else {}),
|
||||
**frame_kwargs,
|
||||
resize_mode=job["resize_mode"],
|
||||
progress_callback=lambda value: _update_request_progress(
|
||||
request_index,
|
||||
@@ -1209,30 +1247,76 @@ async def _execute_gpt_image_job(
|
||||
if not images:
|
||||
raise RuntimeError(f"第 {request_index + 1} 次请求没有返回图片")
|
||||
_update_request_progress(request_index, 0.96)
|
||||
selected = images[0]
|
||||
filename = _result_filename(
|
||||
job,
|
||||
request_index,
|
||||
0,
|
||||
_provider_result_format(selected),
|
||||
)
|
||||
target = os.path.join(output_path, filename)
|
||||
await asyncio.to_thread(
|
||||
_write_provider_result,
|
||||
selected,
|
||||
target,
|
||||
)
|
||||
descriptor = {
|
||||
"filename": filename,
|
||||
"subfolder": relative_subfolder,
|
||||
"type": "temp",
|
||||
"batch_id": job["batch_id"],
|
||||
"request_index": request_index + 1,
|
||||
"result_index": 1,
|
||||
}
|
||||
_publish_partial_images(progress_callback, [descriptor])
|
||||
descriptors: list[dict[str, Any]] = []
|
||||
anim = animation_bytes_from_images(images)
|
||||
svg = svg_bytes_from_image(images[0])
|
||||
if anim is not None:
|
||||
filename = _result_filename(job, request_index, 0, "gif")
|
||||
target = os.path.join(output_path, filename)
|
||||
await asyncio.to_thread(write_bytes_atomic, target, anim)
|
||||
descriptors.append({
|
||||
"filename": filename,
|
||||
"subfolder": relative_subfolder,
|
||||
"type": "temp",
|
||||
"batch_id": job["batch_id"],
|
||||
"request_index": request_index + 1,
|
||||
"result_index": 1,
|
||||
"media": "gif",
|
||||
})
|
||||
elif svg is not None:
|
||||
svg_name = _result_filename(job, request_index, 0, "svg")
|
||||
svg_target = os.path.join(output_path, svg_name)
|
||||
await asyncio.to_thread(write_bytes_atomic, svg_target, svg)
|
||||
# Raster preview for Comfy IMAGE / native preview pipelines.
|
||||
preview = images[0]
|
||||
# Ensure preview file is PNG bytes, not SVG container.
|
||||
from io import BytesIO
|
||||
buf = BytesIO()
|
||||
preview.convert("RGBA").save(buf, format="PNG", compress_level=4)
|
||||
png_bytes = buf.getvalue()
|
||||
png_name = _result_filename(job, request_index, 1, "png")
|
||||
png_target = os.path.join(output_path, png_name)
|
||||
await asyncio.to_thread(write_bytes_atomic, png_target, png_bytes)
|
||||
descriptors.append({
|
||||
"filename": png_name,
|
||||
"subfolder": relative_subfolder,
|
||||
"type": "temp",
|
||||
"batch_id": job["batch_id"],
|
||||
"request_index": request_index + 1,
|
||||
"result_index": 1,
|
||||
"media": "image",
|
||||
"svg_filename": svg_name,
|
||||
})
|
||||
descriptors.append({
|
||||
"filename": svg_name,
|
||||
"subfolder": relative_subfolder,
|
||||
"type": "temp",
|
||||
"batch_id": job["batch_id"],
|
||||
"request_index": request_index + 1,
|
||||
"result_index": 2,
|
||||
"media": "svg",
|
||||
})
|
||||
else:
|
||||
selected = images[0]
|
||||
filename = _result_filename(
|
||||
job,
|
||||
request_index,
|
||||
0,
|
||||
_provider_result_format(selected),
|
||||
)
|
||||
target = os.path.join(output_path, filename)
|
||||
await asyncio.to_thread(_write_provider_result, selected, target)
|
||||
descriptors.append({
|
||||
"filename": filename,
|
||||
"subfolder": relative_subfolder,
|
||||
"type": "temp",
|
||||
"batch_id": job["batch_id"],
|
||||
"request_index": request_index + 1,
|
||||
"result_index": 1,
|
||||
})
|
||||
_publish_partial_images(progress_callback, descriptors)
|
||||
_update_request_progress(request_index, 1.0)
|
||||
return [descriptor]
|
||||
return descriptors
|
||||
finally:
|
||||
for image in images:
|
||||
image.close()
|
||||
|
||||
@@ -24,7 +24,8 @@ from PIL.PngImagePlugin import PngInfo
|
||||
SAVE_FORMAT_OPTIONS = ("原始", "png", "jpg", "webp")
|
||||
SAVE_NAMING_RULE_OPTIONS = ("和主图一致", "自然数字", "自定义前缀")
|
||||
DEFAULT_SAVE_NAMING_RULE = "自定义前缀"
|
||||
_FORMAT_EXTENSIONS = {"PNG": "png", "JPEG": "jpg", "WEBP": "webp"}
|
||||
_FORMAT_EXTENSIONS = {"PNG": "png", "JPEG": "jpg", "WEBP": "webp", "GIF": "gif"}
|
||||
_TEMP_RESULT_FORMATS = frozenset(_FORMAT_EXTENSIONS) # GIF kept as original bytes when 原始
|
||||
_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
_SAVE_LOCK = threading.Lock()
|
||||
_UNSAFE_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
|
||||
@@ -107,6 +108,11 @@ def detect_image_format(data: bytes) -> str | None:
|
||||
return "JPEG"
|
||||
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return "WEBP"
|
||||
if data.startswith(b"GIF87a") or data.startswith(b"GIF89a"):
|
||||
return "GIF"
|
||||
head = data.lstrip()[:256].lower() if data else b""
|
||||
if head.startswith(b"<svg") or (head.startswith(b"<?xml") and b"<svg" in head):
|
||||
return "SVG"
|
||||
return None
|
||||
|
||||
|
||||
@@ -458,12 +464,20 @@ def _save_sources(
|
||||
"jpg": "JPEG",
|
||||
"webp": "WEBP",
|
||||
}[selected]
|
||||
# Never re-encode GIF into itself via Pillow; keep provider bytes.
|
||||
if selected == "原始" and source_format == "GIF" and isinstance(raw, bytes) and detect_image_format(raw) == "GIF":
|
||||
target_format = "GIF"
|
||||
if target_format not in _FORMAT_EXTENSIONS:
|
||||
target_format = "PNG"
|
||||
if target_format == "JPEG" and _has_workflow_metadata(extra_pnginfo):
|
||||
target_format = "PNG"
|
||||
# GIF has no workflow metadata container in this pack; keep bytes intact.
|
||||
if target_format == "GIF" and (not isinstance(raw, bytes) or detect_image_format(raw) != "GIF"):
|
||||
raise ValueError("GIF 结果缺少原始字节,无法原样保存")
|
||||
extension = _FORMAT_EXTENSIONS[target_format]
|
||||
if selected == "原始" and raw is not None and detect_image_format(raw) == target_format:
|
||||
if target_format == "GIF":
|
||||
encoded = raw
|
||||
elif selected == "原始" and raw is not None and detect_image_format(raw) == target_format:
|
||||
encoded = inject_workflow_metadata(
|
||||
raw,
|
||||
target_format,
|
||||
@@ -502,11 +516,13 @@ def _save_sources(
|
||||
except FileExistsError:
|
||||
continue
|
||||
if external_location:
|
||||
results.append(
|
||||
_external_preview_descriptor(encoded, saved_name, folder_paths_module)
|
||||
)
|
||||
descriptor = _external_preview_descriptor(encoded, saved_name, folder_paths_module)
|
||||
else:
|
||||
results.append({"filename": saved_name, "subfolder": subfolder, "type": "output"})
|
||||
descriptor = {"filename": saved_name, "subfolder": subfolder, "type": "output"}
|
||||
if target_format == "GIF" or saved_name.lower().endswith(".gif"):
|
||||
descriptor["media"] = "gif"
|
||||
descriptor["animated"] = True
|
||||
results.append(descriptor)
|
||||
return results
|
||||
|
||||
|
||||
@@ -564,6 +580,7 @@ def save_temp_images(
|
||||
image_format = detect_image_format(raw)
|
||||
if image_format not in _FORMAT_EXTENSIONS:
|
||||
raise ValueError(f"临时结果不是受支持的图像:{os.path.basename(source_path)}")
|
||||
# GIF is accepted and preserved byte-for-byte when save format is 原始.
|
||||
with Image.open(BytesIO(raw)) as opened:
|
||||
opened.load()
|
||||
image = opened.copy()
|
||||
|
||||
@@ -217,6 +217,17 @@ def extract_video_url(payload: Dict[str, Any]) -> str | None:
|
||||
if value:
|
||||
return str(value)
|
||||
|
||||
# Kling 4.0 compatible task envelopes may place the result under
|
||||
# output.media[].url instead of result_url/task_result.videos[].url.
|
||||
output = _as_dict(source.get("output"))
|
||||
media = output.get("media")
|
||||
if isinstance(media, list):
|
||||
for item in media:
|
||||
item = _as_dict(item)
|
||||
value = item.get("url") or item.get("video_url")
|
||||
if value:
|
||||
return str(value)
|
||||
|
||||
# 腾讯 Kling(v3-t)渠道:完成时视频地址在 metadata.url
|
||||
metadata = _as_dict(source.get("metadata"))
|
||||
value = metadata.get("url") or metadata.get("video_url")
|
||||
|
||||
Reference in New Issue
Block a user