converted SaveSVGNode to V3

This commit is contained in:
bigcat88 2025-07-26 21:01:02 +03:00
parent 9a3d02eb3a
commit 12044d0afc
No known key found for this signature in database
GPG Key ID: 1F0BF0EC3CF22721
3 changed files with 95 additions and 6 deletions

View File

@ -6,6 +6,7 @@ from abc import ABC, abstractmethod
from collections import Counter from collections import Counter
from dataclasses import asdict, dataclass from dataclasses import asdict, dataclass
from enum import Enum from enum import Enum
from io import BytesIO
from typing import Any, Callable, Literal, TypedDict, TypeVar from typing import Any, Callable, Literal, TypedDict, TypeVar
# used for type hinting # used for type hinting
@ -27,7 +28,6 @@ from comfy_api.internal import (_ComfyNodeInternal, _NodeOutputInternal, classpr
from comfy_api.latest._resources import Resources, ResourcesLocal from comfy_api.latest._resources import Resources, ResourcesLocal
from comfy_execution.graph import ExecutionBlocker from comfy_execution.graph import ExecutionBlocker
# from comfy_extras.nodes_images import SVG as SVG_ # NOTE: needs to be moved before can be imported due to circular reference
class FolderType(str, Enum): class FolderType(str, Enum):
input = "input" input = "input"
@ -605,9 +605,24 @@ class Audio(ComfyTypeIO):
class Video(ComfyTypeIO): class Video(ComfyTypeIO):
Type = VideoInput Type = VideoInput
@comfytype(io_type="SVG") @comfytype(io_type="SVG")
class SVG(ComfyTypeIO): class SVG(ComfyTypeIO):
Type = Any # TODO: SVG class is defined in comfy_extras/nodes_images.py, causing circular reference; should be moved to somewhere else before referenced directly in v3 class Data:
"""Stores SVG representations via a list of BytesIO objects."""
def __init__(self, data: list[BytesIO]):
self.data = data
@staticmethod
def combine_all(svgs: list['SVG.Data']) -> 'SVG.Data':
all_svgs_list: list[BytesIO] = []
for svg_item in svgs:
all_svgs_list.extend(svg_item.data)
return SVG.Data(all_svgs_list)
Type = Data
@comfytype(io_type="LORA_MODEL") @comfytype(io_type="LORA_MODEL")
class LoraModel(ComfyTypeIO): class LoraModel(ComfyTypeIO):

View File

@ -2,7 +2,6 @@ from __future__ import annotations
from inspect import cleandoc from inspect import cleandoc
from typing import Optional from typing import Optional
from comfy.utils import ProgressBar from comfy.utils import ProgressBar
from comfy_extras.nodes_images import SVG # Added
from comfy.comfy_types.node_typing import IO from comfy.comfy_types.node_typing import IO
from comfy_api_nodes.apis.recraft_api import ( from comfy_api_nodes.apis.recraft_api import (
RecraftImageGenerationRequest, RecraftImageGenerationRequest,
@ -35,6 +34,7 @@ from server import PromptServer
import torch import torch
from io import BytesIO from io import BytesIO
from PIL import UnidentifiedImageError from PIL import UnidentifiedImageError
from comfy_api.latest import io
def handle_recraft_file_request( def handle_recraft_file_request(
@ -833,7 +833,7 @@ class RecraftTextToVectorNode:
) )
svg_data.append(download_url_to_bytesio(data.url, timeout=1024)) svg_data.append(download_url_to_bytesio(data.url, timeout=1024))
return (SVG(svg_data),) return (io.SVG.Data(svg_data),)
class RecraftVectorizeImageNode: class RecraftVectorizeImageNode:
@ -875,10 +875,10 @@ class RecraftVectorizeImageNode:
path="/proxy/recraft/images/vectorize", path="/proxy/recraft/images/vectorize",
auth_kwargs=kwargs, auth_kwargs=kwargs,
) )
svgs.append(SVG(sub_bytes)) svgs.append(io.SVG.Data(sub_bytes))
pbar.update(1) pbar.update(1)
return (SVG.combine_all(svgs), ) return (io.SVG.combine_all(svgs), )
class RecraftReplaceBackgroundNode: class RecraftReplaceBackgroundNode:

View File

@ -1,5 +1,7 @@
import hashlib import hashlib
import json
import os import os
import re
import numpy as np import numpy as np
import torch import torch
@ -708,6 +710,77 @@ class SaveImage(io.ComfyNode):
) )
class SaveSVGNode(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="SaveSVGNode_V3",
display_name="Save SVG _V3",
description="Save SVG files on disk.",
category="image/save",
inputs=[
io.SVG.Input("svg"),
io.String.Input(
"filename_prefix",
default="svg/ComfyUI",
tooltip="The prefix for the file to save. This may include formatting information such as "
"%date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes.",
),
],
hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo],
is_output_node=True,
)
@classmethod
def execute(cls, svg: io.SVG.Data, filename_prefix="svg/ComfyUI") -> io.NodeOutput:
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
filename_prefix, folder_paths.get_output_directory()
)
results = []
# Prepare metadata JSON
metadata_dict = {}
if cls.hidden.prompt is not None:
metadata_dict["prompt"] = cls.hidden.prompt
if cls.hidden.extra_pnginfo is not None:
metadata_dict.update(cls.hidden.extra_pnginfo)
# Convert metadata to JSON string
metadata_json = json.dumps(metadata_dict, indent=2) if metadata_dict else None
for batch_number, svg_bytes in enumerate(svg.data):
filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
file = f"{filename_with_batch_num}_{counter:05}_.svg"
# Read SVG content
svg_bytes.seek(0)
svg_content = svg_bytes.read().decode('utf-8')
# Inject metadata if available
if metadata_json:
# Create metadata element with CDATA section
metadata_element = f""" <metadata>
<![CDATA[
{metadata_json}
]]>
</metadata>
"""
# Insert metadata after opening svg tag using regex with a replacement function
def replacement(match):
# match.group(1) contains the captured <svg> tag
return match.group(1) + '\n' + metadata_element
# Apply the substitution
svg_content = re.sub(r'(<svg[^>]*>)', replacement, svg_content, flags=re.UNICODE)
# Write the modified SVG to file
with open(os.path.join(full_output_folder, file), 'wb') as svg_file:
svg_file.write(svg_content.encode('utf-8'))
results.append(ui.SavedResult(file, subfolder, io.FolderType.output))
counter += 1
return io.NodeOutput(ui={"images": results})
NODES_LIST: list[type[io.ComfyNode]] = [ NODES_LIST: list[type[io.ComfyNode]] = [
GetImageSize, GetImageSize,
ImageAddNoise, ImageAddNoise,
@ -724,4 +797,5 @@ NODES_LIST: list[type[io.ComfyNode]] = [
SaveAnimatedPNG, SaveAnimatedPNG,
SaveAnimatedWEBP, SaveAnimatedWEBP,
SaveImage, SaveImage,
SaveSVGNode,
] ]