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.
295 lines
9.8 KiB
Python
295 lines
9.8 KiB
Python
"""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",
|
|
]
|