HEL-892: document four watermark branches with pinned static sources

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-30 21:08:43 +08:00
co-authored by multica-agent
parent 11938ca837
commit 459d7fd866
111 changed files with 47013 additions and 14 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,654 @@
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import os
import json
import re
import random
from dataclasses import dataclass, field
from typing import Optional, Tuple, List, Dict, Any
# Author: KARAS
# Version: 3.9.0 - Implemented dynamic scaling for small images
#
# --- 依赖导入 ---
try:
import piexif
except ImportError:
piexif = None
# --- 插件资源路径设置 ---
current_dir = os.path.dirname(os.path.abspath(__file__))
fonts_dir = os.path.join(current_dir, "fonts")
logos_dir = os.path.join(current_dir, "logos")
os.makedirs(fonts_dir, exist_ok=True)
os.makedirs(logos_dir, exist_ok=True)
# --- 资源扫描与缓存 ---
def get_resource_files(directory: str, extensions: Tuple[str, ...]) -> List[str]:
"""Scans a directory for files with given extensions."""
try:
return sorted([f for f in os.listdir(directory) if f.lower().endswith(extensions)])
except FileNotFoundError:
return []
font_files = get_resource_files(fonts_dir, ('.ttf', '.ttc', '.otf')) or ["default"]
bold_font_files = [f for f in font_files if 'bold' in f.lower() or 'bd' in f.lower()] or font_files
logo_files = ["None"] + sorted([os.path.splitext(f)[0] for f in get_resource_files(logos_dir, ('.png',))])
# --- 预设数据 ---
PHONE_MODELS = [
"HUAWEI Pura 70 Ultra", "HUAWEI Pura 70 Pro", "HUAWEI Mate 60 Pro",
"iPhone 15 Pro Max", "iPhone 15 Pro",
"Samsung Galaxy S24 Ultra", "Xiaomi 14 Ultra",
"OPPO Find X7 Ultra", "vivo X100 Ultra", "Google Pixel 8 Pro", "自定义型号"
]
LAYOUT_OPTIONS = [
"1. 底部留白 - 左右分布",
"2. 底部留白 - 居中",
"3. 右侧留白 - 上下竖排",
"4. 顶部 & 底部留白",
"5. 画内叠加 - 左下角",
"6. 画内叠加 - 右下角",
"7. 画内叠加 - 左上角",
"8. 画内叠加 - 右上角",
"9. 画内叠加 - 居中",
"10. 独立信息条"
]
LAYOUT_PRESETS = {
LAYOUT_OPTIONS[0]: {
"logo": "leica",
"logo_size_ratio": 1.0,
"bar_size": 200,
"bg_color": "#FFFFFF",
"title_color": "#000000",
"subtitle_color": "#888888",
},
LAYOUT_OPTIONS[1]: {
"block_b_text_1": "",
"block_a_text_1": "",
"block_a_text_2": "",
"logo": "hasselblad",
"logo_size_ratio": 1,
"bg_color": "#FFFFFF",
"title_color": "#000000",
"subtitle_color": "#888888",
},
LAYOUT_OPTIONS[2]: {
"bar_size": 300,
"block_a_text_2": "",
"logo_size_ratio": 1.0,
},
LAYOUT_OPTIONS[3]: {
"bar_size": 150,
"block_a_text_2": "",
"logo_size_ratio": 1.0,
},
LAYOUT_OPTIONS[4]: {
"logo": "zeiss",
"title_color": "#FFFFFF",
"subtitle_color": "#CCCCCC",
"logo_size_ratio": 1.0,
},
LAYOUT_OPTIONS[5]: {
"logo": "zeiss",
"title_color": "#FFFFFF",
"subtitle_color": "#CCCCCC",
"logo_size_ratio": 1.0,
},
LAYOUT_OPTIONS[6]: {
"logo": "zeiss",
"title_color": "#FFFFFF",
"subtitle_color": "#CCCCCC",
"logo_size_ratio": 1.0,
},
LAYOUT_OPTIONS[7]: {
"logo": "zeiss",
"title_color": "#FFFFFF",
"subtitle_color": "#CCCCCC",
"logo_size_ratio": 1.0,
},
LAYOUT_OPTIONS[8]: {
"logo": "zeiss",
"title_color": "#FFFFFF",
"subtitle_color": "#CCCCCC",
"logo_size_ratio": 1.0,
},
}
# -----------------------------------------------------------------
# 节点 1: 加载图片/附加EXIF
# -----------------------------------------------------------------
class ImageLoaderWithEXIF:
@classmethod
def INPUT_TYPES(s):
input_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "input")
files = get_resource_files(input_dir, ('.jpg', '.jpeg', '.png', '.webp'))
return {
"required": { "image_file": (sorted(files), {"image_upload": True}) },
"optional": { "image_passthrough": ("IMAGE",) }
}
RETURN_TYPES = ("IMAGE", "STRING")
RETURN_NAMES = ("image", "exif_json")
FUNCTION = "load_or_passthrough"
CATEGORY = "Watermark"
def load_or_passthrough(self, image_file: str, image_passthrough: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, str]:
if piexif is None:
raise ImportError("需要 'piexif' 库。请运行: pip install piexif")
image_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "input", image_file)
output_exif_json = "{}"
try:
with Image.open(image_path) as img_for_exif:
if 'exif' in img_for_exif.info and img_for_exif.info['exif']:
exif_dict = piexif.load(img_for_exif.info['exif'])
exif_data = self.parse_exif(exif_dict)
output_exif_json = json.dumps(exif_data)
except Exception as e:
print(f"无法从 '{image_file}' 读取EXIF: {e}")
if image_passthrough is not None:
return (image_passthrough, output_exif_json)
else:
with Image.open(image_path) as img:
img_rgb = img.convert("RGB")
if "exif" in img.info:
try:
exif_dict = piexif.load(img.info["exif"])
orientation = exif_dict.get("0th", {}).get(piexif.ImageIFD.Orientation, 1)
if orientation > 1:
img_rgb = self.apply_exif_orientation(img_rgb, orientation)
except Exception as e:
print(f"处理EXIF方向时出错: {e}")
image_tensor = np.array(img_rgb).astype(np.float32) / 255.0
return (torch.from_numpy(image_tensor)[None,], output_exif_json)
def apply_exif_orientation(self, image: Image.Image, orientation: int) -> Image.Image:
"""Applies EXIF orientation to the image."""
if orientation == 2: return image.transpose(Image.FLIP_LEFT_RIGHT)
if orientation == 3: return image.rotate(180)
if orientation == 4: return image.transpose(Image.FLIP_TOP_BOTTOM)
if orientation == 5: return image.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
if orientation == 6: return image.rotate(-90, expand=True)
if orientation == 7: return image.rotate(90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
if orientation == 8: return image.rotate(90, expand=True)
return image
def parse_exif(self, exif_dict: Dict) -> Dict[str, Any]:
"""Parses raw EXIF data into a structured dictionary."""
exif_data = {}
zeroth_ifd = exif_dict.get('0th', {})
exif_ifd = exif_dict.get('Exif', {})
if piexif.ImageIFD.Make in zeroth_ifd:
exif_data['Make'] = zeroth_ifd[piexif.ImageIFD.Make].decode('utf-8', errors='ignore').strip('\x00').strip()
if piexif.ImageIFD.Model in zeroth_ifd:
exif_data['Model'] = zeroth_ifd[piexif.ImageIFD.Model].decode('utf-8', errors='ignore').strip('\x00').strip()
if piexif.ExifIFD.LensModel in exif_ifd:
exif_data['LensModel'] = exif_ifd[piexif.ExifIFD.LensModel].decode('utf-8', errors='ignore').strip('\x00').strip()
if piexif.ExifIFD.DateTimeOriginal in exif_ifd:
exif_data['Timestamp'] = exif_ifd[piexif.ExifIFD.DateTimeOriginal].decode('utf-8', errors='ignore').strip('\x00').strip()
if piexif.ExifIFD.FNumber in exif_ifd:
f_num = exif_ifd[piexif.ExifIFD.FNumber]
exif_data['Aperture'] = f"f/{(f_num[0]/f_num[1]):.1f}" if f_num[1] > 0 else "f/0.0"
if piexif.ExifIFD.ExposureTime in exif_ifd:
exp = exif_ifd[piexif.ExifIFD.ExposureTime]
if exp[0] > 0 and exp[1] > 0:
shutter = exp[0] / exp[1]
exif_data['ShutterSpeed'] = f"1/{int(1/shutter)}s" if shutter < 1 else f"{shutter}s"
if piexif.ExifIFD.ISOSpeedRatings in exif_ifd:
exif_data['ISO'] = f"ISO{exif_ifd[piexif.ExifIFD.ISOSpeedRatings]}"
if piexif.ExifIFD.FocalLength in exif_ifd:
focal = exif_ifd[piexif.ExifIFD.FocalLength]
if focal[1] > 0:
exif_data['FocalLength'] = f"{int(focal[0]/focal[1])}mm"
return exif_data
# -----------------------------------------------------------------
# 节点 2: 相机水印生成器
# -----------------------------------------------------------------
@dataclass
class TextContent:
block_a: List[str]
block_b: List[str]
@dataclass
class TextBlock:
lines: List[Tuple[str, ImageFont.FreeTypeFont, str]] = field(default_factory=list)
width: int = 0
height: int = 0
line_bboxes: List[Tuple[int, int, int, int]] = field(default_factory=list)
class CameraWatermarkNode:
_font_cache = {}
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"layout": (LAYOUT_OPTIONS,),
"restore_preset": ("BOOLEAN", {"default": False, "label_on": "应用当前样式预设", "label_off": "应用当前样式预设"}),
"randomize_style": ("BOOLEAN", {"default": False}),
"random_style_selection": ("STRING", {"multiline": False, "default": "1-10"}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"use_exif": ("BOOLEAN", {"default": True}),
"block_a_text_1": ("STRING", {"multiline": False, "default": "iPhone 15 Pro Max"}),
"block_a_text_2": ("STRING", {"multiline": False, "default": "Main Camera"}),
"block_a_text_3": ("STRING", {"multiline": False, "default": "© KARAS"}),
"block_b_text_1": ("STRING", {"multiline": False, "default": "SONY"}),
"block_b_text_2": ("STRING", {"multiline": False, "default": "24mm | f/1.8 | 1/125s | ISO 50"}),
"block_b_text_3": ("STRING", {"multiline": False, "default": ""}),
"logo": (logo_files, {"default": "leica" if "leica" in [lf.lower() for lf in logo_files] else logo_files[0]}),
"logo_size_ratio": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 3.0, "step": 0.1}),
"bar_size": ("INT", {"default": 200, "min": 0, "max": 2048, "step": 10}),
"bar_width": ("INT", {"default": 1894, "min": 64, "max": 8192, "step": 64}),
"bar_height": ("INT", {"default": 165, "min": 64, "max": 8192, "step": 64}),
"padding": ("INT", {"default": 50, "min": 0, "max": 400, "step": 1}),
"spacing": ("INT", {"default": 15, "min": 0, "max": 200, "step": 1}),
"font_name": (font_files, {}),
"font_bold_name": (bold_font_files, {}),
"font_size_large": ("INT", {"default": 48, "min": 8, "max": 200, "step": 1}),
"font_size_medium": ("INT", {"default": 28, "min": 8, "max": 200, "step": 1}),
"font_size_small": ("INT", {"default": 24, "min": 8, "max": 200, "step": 1}),
"bg_color": ("STRING", {"multiline": False, "default": "#FFFFFF"}),
"title_color": ("STRING", {"multiline": False, "default": "#000000"}),
"subtitle_color": ("STRING", {"multiline": False, "default": "#888888"}),
},
"optional": { "exif_data": ("STRING", {"forceInput": True}), }
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "generate_image"
CATEGORY = "Watermark"
def tensor_to_pil(self, tensor: torch.Tensor) -> Optional[Image.Image]:
if tensor is None: return None
return Image.fromarray(np.clip(255. * tensor.cpu().numpy().squeeze(0), 0, 255).astype(np.uint8))
def pil_to_tensor(self, pil_image: Image.Image) -> torch.Tensor:
return torch.from_numpy(np.array(pil_image).astype(np.float32) / 255.0).unsqueeze(0)
def get_font(self, font_name: str, size: int) -> ImageFont.FreeTypeFont:
cache_key = f"{font_name}_{size}"
if cache_key in self._font_cache:
return self._font_cache[cache_key]
if not font_name or font_name == "default":
try: font = ImageFont.load_default(size=size)
except AttributeError: font = ImageFont.load_default()
else:
font_path = os.path.join(fonts_dir, font_name)
try: font = ImageFont.truetype(font_path, size=size)
except Exception as e:
print(f"警告: 无法加载字体 '{font_name}'。错误: {e}")
try: font = ImageFont.load_default(size=size)
except AttributeError: font = ImageFont.load_default()
self._font_cache[cache_key] = font
return font
def get_text_bbox(self, text: str, font: ImageFont.FreeTypeFont) -> Tuple[int, int, int, int]:
if hasattr(font, 'getbbox'):
return font.getbbox(text)
else:
w, h = font.getsize(text)
return (0, 0, w, h)
def _crop_transparent_border(self, pil_image: Image.Image) -> Image.Image:
"""Crops the transparent border from a PIL image."""
if pil_image.mode != "RGBA":
return pil_image
bbox = pil_image.getbbox()
if bbox:
return pil_image.crop(bbox)
return pil_image
def _parse_range_string(self, range_string: str) -> List[int]:
numbers = set()
parts = range_string.split(',')
for part in parts:
part = part.strip()
if not part: continue
if '-' in part:
try:
start, end = map(int, part.split('-'))
if start <= end:
numbers.update(range(start, end + 1))
except ValueError:
print(f"警告: 无效的范围 '{part}' in random style selection.")
else:
try:
numbers.add(int(part))
except ValueError:
print(f"警告: 无效的数字 '{part}' in random style selection.")
return sorted(list(numbers))
def _prepare_content(self, **kwargs) -> Tuple[TextContent, str]:
exif_data_str = kwargs.get('exif_data')
has_valid_exif = kwargs['use_exif'] and exif_data_str and exif_data_str.strip() != "{}"
b_a1, b_a2, b_a3 = kwargs['block_a_text_1'], kwargs['block_a_text_2'], kwargs['block_a_text_3']
b_b1, b_b2, b_b3 = kwargs['block_b_text_1'], kwargs['block_b_text_2'], kwargs['block_b_text_3']
logo_match_source = b_a1.lower()
if has_valid_exif:
try:
data = json.loads(exif_data_str)
param_parts = [data.get("FocalLength"), data.get("Aperture"), data.get("ShutterSpeed"), data.get("ISO")]
b_a1 = data.get("Model", "")
b_a2 = data.get("LensModel", "")
b_a3 = kwargs.get('author', '© KARAS')
b_b1 = data.get("Make", "")
b_b2 = " | ".join(filter(None, param_parts))
b_b3 = data.get("Timestamp", "")
logo_match_source = data.get("Make", "").lower()
except (json.JSONDecodeError, KeyError) as e:
print(f"无法解析EXIF: {e}")
content = TextContent(block_a=[b_a1, b_a2, b_a3], block_b=[b_b1, b_b2, b_b3])
final_logo = kwargs['logo']
if final_logo == "None" and logo_match_source:
for logo_name in logo_files:
if logo_name != "None" and logo_name.lower() in logo_match_source:
final_logo = logo_name
break
return content, final_logo
def _draw_block(self, draw, block: TextBlock, start_x: int, start_y: int, align: str = 'left', spacing: int = 10):
y = start_y
for i, (text, font, color) in enumerate(block.lines):
bbox = block.line_bboxes[i]
text_width, text_height = bbox[2] - bbox[0], bbox[3] - bbox[1]
x = start_x
if align == 'center':
x = start_x - text_width / 2
elif align == 'right':
x = start_x - text_width
draw.text((x - bbox[0], y - bbox[1]), text, font=font, fill=color)
y += text_height + spacing
def _draw_vertical_text_block(self, draw_layer, block: TextBlock, center_x: int, start_y: int, spacing: int):
if not block.lines:
return 0
temp_surface = Image.new("RGBA", (block.width, block.height), (0, 0, 0, 0))
temp_draw = ImageDraw.Draw(temp_surface)
y_cursor = 0
min_x_offset = min(box[0] for box in block.line_bboxes)
for i, (text, font, color) in enumerate(block.lines):
bbox = block.line_bboxes[i]
text_height = bbox[3] - bbox[1]
temp_draw.text((-min_x_offset, y_cursor - bbox[1]), text, font=font, fill=color)
y_cursor += text_height + spacing
rotated_surface = temp_surface.rotate(90, expand=True, resample=Image.Resampling.LANCZOS)
paste_x = center_x - rotated_surface.width / 2
paste_y = start_y
draw_layer.paste(rotated_surface, (int(paste_x), int(paste_y)), rotated_surface)
return rotated_surface.height
def generate_image(self, **kwargs):
params = kwargs.copy()
layout = params['layout']
seed = params['seed']
restore_preset = params.pop('restore_preset', False)
if params.get('randomize_style', False):
random.seed(seed)
selection_str = params.get('random_style_selection', '1-10')
allowed_indices = self._parse_range_string(selection_str)
allowed_indices_0based = [i - 1 for i in allowed_indices if 1 <= i <= len(LAYOUT_OPTIONS)]
if allowed_indices_0based:
chosen_index = random.choice(allowed_indices_0based)
layout = LAYOUT_OPTIONS[chosen_index]
print(f"随机样式已启用 (种子: {seed}),选择: {layout}")
if restore_preset:
if layout in LAYOUT_PRESETS:
print(f"恢复预设: {layout}")
params.update(LAYOUT_PRESETS[layout])
content, final_logo_name = self._prepare_content(**params)
input_pil = self.tensor_to_pil(params['image'])
img_w, img_h = input_pil.size
# --- Dynamic Scaling Logic ---
base_width = 1200.0 # Standard width for scaling
scale_factor = min(1.0, img_w / base_width)
bar_size = int(params['bar_size'] * scale_factor)
padding = int(params['padding'] * scale_factor)
spacing = int(params['spacing'] * scale_factor)
font_size_large = int(params['font_size_large'] * scale_factor)
font_size_medium = int(params['font_size_medium'] * scale_factor)
font_size_small = int(params['font_size_small'] * scale_factor)
bg_color = params['bg_color']
if layout.startswith("1.") or layout.startswith("2.") or layout.startswith("10."):
canvas = Image.new("RGBA", (img_w, img_h + bar_size), bg_color)
canvas.paste(input_pil.convert("RGBA"), (0, 0))
draw_area = (0, img_h, img_w, bar_size)
elif layout.startswith("3."):
canvas = Image.new("RGBA", (img_w + bar_size, img_h), bg_color)
canvas.paste(input_pil.convert("RGBA"), (0, 0))
draw_area = (img_w, 0, bar_size, img_h)
elif layout.startswith("4."):
canvas = Image.new("RGBA", (img_w, img_h + bar_size * 2), bg_color)
canvas.paste(input_pil.convert("RGBA"), (0, bar_size))
draw_area_top = (0, 0, img_w, bar_size)
draw_area_bottom = (0, img_h + bar_size, img_w, bar_size)
draw_area = draw_area_top
elif layout.startswith("5.") or layout.startswith("6.") or layout.startswith("7.") or layout.startswith("8.") or layout.startswith("9."):
canvas = input_pil.convert("RGBA")
draw_area = (0, 0, img_w, img_h)
else:
bar_width = int(params['bar_width'] * scale_factor)
bar_height = int(params['bar_height'] * scale_factor)
canvas = Image.new("RGBA", (bar_width, bar_height), bg_color)
draw_area = (0, 0, canvas.width, canvas.height)
draw_layer = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(draw_layer)
fonts = {
'large_bold': self.get_font(params['font_bold_name'], font_size_large),
'medium': self.get_font(params['font_name'], font_size_medium),
'small': self.get_font(params['font_name'], font_size_small)
}
block_a_fonts = [fonts['large_bold'], fonts['medium'], fonts['small']]
block_b_fonts = [fonts['large_bold'], fonts['medium'], fonts['small']]
block_a_colors = [params['title_color'], params['subtitle_color'], params['subtitle_color']]
block_b_colors = [params['title_color'], params['subtitle_color'], params['subtitle_color']]
block_a = TextBlock()
for i, text in enumerate(content.block_a):
if text:
block_a.lines.append((text, block_a_fonts[i], block_a_colors[i]))
if block_a.lines:
block_a.line_bboxes = [self.get_text_bbox(line[0], line[1]) for line in block_a.lines]
min_x = min(box[0] for box in block_a.line_bboxes)
max_x = max(box[2] for box in block_a.line_bboxes)
block_a.width = max_x - min_x
line_heights = [box[3] - box[1] for box in block_a.line_bboxes]
block_a.height = int(sum(line_heights) + max(0, len(line_heights) - 1) * spacing)
block_b = TextBlock()
for i, text in enumerate(content.block_b):
if text:
block_b.lines.append((text, block_b_fonts[i], block_b_colors[i]))
if block_b.lines:
block_b.line_bboxes = [self.get_text_bbox(line[0], line[1]) for line in block_b.lines]
min_x = min(box[0] for box in block_b.line_bboxes)
max_x = max(box[2] for box in block_b.line_bboxes)
block_b.width = max_x - min_x
line_heights = [box[3] - box[1] for box in block_b.line_bboxes]
block_b.height = int(sum(line_heights) + max(0, len(line_heights) - 1) * spacing)
pil_logo = None
if final_logo_name != "None":
try:
logo_filename = next((f for f in os.listdir(logos_dir) if os.path.splitext(f)[0].lower() == final_logo_name.lower()), None)
if logo_filename:
pil_logo = Image.open(os.path.join(logos_dir, logo_filename)).convert("RGBA")
pil_logo = self._crop_transparent_border(pil_logo)
except Exception as e:
print(f"无法加载内置Logo '{final_logo_name}': {e}")
if pil_logo:
bar_based_target_height = 0
if not (layout.startswith("5.") or layout.startswith("6.") or layout.startswith("7.") or layout.startswith("8.") or layout.startswith("9.")):
max_size_ref = draw_area[3] if not layout.startswith("3.") else draw_area[2]
bar_based_target_height = int(max_size_ref * 0.5)
text_based_target_height = 0
if layout in [LAYOUT_OPTIONS[0], LAYOUT_OPTIONS[9]]:
text_based_target_height = block_b.height
elif layout in [LAYOUT_OPTIONS[1], LAYOUT_OPTIONS[3]] or layout.startswith("5.") or layout.startswith("6.") or layout.startswith("7.") or layout.startswith("8.") or layout.startswith("9."):
text_based_target_height = block_a.height if block_a.height > 0 else block_b.height
base_height = max(text_based_target_height, bar_based_target_height)
final_target_height = int(base_height * params['logo_size_ratio'])
if final_target_height > 0:
original_width, original_height = pil_logo.size
if original_height > 0:
ratio = final_target_height / original_height
new_width = int(original_width * ratio)
pil_logo = pil_logo.resize((new_width, final_target_height), Image.Resampling.LANCZOS)
if layout == LAYOUT_OPTIONS[0] or layout == LAYOUT_OPTIONS[9]:
x, y, w, h = draw_area
y_a = y + (h - block_a.height) / 2
self._draw_block(draw, block_a, x + padding, y_a, spacing=spacing)
y_b = y + (h - block_b.height) / 2
if pil_logo:
right_group_width = block_b.width + spacing + pil_logo.width
start_x_right = x + w - padding - right_group_width
logo_x = start_x_right
logo_y = y + (h - pil_logo.height) / 2
draw_layer.paste(pil_logo, (int(logo_x), int(logo_y)), pil_logo)
block_b_x = logo_x + pil_logo.width + spacing
self._draw_block(draw, block_b, block_b_x, y_b, align='left', spacing=spacing)
else:
self._draw_block(draw, block_b, x + w - padding, y_b, align='right', spacing=spacing)
elif layout == LAYOUT_OPTIONS[1]:
x, y, w, h = draw_area
elements = []
if pil_logo: elements.append({'type': 'logo', 'data': pil_logo, 'height': pil_logo.height})
if block_a.lines: elements.append({'type': 'block', 'data': block_a, 'height': block_a.height})
if block_b.lines: elements.append({'type': 'block', 'data': block_b, 'height': block_b.height})
total_height = sum(el['height'] for el in elements) + max(0, len(elements) - 1) * spacing
y_start = y + (h - total_height) / 2
for el in elements:
if el['type'] == 'logo':
logo = el['data']
logo_x = x + (w - logo.width) / 2
draw_layer.paste(logo, (int(logo_x), int(y_start)), logo)
else:
self._draw_block(draw, el['data'], x + w/2, y_start, align='center', spacing=spacing)
y_start += el['height'] + spacing
elif layout == LAYOUT_OPTIONS[2]:
x, y, w, h = draw_area
center_x = x + w / 2
if block_b.lines:
y_b = y + padding
self._draw_vertical_text_block(draw_layer, block_b, center_x, y_b, spacing)
if block_a.lines:
rotated_height_a = block_a.width
y_a = y + h - padding - rotated_height_a
self._draw_vertical_text_block(draw_layer, block_a, center_x, y_a, spacing)
if pil_logo:
logo_x = center_x - pil_logo.width / 2
logo_y = y + (h - pil_logo.height) / 2
draw_layer.paste(pil_logo, (int(logo_x), int(logo_y)), pil_logo)
elif layout == LAYOUT_OPTIONS[3]:
x_top, y_top, w_top, h_top = draw_area_top
x_bot, y_bot, w_bot, h_bot = draw_area_bottom
if pil_logo:
total_top_width = pil_logo.width + spacing + block_a.width
start_x_top = x_top + (w_top - total_top_width) / 2
logo_x = start_x_top
logo_y = y_top + (h_top - pil_logo.height) / 2
draw_layer.paste(pil_logo, (int(logo_x), int(logo_y)), pil_logo)
block_a_x = start_x_top + pil_logo.width + spacing
self._draw_block(draw, block_a, block_a_x, y_top + (h_top - block_a.height) / 2, align='left', spacing=spacing)
else:
self._draw_block(draw, block_a, x_top + w_top / 2, y_top + (h_top - block_a.height) / 2, align='center', spacing=spacing)
self._draw_block(draw, block_b, x_bot + w_bot / 2, y_bot + (h_bot - block_b.height) / 2, align='center', spacing=spacing)
elif layout.startswith("5.") or layout.startswith("6.") or layout.startswith("7.") or layout.startswith("8.") or layout.startswith("9."):
x, y, w, h = draw_area
elements = []
if block_a.lines: elements.append({'type': 'block', 'data': block_a, 'height': block_a.height, 'width': block_a.width})
if block_b.lines: elements.append({'type': 'block', 'data': block_b, 'height': block_b.height, 'width': block_b.width})
if pil_logo: elements.append({'type': 'logo', 'data': pil_logo, 'height': pil_logo.height, 'width': pil_logo.width})
if elements:
total_height = sum(el['height'] for el in elements) + max(0, len(elements) - 1) * spacing
max_width = max(el['width'] for el in elements) if elements else 0
if "左下角" in layout: y_start, x_start, align = h - padding - total_height, padding, 'left'
elif "右下角" in layout: y_start, x_start, align = h - padding - total_height, w - padding, 'right'
elif "左上角" in layout: y_start, x_start, align = padding, padding, 'left'
elif "右上角" in layout: y_start, x_start, align = padding, w - padding, 'right'
else: y_start, x_start, align = (h - total_height) / 2, w / 2, 'center'
current_y = y_start
for el in elements:
el_width = el['width']
if el['type'] == 'logo':
logo = el['data']
if align == 'left': logo_x = x_start
elif align == 'right': logo_x = x_start - el_width
else: logo_x = x_start - el_width / 2
draw_layer.paste(logo, (int(logo_x), int(current_y)), logo)
else:
self._draw_block(draw, el['data'], x_start, current_y, align=align, spacing=spacing)
current_y += el['height'] + spacing
canvas.alpha_composite(draw_layer)
final_image = canvas.convert("RGB")
return (self.pil_to_tensor(final_image),)
# --- ComfyUI 节点注册 ---
NODE_CLASS_MAPPINGS = {
"CameraWatermarkNode": CameraWatermarkNode,
"ImageLoaderWithEXIF": ImageLoaderWithEXIF,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"CameraWatermarkNode": "相机水印",
"ImageLoaderWithEXIF": "加载/附加 EXIF",
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,2 @@
# This file only exists for backwards compatibility.
from comfy_api.latest._input_impl.video_types import * # noqa: F403
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,30 @@
# By Suzie1 and RockOfFire
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to
# deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
@author: Suzie1
@title: Comfyroll Studio
@nickname: Comfyroll Studio
@description: 175 custom nodes for artists, designers and animators.
"""
from .node_mappings import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
print("------------------------------------------")
print("\033[34mComfyroll Studio v1.76 : \033[92m 175 Nodes Loaded\033[0m")
print("------------------------------------------")
print("** For changes, please see patch notes at https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/blob/main/Patch_Notes.md")
print("** For help, please see the wiki at https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki")
print("------------------------------------------")
@@ -0,0 +1,43 @@
icons = {
"Comfyroll/Upscale": "🧩 Comfyroll Studio/✨ Essential/🔍 Upscale",
"Comfyroll/Model Merge": "🧩 Comfyroll Studio/✨ Essential/⛏️ Model Merge",
"Comfyroll/Utils/Logic": "🧩 Comfyroll Studio/🛠️ Utils/🔀 Logic",
"Comfyroll/Utils/Conditional": "🧩 Comfyroll Studio/🛠️ Utils/🔀 Conditional",
"Comfyroll/Utils/Process": "🧩 Comfyroll Studio/🛠️ Utils/🔂 Process",
"Comfyroll/Utils/Index": "🧩 Comfyroll Studio/🛠️ Utils/🔢 Index",
"Comfyroll/Utils/Conversion": "🧩 Comfyroll Studio/🛠️ Utils/🔧 Conversion",
"Comfyroll/Utils/Random": "🧩 Comfyroll Studio/🛠️ Utils/🎲 Random",
"Comfyroll/Utils/Text": "🧩 Comfyroll Studio/🛠️ Utils/🔤 Text",
"Comfyroll/Utils/Other": "🧩 Comfyroll Studio/🛠️ Utils/⚙️ Other",
"Comfyroll/LoRA": "🧩 Comfyroll Studio/✨ Essential/💊 LoRA",
"Comfyroll/ControlNet": "🧩 Comfyroll Studio/✨ Essential/🕹️ ControlNet",
"Comfyroll/XY Grid": "🧩 Comfyroll Studio/✨ Essential/📉 XY Grid",
"Comfyroll/SDXL": "🧩 Comfyroll Studio/✨ Essential/🌟 SDXL",
"Comfyroll/List": "🧩 Comfyroll Studio/✨ Essential/📜 List",
"Comfyroll/List/IO": "🧩 Comfyroll Studio/✨ Essential/📜 List/⌨️ IO",
"Comfyroll/List/Utils": "🧩 Comfyroll Studio/✨ Essential/📜 List/🛠️ Utils",
"Comfyroll/Aspect Ratio": "🧩 Comfyroll Studio/✨ Essential/🔳 Aspect Ratio",
"Comfyroll/Pipe/Module": "🧩 Comfyroll Studio/✨ Essential/🎷 Pipe/✈️ Module",
"Comfyroll/Pipe/Image": "🧩 Comfyroll Studio/✨ Essential/🎷 Pipe/🛩️ Image",
"Comfyroll/Pipe/Bus": "🧩 Comfyroll Studio/✨ Essential/🎷 Pipe/🚌 Bus",
"Comfyroll/Pipe": "🧩 Comfyroll Studio/✨ Essential/🎷 Pipe",
"Comfyroll/Graphics/Text": "🧩 Comfyroll Studio/👾 Graphics/🔤 Text",
"Comfyroll/Graphics/Layout": "🧩 Comfyroll Studio/👾 Graphics/🌁 Layout",
"Comfyroll/Graphics/Template": "🧩 Comfyroll Studio/👾 Graphics/📱 Template",
"Comfyroll/Graphics/Filter": "🧩 Comfyroll Studio/👾 Graphics/🎨 Filter",
"Comfyroll/Graphics/Pattern": "🧩 Comfyroll Studio/👾 Graphics/🌈 Pattern",
"Comfyroll/Graphics/Shape": "🧩 Comfyroll Studio/👾 Graphics/🟣 Shape",
"Comfyroll/Graphics/3D": "🧩 Comfyroll Studio/👾 Graphics/3D",
"Comfyroll/Graphics/Utilty": "🧩 Comfyroll Studio/👾 Graphics/🔧 Utility",
"Comfyroll/Workflow": "🧩 Comfyroll Studio/✨ Essential/Workflow",
"Comfyroll/Essential/Core": "🧩 Comfyroll Studio/✨ Essential/📦 Core",
"Comfyroll/Essential/Legacy": "🧩 Comfyroll Studio/✨ Essential/💀 Legacy",
"Comfyroll/Animation/Camera": "🧩 Comfyroll Studio/🎥 Animation/🎦 Camera",
"Comfyroll/Animation/Utils": "🧩 Comfyroll Studio/🎥 Animation/🛠️ Utils",
"Comfyroll/Animation/Schedule": "🧩 Comfyroll Studio/🎥 Animation/📋 Schedule",
"Comfyroll/Animation/Schedulers": "🧩 Comfyroll Studio/🎥 Animation/📑 Schedulers",
"Comfyroll/Animation/Prompt": "🧩 Comfyroll Studio/🎥 Animation/📝 Prompt",
"Comfyroll/Animation/Legacy": "🧩 Comfyroll Studio/🎥 Animation/💀 Legacy",
"Comfyroll/Animation/Interpolate": "🧩 Comfyroll Studio/🎥 Animation/🔢 Interpolate",
"Comfyroll/Animation/IO": "🧩 Comfyroll Studio/🎥 Animation/⌨️ IO",
}
@@ -0,0 +1,77 @@
color_mapping = {
"white": (255, 255, 255),
"black": (0, 0, 0),
"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"yellow": (255, 255, 0),
"cyan": (0, 255, 255),
"magenta": (255, 0, 255),
"orange": (255, 165, 0),
"purple": (128, 0, 128),
"pink": (255, 192, 203),
"brown": (160, 85, 15),
"gray": (128, 128, 128),
"lightgray": (211, 211, 211),
"darkgray": (102, 102, 102),
"olive": (128, 128, 0),
"lime": (0, 128, 0),
"teal": (0, 128, 128),
"navy": (0, 0, 128),
"maroon": (128, 0, 0),
"fuchsia": (255, 0, 128),
"aqua": (0, 255, 128),
"silver": (192, 192, 192),
"gold": (255, 215, 0),
"turquoise": (64, 224, 208),
"lavender": (230, 230, 250),
"violet": (238, 130, 238),
"coral": (255, 127, 80),
"indigo": (75, 0, 130),
}
COLORS = ["custom", "white", "black", "red", "green", "blue", "yellow",
"cyan", "magenta", "orange", "purple", "pink", "brown", "gray",
"lightgray", "darkgray", "olive", "lime", "teal", "navy", "maroon",
"fuchsia", "aqua", "silver", "gold", "turquoise", "lavender",
"violet", "coral", "indigo"]
iso_sizes = {
"A0 - 9933x14043": (9933, 14043),
"A1 - 7016x9933": (7016, 9933),
"A2 - 4960x7016": (4960, 7016),
"A3 - 3508x4960": (3508, 4960),
"A4 - 2480x3508": (2480, 3508),
"A5 - 1748x2480": (1748, 2480),
"A6 - 1240x1748": (1240, 1748),
"A7 - 874x1240": (874, 1240),
"A8 - 614x874": (614, 874),
"A9 - 437x614": (437, 614),
"A10 - 307x437": (307, 437),
"A11 - 213x307": (213, 307),
"A12 - 154x213": (154, 213),
"A13 - 106x154": (106, 154),
"B0 - 11811x16701": (11811, 16701),
"B1 - 8350x11811": (8350, 11811),
"B2 - 5906x8350": (5906, 8350),
"B3 - 4169x5906": (4169, 5906),
"B4 - 2953x4169": (2953, 4169),
"B5 - 2079x2953": (2079, 2953),
"B6 - 1476x2079": (1476, 2079),
"B7 - 1039x1476": (1039, 1476),
"B8 - 732x1039": (732, 1039),
"B9 - 520x732": (520, 732),
"B10 - 366x520": (366, 520),
"C0 - 10831x15319": (10831, 15319),
"C1 - 7654x10831": (7654, 10831),
"C2 - 5409x7654": (5409, 7654),
"C3 - 3827x5409": (3827, 5409),
"C4 - 2705x3827": (2705, 3827),
"C5 - 1913x2705": (1913, 2705),
"C6 - 1346x1913": (1346, 1913),
"C7 - 957x1346": (957, 1346),
"C8 - 673x957": (673, 957),
"C9 - 472x673": (472, 673),
"C10 - 331x472": (331, 472),
}
@@ -0,0 +1,532 @@
try:
from .nodes.nodes_core import *
from .nodes.nodes_aspect_ratio import *
from .nodes.nodes_list import *
from .nodes.nodes_lora import *
from .nodes.nodes_controlnet import *
from .nodes.nodes_pipe import *
from .nodes.nodes_sdxl import *
from .nodes.nodes_model_merge import *
from .nodes.nodes_upscale import *
from .nodes.nodes_xygrid import *
from .nodes.nodes_legacy import *
except ImportError:
print("\033[34mComfyroll Studio: \033[92mFailed to load Essential nodes\033[0m")
try:
from .nodes.nodes_graphics_matplot import *
from .nodes.nodes_graphics_text import *
from .nodes.nodes_graphics_layout import *
from .nodes.nodes_graphics_filter import *
from .nodes.nodes_graphics_template import *
from .nodes.nodes_graphics_pattern import *
except ImportError:
print("\033[34mComfyroll Studio: \033[92mFailed to load Graphics nodes\033[0m")
try:
from .nodes.nodes_animation_interpolation import *
from .nodes.nodes_animation_io import *
from .nodes.nodes_animation_prompt import *
from .nodes.nodes_animation_schedulers import *
from .nodes.nodes_animation_schedules import *
from .nodes.nodes_animation_lists import *
from .nodes.nodes_animation_utils import *
from .nodes.nodes_animation_cyclers import *
except ImportError:
print("\033[34mComfyroll Studio: \033[92mFailed to load Animation nodes\033[0m")
try:
from .nodes.nodes_utils_logic import *
from .nodes.nodes_utils_index import *
from .nodes.nodes_utils_conversion import *
from .nodes.nodes_utils_random import *
from .nodes.nodes_utils_text import *
from .nodes.nodes_utils_other import *
except ImportError:
print("\033[34mComfyroll Studio: \033[92mFailed to load Utility nodes\033[0m")
NODE_CLASS_MAPPINGS = {
### Core Nodes
"CR Image Output": CR_ImageOutput,
"CR Latent Batch Size": CR_LatentBatchSize,
"CR Conditioning Mixer": CR_ConditioningMixer,
"CR Select Model": CR_SelectModel,
"CR Seed": CR_Seed,
"CR Prompt Text": CR_PromptText,
"CR Combine Prompt": CR_CombinePrompt,
"CR VAE Decode": CR_VAEDecode,
### List Nodes
"CR Text List": CR_TextList,
"CR Prompt List": CR_PromptList,
"CR Simple List": CR_SimpleList,
"CR Float Range List": CR_FloatRangeList,
"CR Integer Range List": CR_IntegerRangeList,
"CR Load Text List": CR_LoadTextList,
"CR Binary To Bit List": CR_BinaryToBitList,
"CR Text Cycler": CR_TextCycler,
"CR Value Cycler": CR_ValueCycler,
### List IO
"CR Load Image List": CR_LoadImageList,
"CR Load Image List Plus": CR_LoadImageListPlus,
"CR Load GIF As List": CR_LoadGIFAsList,
"CR Font File List": CR_FontFileList,
### List Utils
"CR Batch Images From List": CR_MakeBatchFromImageList,
"CR Intertwine Lists" : CR_IntertwineLists,
"CR Repeater": CR_Repeater,
"CR XY Product": CR_XYProduct,
"CR Text List To String": CR_TextListToString,
### Aspect Ratio Nodes
"CR SD1.5 Aspect Ratio": CR_AspectRatioSD15,
"CR SDXL Aspect Ratio": CR_SDXLAspectRatio,
"CR Aspect Ratio": CR_AspectRatio,
"CR Aspect Ratio Banners": CR_AspectRatioBanners,
"CR Aspect Ratio Social Media": CR_AspectRatioSocialMedia,
"CR_Aspect Ratio For Print": CR_AspectRatioForPrint,
### Legacy Nodes
"CR Image Size": CR_ImageSize,
"CR Aspect Ratio SDXL": CR_AspectRatio_SDXL,
"CR SDXL Prompt Mixer": CR_PromptMixer,
"CR Seed to Int": CR_SeedToInt,
### ControlNet Nodes
"CR Apply ControlNet": CR_ApplyControlNet,
"CR Multi-ControlNet Stack": CR_ControlNetStack,
"CR Apply Multi-ControlNet": CR_ApplyControlNetStack,
### LoRA Nodes
"CR Load LoRA": CR_LoraLoader,
"CR LoRA Stack": CR_LoRAStack,
"CR Random LoRA Stack": CR_RandomLoRAStack,
"CR Random Weight LoRA": CR_RandomWeightLoRA,
"CR Apply LoRA Stack": CR_ApplyLoRAStack,
### Model Merge Nodes
"CR Apply Model Merge": CR_ApplyModelMerge,
"CR Model Merge Stack": CR_ModelMergeStack,
### Pipe Nodes
"CR Data Bus In":CR_DataBusIn,
"CR Data Bus Out":CR_DataBusOut,
"CR 8 Channel In":CR_8ChannelIn,
"CR 8 Channel Out":CR_8ChannelOut,
"CR Module Pipe Loader": CR_ModulePipeLoader,
"CR Module Input": CR_ModuleInput,
"CR Module Output": CR_ModuleOutput,
"CR Image Pipe In": CR_ImagePipeIn,
"CR Image Pipe Edit": CR_ImagePipeEdit,
"CR Image Pipe Out": CR_ImagePipeOut,
"CR Pipe Switch": CR_InputSwitchPipe,
### SDXL Nodes
"CR SDXL Prompt Mix Presets": CR_PromptMixPresets,
"CR SDXL Style Text": CR_SDXLStyleText,
"CR SDXL Base Prompt Encoder": CR_SDXLBasePromptEncoder,
### Upscale Nodes
"CR Multi Upscale Stack": CR_MultiUpscaleStack,
"CR Upscale Image": CR_UpscaleImage,
"CR Apply Multi Upscale": CR_ApplyMultiUpscale,
### XY Grid Nodes
"CR XY List": CR_XYList,
"CR XY Interpolate": CR_XYInterpolate,
"CR XY From Folder": CR_XYFromFolder,
"CR XY Save Grid Image": CR_XYSaveGridImage,
"CR XY Index": CR_XYIndex,
#"CR XYZ Index": CR_XYZIndex,
### Graphics Pattern
"CR Halftone Grid": CR_HalftoneGrid,
"CR Color Bars": CR_ColorBars,
"CR Style Bars": CR_StyleBars,
"CR Checker Pattern": CR_CheckerPattern,
"CR Polygons": CR_Polygons,
"CR Color Gradient": CR_ColorGradient,
"CR Radial Gradient": CR_RadialGradient,
"CR Starburst Lines": CR_StarburstLines,
"CR Starburst Colors": CR_StarburstColors,
"CR Simple Binary Pattern": CR_BinaryPatternSimple,
"CR Binary Pattern": CR_BinaryPattern,
### Graphics Shape
"CR Draw Shape": CR_DrawShape,
"CR Draw Pie": CR_DrawPie,
"CR Random Shape Pattern": CR_RandomShapePattern,
### Graphics Text
"CR Overlay Text": CR_OverlayText,
"CR Draw Text": CR_DrawText,
"CR Mask Text": CR_MaskText,
"CR Composite Text": CR_CompositeText,
#"CR Arabic Text RTL": CR_ArabicTextRTL,
"CR Simple Text Watermark": CR_SimpleTextWatermark,
"CR Select Font": CR_SelectFont,
### Graphics Filter
"CR Halftone Filter": CR_HalftoneFilter,
"CR Color Tint": CR_ColorTint,
"CR Vignette Filter": CR_VignetteFilter,
### Graphics Layout
"CR Page Layout": CR_PageLayout,
"CR Image Panel": CR_ImagePanel,
"CR Image Grid Panel": CR_ImageGridPanel,
"CR Image Border": CR_ImageBorder,
"CR Feathered Border": CR_FeatheredBorder,
"CR Simple Text Panel": CR_SimpleTextPanel,
"CR Color Panel": CR_ColorPanel,
"CR Overlay Transparent Image": CR_OverlayTransparentImage,
"CR Half Drop Panel": CR_HalfDropPanel,
"CR Diamond Panel": CR_DiamondPanel,
#"CR Simple Titles": CR_SimpleTitles,
### Graphics Template
"CR Simple Meme Template": CR_SimpleMemeTemplate,
"CR Simple Banner": CR_SimpleBanner,
"CR Comic Panel Templates": CR_ComicPanelTemplates,
"CR Simple Image Compare": CR_SimpleImageCompare,
"CR Thumbnail Preview": CR_ThumbnailPreview,
"CR Seamless Checker": CR_SeamlessChecker,
### Utils Logic
"CR Image Input Switch": CR_ImageInputSwitch,
"CR Image Input Switch (4 way)": CR_ImageInputSwitch4way,
"CR Latent Input Switch": CR_LatentInputSwitch,
"CR Conditioning Input Switch": CR_ConditioningInputSwitch,
"CR Clip Input Switch": CR_ClipInputSwitch,
"CR Model Input Switch": CR_ModelInputSwitch,
"CR ControlNet Input Switch": CR_ControlNetInputSwitch,
"CR VAE Input Switch": CR_VAEInputSwitch,
"CR Text Input Switch": CR_TextInputSwitch,
"CR Text Input Switch (4 way)": CR_TextInputSwitch4way,
"CR Switch Model and CLIP": CR_ModelAndCLIPInputSwitch,
### Utils Process
"CR Batch Process Switch": CR_BatchProcessSwitch,
"CR Img2Img Process Switch": CR_Img2ImgProcessSwitch,
"CR Hires Fix Process Switch": CR_HiResFixProcessSwitch,
### Utils Index
"CR Index": CR_Index,
"CR Index Increment": CR_IncrementIndex,
"CR Index Multiply": CR_MultiplyIndex,
"CR Index Reset": CR_IndexReset,
"CR Trigger": CR_Trigger,
### Utils Conversion
"CR String To Number": CR_StringToNumber,
"CR String To Combo": CR_StringToCombo,
"CR Float To String": CR_FloatToString,
"CR Float To Integer": CR_FloatToInteger,
"CR Integer To String": CR_IntegerToString,
"CR String To Boolean": CR_StringToBoolean,
### Utils Random
"CR Random Hex Color": CR_RandomHexColor,
"CR Random RGB": CR_RandomRGB,
"CR Random Multiline Values": CR_RandomMultilineValues,
"CR Random Multiline Colors": CR_RandomMultilineColors,
"CR Random RGB Gradient": CR_RandomRGBGradient,
"CR Random Panel Codes": CR_RandomPanelCodes,
### Utils Text
"CR Text": CR_Text,
"CR Multiline Text": CR_MultilineText,
"CR Split String": CR_SplitString,
"CR Text Concatenate": CR_TextConcatenate,
"CR Text Replace": CR_TextReplace,
"CR Text Length": CR_TextLength,
"CR Text Operation": CR_TextOperation,
"CR Text Blacklist": CR_TextBlacklist,
"CR Save Text To File": CR_SaveTextToFile,
### Utils Conditional
"CR Set Value On Boolean": CR_SetValueOnBoolean,
"CR Set Value On Binary": CR_SetValueOnBinary,
"CR Set Value on String": CR_SetValueOnString,
"CR Set Switch From String": CR_SetSwitchFromString,
### Utils Other
"CR Value": CR_Value,
"CR Integer Multiple": CR_IntegerMultipleOf,
"CR Clamp Value": CR_ClampValue,
"CR Math Operation": CR_MathOperation,
"CR Get Parameter From Prompt": CR_GetParameterFromPrompt,
"CR Select Resize Method": CR_SelectResizeMethod,
"CR Select ISO Size": CR_SelectISOSize,
### Animation Nodes
# Schedules
"CR Simple Schedule": CR_SimpleSchedule,
"CR Central Schedule": CR_CentralSchedule,
"CR Combine Schedules": CR_CombineSchedules,
"CR Output Schedule To File": CR_OutputScheduleToFile,
"CR Load Schedule From File": CR_LoadScheduleFromFile,
"CR Schedule Input Switch": Comfyroll_ScheduleInputSwitch,
"CR Bit Schedule": CR_BitSchedule,
# Schedulers
"CR Simple Value Scheduler": CR_SimpleValueScheduler,
"CR Simple Text Scheduler": CR_SimpleTextScheduler,
"CR Value Scheduler": CR_ValueScheduler,
"CR Text Scheduler": CR_TextScheduler,
"CR Load Scheduled Models": CR_LoadScheduledModels,
"CR Load Scheduled LoRAs": CR_LoadScheduledLoRAs,
"CR Prompt Scheduler": CR_PromptScheduler,
"CR Simple Prompt Scheduler": CR_SimplePromptScheduler,
# Prompt
"CR Keyframe List": CR_KeyframeList,
#"CR Load Prompt Style": CR_LoadPromptStyle,
"CR Encode Scheduled Prompts": CR_EncodeScheduledPrompts,
# Interpolation
"CR Gradient Float": CR_GradientFloat,
"CR Gradient Integer": CR_GradientInteger,
"CR Increment Float": CR_IncrementFloat,
"CR Increment Integer": CR_IncrementInteger,
"CR Interpolate Latents": CR_InterpolateLatents,
# Utils
"CR Debatch Frames": CR_DebatchFrames,
"CR Current Frame": CR_CurrentFrame,
#"CR Input Text List": CR_InputTextList,
# IO
"CR Load Animation Frames": CR_LoadAnimationFrames,
"CR Load Flow Frames": CR_LoadFlowFrames,
"CR Output Flow Frames": CR_OutputFlowFrames,
### Legacy
# Note: CR Prompt List and CR Text List names have been reused,
# so the old versions of these nodes are no longer available
"CR Prompt List Keyframes": CR_PromptListKeyframes,
"CR Simple Prompt List": CR_SimplePromptList,
"CR Simple Prompt List Keyframes": CR_SimplePromptListKeyframes,
"CR Cycle Models": CR_CycleModels,
"CR Cycle LoRAs": CR_CycleLoRAs,
"CR Cycle Text": CR_CycleText,
"CR Cycle Text Simple": CR_CycleTextSimple,
"CR Cycle Images": CR_CycleImages,
"CR Cycle Images Simple": CR_CycleImagesSimple,
"CR Model List": CR_ModelList,
"CR LoRA List": CR_LoRAList,
"CR Text List Simple": CR_TextListSimple,
"CR Image List": CR_ImageList,
"CR Image List Simple": CR_ImageListSimple,
}
NODE_DISPLAY_NAME_MAPPINGS = {
### Core Nodes
"CR Image Output": "💾 CR Image Output",
"CR Integer Multiple": "⚙️ CR Integer Multiple",
"CR Latent Batch Size": "⚙️ CR Latent Batch Size",
"CR Seed": "🌱 CR Seed",
"CR Value": "⚙️ CR Value",
"CR Conditioning Mixer": "⚙️ CR Conditioning Mixer",
"CR Select Model": "🔮 CR Select Model",
"CR Prompt Text": "⚙️ CR Prompt Text",
"CR Combine Prompt": "⚙️ CR Combine Prompt",
"CR VAE Decode": "⚙️ CR VAE Decode",
### List Nodes
"CR Text List": "📜 CR Text List",
"CR Prompt List": "📜 CR Prompt List",
"CR Simple List": "📜 CR Simple List",
"CR Float Range List": "📜 CR Float Range List",
"CR Integer Range List": "📜 CR Integer Range List",
"CR Load Value List": "📜 CR Load Value List",
"CR Load Text List": "📜 CR Load Text List",
"CR Binary To Bit List": "📜 CR Binary To Bit List",
"CR Text Cycler": "📜 CR Text Cycler",
"CR Value Cycler": "📜 CR Value Cycler",
### List IO
"CR Load Image List": "⌨️ CR Load Image List",
"CR Load Image List Plus": "⌨️ CR Load Image List Plus",
"CR Load GIF As List": "⌨️ CR Load GIF As List",
"CR Font File List": "⌨️ CR Font File List",
### List Utils
"CR Batch Images From List": "🛠️ CR Batch Images From List",
"CR Intertwine Lists" : "🛠️ CR Intertwine Lists",
"CR Repeater": "🛠️ CR Repeater",
"CR XY Product": "🛠️ CR XY Product",
"CR Text List To String": "🛠️ CR Text List To String",
### Aspect Ratio Nodes
"CR SD1.5 Aspect Ratio": "🔳 CR SD1.5 Aspect Ratio",
"CR SDXL Aspect Ratio": "🔳 CR SDXL Aspect Ratio",
"CR Aspect Ratio": "🔳 CR Aspect Ratio",
"CR Aspect Ratio Banners": "🔳 CR Aspect Ratio Banners",
"CR Aspect Ratio Social Media": "🔳 CR Aspect Ratio Social Media",
"CR_Aspect Ratio For Print": "🔳 CR_Aspect Ratio For Print",
### Legacy Nodes
"CR Image Size": "CR Image Size (Legacy)",
"CR Aspect Ratio SDXL": "CR Aspect Ratio SDXL (Legacy)",
"CR SDXL Prompt Mixer": "CR SDXL Prompt Mixer (Legacy)",
"CR Seed to Int": "CR Seed to Int (Legacy)",
### ControlNet Nodes
"CR Apply ControlNet": "🕹️ CR Apply ControlNet",
"CR Multi-ControlNet Stack": "🕹️ CR Multi-ControlNet Stack",
"CR Apply Multi-ControlNet": "🕹️ CR Apply Multi-ControlNet",
### LoRA Nodes
"CR Load LoRA": "💊 CR Load LoRA",
"CR LoRA Stack": "💊 CR LoRA Stack",
"CR Random LoRA Stack": "💊 CR Random LoRA Stack",
"CR Random Weight LoRA": "💊 CR Random Weight LoRA",
"CR Apply LoRA Stack": "💊 CR Apply LoRA Stack",
### Model Merge Nodes
"CR Apply Model Merge": "⛏️ CR Apply Model Merge",
"CR Model Merge Stack": "⛏️ CR Model Merge Stack",
### Pipe Nodes
"CR Data Bus In": "🚌 CR Data Bus In",
"CR Data Bus Out": "🚌 CR Data Bus Out",
"CR 8 Channel In": "🚌 CR 8 Channel In",
"CR 8 Channel Out": "🚌 CR 8 Channel Out",
"CR Module Pipe Loader": "✈️ CR Module Pipe Loader",
"CR Module Input": "✈️ CR Module Input",
"CR Module Output": "✈️ CR Module Output",
"CR Image Pipe In": "🛩 CR Image Pipe In",
"CR Image Pipe Edit": "🛩️ CR Image Pipe Edit",
"CR Image Pipe Out": "🛩️ CR Image Pipe Out",
"CR Pipe Switch": "🔀️ CR Pipe Switch",
### SDXL Nodes
"CR SDXL Prompt Mix Presets": "🌟 CR SDXL Prompt Mix Presets",
"CR SDXL Style Text": "🌟 CR SDXL Style Text",
"CR SDXL Base Prompt Encoder": "🌟 CR SDXL Base Prompt Encoder",
### Upscale Nodes
"CR Multi Upscale Stack": "🔍 CR Multi Upscale Stack",
"CR Upscale Image": "🔍 CR Upscale Image",
"CR Apply Multi Upscale": "🔍 CR Apply Multi Upscale",
### XY Grid Nodes
"CR XY List": "📉 CR XY List",
"CR XY Interpolate": "📉 CR XY Interpolate",
"CR XY Index": "📉 CR XY Index",
"CR XY From Folder": "📉 CR XY From Folder",
"CR XY Save Grid Image": "📉 CR XY Save Grid Image",
### Graphics Pattern
"CR Halftone Grid" : "🟫 CR Halftone Grid",
"CR Color Bars" : "🟫 CR Color Bars",
"CR Style Bars" : "🟪 CR Style Bars",
"CR Checker Pattern": "🟦 CR Checker Pattern",
"CR Polygons": "🟩 CR Polygons",
"CR Color Gradient": "🟨 CR Color Gradient",
"CR Radial Gradient": "🟨 CR Radial Gradient",
"CR Starburst Lines": "🟧 CR Starburst Lines",
"CR Starburst Colors": "🟧 CR Starburst Colors",
"CR Simple Binary Pattern": "🟥 CR Simple Binary Pattern",
"CR Binary Pattern": "🟥 CR Binary Pattern",
### Graphics Shape
"CR Draw Shape": "🟡 CR Draw Shape",
"CR Draw Pie": "🟢 CR Draw Pie",
"CR Random Shape Pattern": "🔵 CR Random Shape Pattern",
### Graphics Text
"CR Overlay Text": "🔤 CR Overlay Text",
"CR Draw Text": "🔤️ CR Draw Text",
"CR Mask Text": "🔤️ CR Mask Text",
"CR Composite Text": "🔤️ CR Composite Text",
"CR Simple Text Watermark": "🔤️ CR Simple Text Watermark",
"CR Select Font": "🔤️ CR Select Font",
### Graphics Filter
"CR Halftone Filter": "🎨 Halftone Filter",
"CR Color Tint": "🎨 CR Color Tint",
"CR Vignette Filter": "🎨 CR Vignette Filter",
### Graphics Layout
"CR Image Panel": "🌁 CR Image Panel",
"CR Image Grid Panel": "🌁 CR Image Grid Panel",
"CR Simple Text Panel": "🌁 CR Simple Text Panel",
"CR Color Panel": "🌁 CR Color Panel",
"CR Half Drop Panel": "🌁 CR Half Drop Panel",
"CR Diamond Panel": "🌁 CR Diamond Panel",
"CR Page Layout": "🌁 CR Page Layout",
"CR Image Border": "🌁 CR Image Border",
"CR Feathered Border": "🌁 CR Feathered Border",
"CR Overlay Transparent Image": "🌁 CR Overlay Transparent Image",
### Graphics Template
"CR Simple Meme Template": "📱 CR Simple Meme Template",
"CR Simple Banner": "📱 CR Simple Banner",
"CR Comic Panel Templates": "📱 CR Comic Panel Templates",
"CR Simple Image Compare": "📱 CR Simple Image Compare",
"CR Thumbnail Preview": "📱 CR Thumbnail Preview",
"CR Seamless Checker": "📱 CR Seamless Checker",
### Utils Logic
"CR Image Input Switch": "🔀 CR Image Input Switch",
"CR Image Input Switch (4 way)": "🔀 CR Image Input Switch (4 way)",
"CR Latent Input Switch": "🔀 CR Latent Input Switch",
"CR Conditioning Input Switch": "🔀 CR Conditioning Input Switch",
"CR Clip Input Switch": "🔀 CR Clip Input Switch",
"CR Model Input Switch": "🔀 CR Model Input Switch",
"CR ControlNet Input Switch": "🔀 CR ControlNet Input Switch",
"CR VAE Input Switch": "🔀 CR VAE Input Switch",
"CR Text Input Switch": "🔀 CR Text Input Switch",
"CR Text Input Switch (4 way)": "🔀 CR Text Input Switch (4 way)",
"CR Switch Model and CLIP": "🔀 CR Switch Model and CLIP",
### Utils Process
"CR Batch Process Switch": "🔂 CR Batch Process Switch",
"CR Img2Img Process Switch": "🔂 CR Img2Img Process Switch",
"CR Hires Fix Process Switch": "🔂 CR Hires Fix Process Switch",
### Utils Index
"CR Index":"🔢 CR Index",
"CR Index Increment": "🔢 CR Index Increment",
"CR Index Multiply": "🔢 CR Index Multiply",
"CR Index Reset": "🔢 CR Index Reset",
"CR Trigger": "🔢 CR Trigger",
### Utils Conversion
"CR String To Number": "🔧 CR String To Number",
"CR String To Combo": "🔧 CR String To Combo",
"CR Float To String": "🔧 CR Float To String",
"CR Float To Integer": "🔧 CR Float To Integer",
"CR Integer To String": "🔧 CR Integer To String",
"CR String To Boolean": "🔧 CR String To Boolean",
### Utils Random
"CR Random Hex Color": "🎲 CR Random Hex Color",
"CR Random RGB": "🎲 CR Random RGB",
"CR Random Multiline Values": "🎲 CR Random Multiline Values",
"CR Random Multiline Colors": "🎲 CR Random Multiline Colors",
"CR Random RGB Gradient": "🎲 CR Random RGB Gradient",
"CR Random Panel Codes": "🎲 CR Random Panel Codes",
### Utils Text
"CR Text": "🔤 CR Text",
"CR Multiline Text": "🔤 CR Multiline Text",
"CR Split String": "🔤 CR Split String",
"CR Text Concatenate": "🔤 CR Text Concatenate",
"CR Text Replace": "🔤 CR Text Replace",
"CR Text Blacklist": "🔤 Text Blacklist",
"CR Text Length": "🔤 CR Text Length",
"CR Text Operation": "🔤 CR Text Operation",
"CR Save Text To File": "🔤 CR Save Text To File",
### Utils Conditional
"CR Set Value On Boolean": "⚙️ CR Set Value On Boolean",
"CR Set Value On Binary": "⚙️ CR Set Value On Binary",
"CR Set Value on String": "⚙️ CR Set Value on String",
"CR Set Switch From String": "⚙️ CR Set Switch From String",
### Utils Other
"CR Integer Multiple": "⚙️ CR Integer Multiple",
"CR Value": "⚙️ CR Value",
"CR Clamp Value": "⚙️ CR Clamp Value",
"CR Math Operation": "⚙️ CR Math Operation",
"CR Get Parameter From Prompt": "⚙️ CR Get Parameter From Prompt",
"CR Select Resize Method": "⚙️ CR Select Resize Method",
"CR Select ISO Size": "⚙️ CR Select ISO Size",
### Animation Nodes
# Schedules
"CR Simple Schedule": "📋 CR Simple Schedule",
"CR Central Schedule": "📋 CR Central Schedule",
"CR Combine Schedules": "📋 CR Combine Schedules",
"CR Output Schedule To File": "📋 CR Output Schedule To File",
"CR Load Schedule From File": "📋 CR Load Schedule From File",
"CR Schedule Input Switch": "📋 CR Schedule Input Switch",
"CR Bit Schedule": "📋 CR Bit Schedule",
# Schedulers
"CR Simple Value Scheduler": "📑 CR Simple Value Scheduler",
"CR Simple Text Scheduler": "📑 CR Simple Text Scheduler",
"CR Value Scheduler": "📑 CR Value Scheduler",
"CR Text Scheduler": "📑 CR Text Scheduler",
"CR Load Scheduled Models": "📑 CR Load Scheduled Models",
"CR Load Scheduled LoRAs": "📑 CR Load Scheduled LoRAs",
"CR Prompt Scheduler": "📑 CR Prompt Scheduler",
"CR Simple Prompt Scheduler": "📑 CR Simple Prompt Scheduler",
# Prompt
"CR Keyframe List": "📝 CR Keyframe List",
#"CR Load Prompt Style": "📝 CR Load Prompt Style",
"CR Encode Scheduled Prompts": "📝 CR Encode Scheduled Prompts",
# Interpolation
"CR Gradient Float": "🔢 CR Gradient Float",
"CR Gradient Integer": "🔢 CR Gradient Integer",
"CR Increment Float": "🔢 CR Increment Float",
"CR Increment Integer": "🔢 CR Increment Integer",
"CR Interpolate Latents": "🔢 CR Interpolate Latents",
# Utils
"CR Debatch Frames": "🛠️ CR Debatch Frames",
"CR Current Frame": "🛠️ CR Current Frame",
# IO
"CR Load Animation Frames": "⌨️ CR Load Animation Frames",
"CR Load Flow Frames": "⌨️ CR Load Flow Frames",
"CR Output Flow Frames": "⌨️ CR Output Flow Frames",
### Legacy
"CR Prompt List Keyframes": "CR Prompt List Keyframes (Legacy)",
"CR Simple Prompt List": "CR Simple Prompt List (Legacy)",
"CR Simple Prompt List Keyframes": "CR Simple Prompt List Keyframes (Legacy)",
"CR Cycle Models": "CR Cycle Models (Legacy)",
"CR Cycle LoRAs": "CR Cycle LoRAs (Legacy)",
"CR Cycle Text": "CR Cycle Text (Legacy)",
"CR Cycle Text Simple": "CR Cycle Text Simple (Legacy)",
"CR Cycle Images": "CR Cycle Images (Legacy)",
"CR Cycle Images Simple": "CR Cycle Images Simple (Legacy)",
"CR Model List": "CR Model List (Legacy)",
"CR LoRA List": "CR LoRA List (Legacy)",
"CR Text List Simple": "CR Text List Simple (Legacy)",
"CR Image List": "CR Image List (Legacy)",
"CR Image List Simple": "CR Image List Simple (Legacy)",
"CR Input Text List": "CR Input Text List (Legacy)",
}
@@ -0,0 +1,484 @@
#---------------------------------------------------------------------------------------------------------------------#
# Comfyroll Studio custom nodes by RockOfFire and Akatsuzi https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes
# for ComfyUI https://github.com/comfyanonymous/ComfyUI
#---------------------------------------------------------------------------------------------------------------------#
import numpy as np
import torch
import os
import random
from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageEnhance
from ..config import color_mapping
font_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "fonts")
file_list = [f for f in os.listdir(font_dir) if os.path.isfile(os.path.join(font_dir, f)) and f.lower().endswith(".ttf")]
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def align_text(align, img_height, text_height, text_pos_y, margins):
if align == "center":
text_plot_y = img_height / 2 - text_height / 2 + text_pos_y
elif align == "top":
text_plot_y = text_pos_y + margins
elif align == "bottom":
text_plot_y = img_height - text_height + text_pos_y - margins
return text_plot_y
def justify_text(justify, img_width, line_width, margins):
if justify == "left":
text_plot_x = 0 + margins
elif justify == "right":
text_plot_x = img_width - line_width - margins
elif justify == "center":
text_plot_x = img_width/2 - line_width/2
return text_plot_x
def get_text_size(draw, text, font):
bbox = draw.textbbox((0, 0), text, font=font)
# Calculate the text width and height
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
return text_width, text_height
def draw_masked_text(text_mask, text,
font_name, font_size,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options):
# Create the drawing context
draw = ImageDraw.Draw(text_mask)
# Define font settings
font_folder = "fonts"
font_file = os.path.join(font_folder, font_name)
resolved_font_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), font_file)
font = ImageFont.truetype(str(resolved_font_path), size=font_size)
# Split the input text into lines
text_lines = text.split('\n')
# Calculate the size of the text plus padding for the tallest line
max_text_width = 0
max_text_height = 0
for line in text_lines:
# Calculate the width and height of the current line
line_width, line_height = get_text_size(draw, line, font)
line_height = line_height + line_spacing
max_text_width = max(max_text_width, line_width)
max_text_height = max(max_text_height, line_height)
# Get the image width and height
image_width, image_height = text_mask.size
image_center_x = image_width / 2
image_center_y = image_height / 2
text_pos_y = position_y
sum_text_plot_y = 0
text_height = max_text_height * len(text_lines)
for line in text_lines:
# Calculate the width of the current line
line_width, _ = get_text_size(draw, line, font)
# Get the text x and y positions for each line
text_plot_x = position_x + justify_text(justify, image_width, line_width, margins)
text_plot_y = align_text(align, image_height, text_height, text_pos_y, margins)
# Add the current line to the text mask
draw.text((text_plot_x, text_plot_y), line, fill=255, font=font)
text_pos_y += max_text_height # Move down for the next line
sum_text_plot_y += text_plot_y # Sum the y positions
# Calculate centers for rotation
text_center_x = text_plot_x + max_text_width / 2
text_center_y = sum_text_plot_y / len(text_lines)
if rotation_options == "text center":
rotated_text_mask = text_mask.rotate(rotation_angle, center=(text_center_x, text_center_y))
elif rotation_options == "image center":
rotated_text_mask = text_mask.rotate(rotation_angle, center=(image_center_x, image_center_y))
return rotated_text_mask
def draw_text_on_image(draw, y_position, bar_width, bar_height, text, font, text_color, font_outline):
# Calculate the width and height of the text
text_width, text_height = get_text_size(draw, text, font)
if font_outline == "thin":
outline_thickness = text_height // 40
elif font_outline == "thick":
outline_thickness = text_height // 20
elif font_outline == "extra thick":
outline_thickness = text_height // 10
outline_color = (0, 0, 0)
text_lines = text.split('\n')
if len(text_lines) == 1:
x = (bar_width - text_width) // 2
y = y_position + (bar_height - text_height) // 2 - (bar_height * 0.10)
if font_outline == "none":
draw.text((x, y), text, fill=text_color, font=font)
else:
draw.text((x, y), text, fill=text_color, font=font, stroke_width=outline_thickness, stroke_fill='black')
elif len(text_lines) > 1:
# Calculate the width and height of the text
text_width, text_height = get_text_size(draw, text_lines[0], font)
x = (bar_width - text_width) // 2
y = y_position + (bar_height - text_height * 2) // 2 - (bar_height * 0.15)
if font_outline == "none":
draw.text((x, y), text_lines[0], fill=text_color, font=font)
else:
draw.text((x, y), text_lines[0], fill=text_color, font=font, stroke_width=outline_thickness, stroke_fill='black')
# Calculate the width and height of the text
text_width, text_height = get_text_size(draw, text_lines[1], font)
x = (bar_width - text_width) // 2
y = y_position + (bar_height - text_height * 2) // 2 + text_height - (bar_height * 0.00)
if font_outline == "none":
draw.text((x, y), text_lines[1], fill=text_color, font=font)
else:
draw.text((x, y), text_lines[1], fill=text_color, font=font, stroke_width=outline_thickness, stroke_fill='black')
def get_font_size(draw, text, max_width, max_height, font_path, max_font_size):
# Adjust the max-width to allow for start and end padding
max_width = max_width * 0.9
# Start with the maximum font size
font_size = max_font_size
font = ImageFont.truetype(str(font_path), size=font_size)
# Get the first two lines
text_lines = text.split('\n')[:2]
if len(text_lines) == 2:
font_size = min(max_height//2, max_font_size)
font = ImageFont.truetype(str(font_path), size=font_size)
# Calculate max text width and height with the current font
max_text_width = 0
longest_line = text_lines[0]
for line in text_lines:
# Calculate the width and height of the current line
line_width, line_height = get_text_size(draw, line, font)
if line_width > max_text_width:
longest_line = line
max_text_width = max(max_text_width, line_width)
# Calculate the width and height of the text
text_width, text_height = get_text_size(draw, text, font)
# Decrease the font size until it fits within the bounds
while max_text_width > max_width or text_height > 0.88 * max_height / len(text_lines):
font_size -= 1
font = ImageFont.truetype(str(font_path), size=font_size)
max_text_width, text_height = get_text_size(draw, longest_line, font)
return font
def hex_to_rgb(hex_color):
hex_color = hex_color.lstrip('#') # Remove the '#' character, if present
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
return (r, g, b)
def text_panel(image_width, image_height, text,
font_name, font_size, font_color,
font_outline_thickness, font_outline_color,
background_color,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options):
"""
Create an image with text overlaid on a background.
Returns:
PIL.Image.Image: Image with text overlaid on the background.
"""
# Create PIL images for the text and background layers and text mask
size = (image_width, image_height)
panel = Image.new('RGB', size, background_color)
# Draw the text on the text mask
image_out = draw_text(panel, text,
font_name, font_size, font_color,
font_outline_thickness, font_outline_color,
background_color,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options)
return image_out
def draw_text(panel, text,
font_name, font_size, font_color,
font_outline_thickness, font_outline_color,
bg_color,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options):
# Create the drawing context
draw = ImageDraw.Draw(panel)
# Define font settings
font_folder = "fonts"
font_file = os.path.join(font_folder, font_name)
resolved_font_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), font_file)
font = ImageFont.truetype(str(resolved_font_path), size=font_size)
# Split the input text into lines
text_lines = text.split('\n')
# Calculate the size of the text plus padding for the tallest line
max_text_width = 0
max_text_height = 0
for line in text_lines:
# Calculate the width and height of the current line
line_width, line_height = get_text_size(draw, line, font)
line_height = line_height + line_spacing
max_text_width = max(max_text_width, line_width)
max_text_height = max(max_text_height, line_height)
# Get the image center
image_center_x = panel.width / 2
image_center_y = panel.height / 2
text_pos_y = position_y
sum_text_plot_y = 0
text_height = max_text_height * len(text_lines)
for line in text_lines:
# Calculate the width and height of the current line
line_width, line_height = get_text_size(draw, line, font)
# Get the text x and y positions for each line
text_plot_x = position_x + justify_text(justify, panel.width, line_width, margins)
text_plot_y = align_text(align, panel.height, text_height, text_pos_y, margins)
# Add the current line to the text mask
draw.text((text_plot_x, text_plot_y), line, fill=font_color, font=font, stroke_width=font_outline_thickness, stroke_fill=font_outline_color)
text_pos_y += max_text_height # Move down for the next line
sum_text_plot_y += text_plot_y # Sum the y positions
text_center_x = text_plot_x + max_text_width / 2
text_center_y = sum_text_plot_y / len(text_lines)
if rotation_options == "text center":
rotated_panel = panel.rotate(rotation_angle, center=(text_center_x, text_center_y), resample=Image.BILINEAR)
elif rotation_options == "image center":
rotated_panel = panel.rotate(rotation_angle, center=(image_center_x, image_center_y), resample=Image.BILINEAR)
return rotated_panel
def combine_images(images, layout_direction='horizontal'):
"""
Combine a list of PIL Image objects either horizontally or vertically.
Args:
images (list of PIL.Image.Image): List of PIL Image objects to combine.
layout_direction (str): 'horizontal' for horizontal layout, 'vertical' for vertical layout.
Returns:
PIL.Image.Image: Combined image.
"""
if layout_direction == 'horizontal':
combined_width = sum(image.width for image in images)
combined_height = max(image.height for image in images)
else:
combined_width = max(image.width for image in images)
combined_height = sum(image.height for image in images)
combined_image = Image.new('RGB', (combined_width, combined_height))
x_offset = 0
y_offset = 0 # Initialize y_offset for vertical layout
for image in images:
combined_image.paste(image, (x_offset, y_offset))
if layout_direction == 'horizontal':
x_offset += image.width
else:
y_offset += image.height
return combined_image
def apply_outline_and_border(images, outline_thickness, outline_color, border_thickness, border_color):
for i, image in enumerate(images):
# Apply the outline
if outline_thickness > 0:
image = ImageOps.expand(image, outline_thickness, fill=outline_color)
# Apply the border
if border_thickness > 0:
image = ImageOps.expand(image, border_thickness, fill=border_color)
images[i] = image
return images
def get_color_values(color, color_hex, color_mapping):
#Get RGB values for the text and background colors.
if color == "custom":
color_rgb = hex_to_rgb(color_hex)
else:
color_rgb = color_mapping.get(color, (0, 0, 0)) # Default to black if the color is not found
return color_rgb
def hex_to_rgb(hex_color):
hex_color = hex_color.lstrip('#') # Remove the '#' character, if present
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
return (r, g, b)
def crop_and_resize_image(image, target_width, target_height):
width, height = image.size
aspect_ratio = width / height
target_aspect_ratio = target_width / target_height
if aspect_ratio > target_aspect_ratio:
# Crop the image's width to match the target aspect ratio
crop_width = int(height * target_aspect_ratio)
crop_height = height
left = (width - crop_width) // 2
top = 0
else:
# Crop the image's height to match the target aspect ratio
crop_height = int(width / target_aspect_ratio)
crop_width = width
left = 0
top = (height - crop_height) // 2
# Perform the center cropping
cropped_image = image.crop((left, top, left + crop_width, top + crop_height))
return cropped_image
def create_and_paste_panel(page, border_thickness, outline_thickness,
panel_width, panel_height, page_width,
panel_color, bg_color, outline_color,
images, i, j, k, len_images, reading_direction):
panel = Image.new("RGB", (panel_width, panel_height), panel_color)
if k < len_images:
img = images[k]
image = crop_and_resize_image(img, panel_width, panel_height)
image.thumbnail((panel_width, panel_height), Image.Resampling.LANCZOS)
panel.paste(image, (0, 0))
panel = ImageOps.expand(panel, border=outline_thickness, fill=outline_color)
panel = ImageOps.expand(panel, border=border_thickness, fill=bg_color)
new_panel_width, new_panel_height = panel.size
if reading_direction == "right to left":
page.paste(panel, (page_width - (j + 1) * new_panel_width, i * new_panel_height))
else:
page.paste(panel, (j * new_panel_width, i * new_panel_height))
def reduce_opacity(img, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if img.mode != 'RGBA':
img = img.convert('RGBA')
else:
img = img.copy()
alpha = img.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
img.putalpha(alpha)
return img
def random_hex_color():
# Generate three random values for RGB
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
# Convert RGB to hex format
hex_color = "#{:02x}{:02x}{:02x}".format(r, g, b)
return hex_color
def random_rgb():
# Generate three random values for RGB
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
# Format RGB as a string in the format "128,128,128"
rgb_string = "{},{},{}".format(r, g, b)
return rgb_string
def make_grid_panel(images, max_columns):
# Calculate dimensions for the grid
num_images = len(images)
num_rows = (num_images - 1) // max_columns + 1
combined_width = max(image.width for image in images) * min(max_columns, num_images)
combined_height = max(image.height for image in images) * num_rows
combined_image = Image.new('RGB', (combined_width, combined_height))
x_offset, y_offset = 0, 0 # Initialize offsets
for image in images:
combined_image.paste(image, (x_offset, y_offset))
x_offset += image.width
if x_offset >= max_columns * image.width:
x_offset = 0
y_offset += image.height
return combined_image
def interpolate_color(color0, color1, t):
"""
Interpolate between two colors.
"""
return tuple(int(c0 * (1 - t) + c1 * t) for c0, c1 in zip(color0, color1))
@@ -0,0 +1,501 @@
#---------------------------------------------------------------------------------------------------------------------#
# Comfyroll Studio custom nodes by RockOfFire and Akatsuzi https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes
# for ComfyUI https://github.com/comfyanonymous/ComfyUI
#---------------------------------------------------------------------------------------------------------------------#
import numpy as np
import torch
import os
import platform
from PIL import Image, ImageDraw, ImageOps, ImageFont
from ..categories import icons
from ..config import color_mapping, COLORS
from .functions_graphics import *
'''
try:
from bidi.algorithm import get_display
except ImportError:
import subprocess
subprocess.check_call(['python', '-m', 'pip', 'install', 'python_bidi'])
try:
import arabic_reshaper
except ImportError:
import subprocess
subprocess.check_call(['python', '-m', 'pip', 'install', 'arabic_reshaper'])
'''
def get_offset_for_true_mm(text, draw, font):
anchor_bbox = draw.textbbox((0, 0), text, font=font, anchor='lt')
anchor_center = (anchor_bbox[0] + anchor_bbox[2]) // 2, (anchor_bbox[1] + anchor_bbox[3]) // 2
mask_bbox = font.getmask(text).getbbox()
mask_center = (mask_bbox[0] + mask_bbox[2]) // 2, (mask_bbox[1] + mask_bbox[3]) // 2
return anchor_center[0] - mask_center[0], anchor_center[1] - mask_center[1]
class AnyType(str):
"""A special type that can be connected to any other types. Credit to pythongosssss"""
def __ne__(self, __value: object) -> bool:
return False
any_type = AnyType("*")
#---------------------------------------------------------------------------------------------------------------------#
ALIGN_OPTIONS = ["center", "top", "bottom"]
ROTATE_OPTIONS = ["text center", "image center"]
JUSTIFY_OPTIONS = ["center", "left", "right"]
PERSPECTIVE_OPTIONS = ["top", "bottom", "left", "right"]
#---------------------------------------------------------------------------------------------------------------------#
class CR_OverlayText:
@classmethod
def INPUT_TYPES(s):
font_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "fonts")
file_list = [f for f in os.listdir(font_dir) if os.path.isfile(os.path.join(font_dir, f)) and f.lower().endswith(".ttf")]
return {"required": {
"image": ("IMAGE",),
"text": ("STRING", {"multiline": True, "default": "text"}),
"font_name": (file_list,),
"font_size": ("INT", {"default": 50, "min": 1, "max": 1024}),
"font_color": (COLORS,),
"align": (ALIGN_OPTIONS,),
"justify": (JUSTIFY_OPTIONS,),
"margins": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"line_spacing": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"position_x": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"position_y": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"rotation_angle": ("FLOAT", {"default": 0.0, "min": -360.0, "max": 360.0, "step": 0.1}),
"rotation_options": (ROTATE_OPTIONS,),
},
"optional": {"font_color_hex": ("STRING", {"multiline": False, "default": "#000000"})
}
}
RETURN_TYPES = ("IMAGE", "STRING",)
RETURN_NAMES = ("IMAGE", "show_help",)
FUNCTION = "overlay_text"
CATEGORY = icons.get("Comfyroll/Graphics/Text")
def overlay_text(self, image, text, font_name, font_size, font_color,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options,
font_color_hex='#000000'):
# Get RGB values for the text color
text_color = get_color_values(font_color, font_color_hex, color_mapping)
# Convert tensor images
image_3d = image[0, :, :, :]
# Create PIL images for the text and background layers and text mask
back_image = tensor2pil(image_3d)
text_image = Image.new('RGB', back_image.size, text_color)
text_mask = Image.new('L', back_image.size)
# Draw the text on the text mask
rotated_text_mask = draw_masked_text(text_mask, text, font_name, font_size,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options)
# Composite the text image onto the background image using the rotated text mask
image_out = Image.composite(text_image, back_image, rotated_text_mask)
show_help = "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki/Text-Nodes#cr-overlay-text"
# Convert the PIL image back to a torch tensor
return (pil2tensor(image_out), show_help,)
#---------------------------------------------------------------------------------------------------------------------#
class CR_DrawText:
@classmethod
def INPUT_TYPES(s):
font_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "fonts")
file_list = [f for f in os.listdir(font_dir) if os.path.isfile(os.path.join(font_dir, f)) and f.lower().endswith(".ttf")]
return {"required": {
"image_width": ("INT", {"default": 512, "min": 64, "max": 2048}),
"image_height": ("INT", {"default": 512, "min": 64, "max": 2048}),
"text": ("STRING", {"multiline": True, "default": "text"}),
"font_name": (file_list,),
"font_size": ("INT", {"default": 50, "min": 1, "max": 1024}),
"font_color": (COLORS,),
"background_color": (COLORS,),
"align": (ALIGN_OPTIONS,),
"justify": (JUSTIFY_OPTIONS,),
"margins": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"line_spacing": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"position_x": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"position_y": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"rotation_angle": ("FLOAT", {"default": 0.0, "min": -360.0, "max": 360.0, "step": 0.1}),
"rotation_options": (ROTATE_OPTIONS,),
},
"optional": {
"font_color_hex": ("STRING", {"multiline": False, "default": "#000000"}),
"bg_color_hex": ("STRING", {"multiline": False, "default": "#000000"})
}
}
RETURN_TYPES = ("IMAGE", "STRING",)
RETURN_NAMES = ("IMAGE", "show_help",)
FUNCTION = "draw_text"
CATEGORY = icons.get("Comfyroll/Graphics/Text")
def draw_text(self, image_width, image_height, text,
font_name, font_size, font_color,
background_color,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options,
font_color_hex='#000000', bg_color_hex='#000000'):
# Get RGB values for the text and background colors
text_color = get_color_values(font_color, font_color_hex, color_mapping)
bg_color = get_color_values(background_color, bg_color_hex, color_mapping)
# Create PIL images for the text and background layers and text mask
size = (image_width, image_height)
text_image = Image.new('RGB', size, text_color)
back_image = Image.new('RGB', size, bg_color)
text_mask = Image.new('L', back_image.size)
# Draw the text on the text mask
rotated_text_mask = draw_masked_text(text_mask, text, font_name, font_size,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options)
# Composite the text image onto the background image using the rotated text mask
image_out = Image.composite(text_image, back_image, rotated_text_mask)
show_help = "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki/Text-Nodes#cr-draw-text"
# Convert the PIL image back to a torch tensor
return (pil2tensor(image_out), show_help,)
#---------------------------------------------------------------------------------------------------------------------#
class CR_MaskText:
@classmethod
def INPUT_TYPES(s):
font_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "fonts")
file_list = [f for f in os.listdir(font_dir) if os.path.isfile(os.path.join(font_dir, f)) and f.lower().endswith(".ttf")]
return {"required": {
"image": ("IMAGE",),
"text": ("STRING", {"multiline": True, "default": "text"}),
"font_name": (file_list,),
"font_size": ("INT", {"default": 50, "min": 1, "max": 1024}),
"background_color": (COLORS,),
"align": (ALIGN_OPTIONS,),
"justify": (JUSTIFY_OPTIONS,),
"margins": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"line_spacing": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"position_x": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"position_y": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"rotation_angle": ("FLOAT", {"default": 0.0, "min": -360.0, "max": 360.0, "step": 0.1}),
"rotation_options": (ROTATE_OPTIONS,),
},
"optional": {
"bg_color_hex": ("STRING", {"multiline": False, "default": "#000000"})
}
}
RETURN_TYPES = ("IMAGE", "STRING",)
RETURN_NAMES = ("IMAGE", "show_help",)
FUNCTION = "mask_text"
CATEGORY = icons.get("Comfyroll/Graphics/Text")
def mask_text(self, image, text, font_name, font_size,
margins, line_spacing,
position_x, position_y, background_color,
align, justify,
rotation_angle, rotation_options,
bg_color_hex='#000000'):
# Get RGB values for the background color
bg_color = get_color_values(background_color, bg_color_hex, color_mapping)
# Convert tensor images
image_3d = image[0, :, :, :]
# Create PIL images for the text and background layers and text mask
text_image = tensor2pil(image_3d)
text_mask = Image.new('L', text_image.size)
background_image = Image.new('RGB', text_mask.size, bg_color)
# Draw the text on the text mask
rotated_text_mask = draw_masked_text(text_mask, text, font_name, font_size,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options)
# Invert the text mask (so the text is white and the background is black)
text_mask = ImageOps.invert(rotated_text_mask)
# Composite the text image onto the background image using the inverted text mask
image_out = Image.composite(background_image, text_image, text_mask)
show_help = "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki/Text-Nodes#cr-mask-text"
# Convert the PIL image back to a torch tensor
return (pil2tensor(image_out), show_help,)
#---------------------------------------------------------------------------------------------------------------------#
class CR_CompositeText:
@classmethod
def INPUT_TYPES(s):
font_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "fonts")
file_list = [f for f in os.listdir(font_dir) if os.path.isfile(os.path.join(font_dir, f)) and f.lower().endswith(".ttf")]
return {"required": {
"image_text": ("IMAGE",),
"image_background": ("IMAGE",),
"text": ("STRING", {"multiline": True, "default": "text"}),
"font_name": (file_list,),
"font_size": ("INT", {"default": 50, "min": 1, "max": 1024}),
"align": (ALIGN_OPTIONS,),
"justify": (JUSTIFY_OPTIONS,),
"margins": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"line_spacing": ("INT", {"default": 0, "min": -1024, "max": 1024}),
"position_x": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"position_y": ("INT", {"default": 0, "min": -4096, "max": 4096}),
"rotation_angle": ("FLOAT", {"default": 0.0, "min": -360.0, "max": 360.0, "step": 0.1}),
"rotation_options": (ROTATE_OPTIONS,),
}
}
RETURN_TYPES = ("IMAGE", "STRING",)
RETURN_NAMES = ("IMAGE", "show_help",)
FUNCTION = "composite_text"
CATEGORY = icons.get("Comfyroll/Graphics/Text")
def composite_text(self, image_text, image_background, text,
font_name, font_size,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options):
# Convert tensor images
image_text_3d = image_text[0, :, :, :]
image_back_3d = image_background[0, :, :, :]
# Create PIL images for the text and background layers and text mask
text_image = tensor2pil(image_text_3d)
back_image = tensor2pil(image_back_3d)
text_mask = Image.new('L', back_image.size)
# Draw the text on the text mask
rotated_text_mask = draw_masked_text(text_mask, text, font_name, font_size,
margins, line_spacing,
position_x, position_y,
align, justify,
rotation_angle, rotation_options)
# Composite the text image onto the background image using the rotated text mask
image_out = Image.composite(text_image, back_image, rotated_text_mask)
show_help = "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki/Text-Nodes#cr-composite-text"
# Convert the PIL image back to a torch tensor
return (pil2tensor(image_out), show_help,)
#---------------------------------------------------------------------------------------------------------------------#
class CR_ArabicTextRTL:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"arabic_text": ("STRING", {"multiline": True, "default": "شمس"}),
}
}
RETURN_TYPES = ("STRING", "STRING", )
RETURN_NAMES = ("arabic_text_rtl", "show help", )
FUNCTION = "adjust_arabic_to_rtl"
CATEGORY = icons.get("Comfyroll/Graphics/Text")
def adjust_arabic_to_rtl(self, arabic_text):
"""
Adjust Arabic text to read from right to left (RTL).
Args:
arabic_text (str): The Arabic text to be adjusted.
Returns:
str: The adjusted Arabic text in RTL format.
"""
arabic_text_reshaped = arabic_reshaper.reshape(arabic_text)
rtl_text = get_display(arabic_text_reshaped)
show_help = "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki/Text-Nodes#cr-arabic-text-rtl"
return (rtl_text, show_help,)
#---------------------------------------------------------------------------------------------------------------------#
class CR_SimpleTextWatermark:
@classmethod
def INPUT_TYPES(s):
font_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "fonts")
file_list = [f for f in os.listdir(font_dir) if os.path.isfile(os.path.join(font_dir, f)) and f.lower().endswith(".ttf")]
ALIGN_OPTIONS = ["center", "top left", "top center", "top right", "bottom left", "bottom center", "bottom right"]
return {"required": {
"image": ("IMAGE",),
"text": ("STRING", {"multiline": False, "default": "@ your name"}),
"align": (ALIGN_OPTIONS,),
"opacity": ("FLOAT", {"default": 0.30, "min": 0.00, "max": 1.00, "step": 0.01}),
"font_name": (file_list,),
"font_size": ("INT", {"default": 50, "min": 1, "max": 1024}),
"font_color": (COLORS,),
"x_margin": ("INT", {"default": 20, "min": -1024, "max": 1024}),
"y_margin": ("INT", {"default": 20, "min": -1024, "max": 1024}),
},
"optional": {
"font_color_hex": ("STRING", {"multiline": False, "default": "#000000"}),
}
}
RETURN_TYPES = ("IMAGE", "STRING", )
RETURN_NAMES = ("IMAGE", "show_help", )
FUNCTION = "overlay_text"
CATEGORY = icons.get("Comfyroll/Graphics/Text")
def overlay_text(self, image, text, align,
font_name, font_size, font_color,
opacity, x_margin, y_margin, font_color_hex='#000000'):
# Get RGB values for the text color
text_color = get_color_values(font_color, font_color_hex, color_mapping)
total_images = []
for img in image:
# Create PIL images for the background layer
img = tensor2pil(img)
textlayer = Image.new("RGBA", img.size)
draw = ImageDraw.Draw(textlayer)
# Load the font
font_file = os.path.join("fonts", str(font_name))
resolved_font_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), font_file)
font = ImageFont.truetype(str(resolved_font_path), size=font_size)
# Get the size of the text
textsize = get_text_size(draw, text, font)
# Calculate the position to place the text based on the alignment
if align == 'center':
textpos = [(img.size[0] - textsize[0]) // 2, (img.size[1] - textsize[1]) // 2]
elif align == 'top left':
textpos = [x_margin, y_margin]
elif align == 'top center':
textpos = [(img.size[0] - textsize[0]) // 2, y_margin]
elif align == 'top right':
textpos = [img.size[0] - textsize[0] - x_margin, y_margin]
elif align == 'bottom left':
textpos = [x_margin, img.size[1] - textsize[1] - y_margin]
elif align == 'bottom center':
textpos = [(img.size[0] - textsize[0]) // 2, img.size[1] - textsize[1] - y_margin]
elif align == 'bottom right':
textpos = [img.size[0] - textsize[0] - x_margin, img.size[1] - textsize[1] - y_margin]
# Draw the text on the text layer
draw.text(textpos, text, font=font, fill=text_color)
# Adjust the opacity of the text layer if needed
if opacity != 1:
textlayer = reduce_opacity(textlayer, opacity)
# Composite the text layer on top of the original image
out_image = Image.composite(textlayer, img, textlayer)
# convert to tensor
out_image = np.array(out_image.convert("RGB")).astype(np.float32) / 255.0
out_image = torch.from_numpy(out_image).unsqueeze(0)
total_images.append(out_image)
images_out = torch.cat(total_images, 0)
show_help = "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki/Text-Nodes#cr-simple-text-watermark"
# Convert the PIL image back to a torch tensor
return (images_out, show_help, )
#---------------------------------------------------------------------------------------------------------------------#
class CR_SelectFont:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
if platform.system() == "Windows":
system_root = os.environ.get("SystemRoot")
font_dir = os.path.join(system_root, "Fonts") if system_root else None
# Default debian-based Linux & MacOS font dirs
elif platform.system() == "Linux":
font_dir = "/usr/share/fonts/truetype"
elif platform.system() == "Darwin":
font_dir = "/System/Library/Fonts"
file_list = [f for f in os.listdir(font_dir) if os.path.isfile(os.path.join(font_dir, f)) and f.lower().endswith(".ttf")]
return {"required": {
"font_name": (file_list,),
}
}
RETURN_TYPES = (any_type, "STRING",)
RETURN_NAMES = ("font_name", "show_help",)
FUNCTION = "select_font"
CATEGORY = icons.get("Comfyroll/Graphics/Text")
def select_font(self, font_name):
show_help = "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes/wiki/Text-Nodes#cr-select-font"
return (font_name, show_help,)
#---------------------------------------------------------------------------------------------------------------------#
# MAPPINGS
#---------------------------------------------------------------------------------------------------------------------#
# For reference only, actual mappings are in __init__.py
'''
NODE_CLASS_MAPPINGS = {
"CR Overlay Text": CR_OverlayText,
"CR Draw Text": CR_DrawText,
"CR Mask Text": CR_MaskText,
"CR Composite Text": CR_CompositeText,
"CR Draw Perspective Text": CR_DrawPerspectiveText,
"CR Arabic Text RTL": CR_ArabicTextRTL,
"CR Simple Text Watermark": CR_SimpleTextWatermark,
"CR Select Font": CR_SelectFont,
}
'''
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,49 @@
import os
import importlib.util
import sys
from pathlib import Path
# 获取当前包目录的路径
current_dir = Path(__file__).parent
nodes_dir = current_dir / "nodes"
# 设置WEB目录路径 - 这是关键配置
WEB_DIRECTORY = "./web"
# 初始化全局映射字典
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
# 遍历nodes目录中的所有Python文件
for file_path in nodes_dir.glob("*.py"):
# 跳过__init__.py文件
if file_path.name == "__init__.py":
continue
# 提取模块名(不含.py后缀)
module_name = file_path.stem
# 使用importlib动态加载模块
spec = importlib.util.spec_from_file_location(f"goohaitools.nodes.{module_name}", file_path)
module = importlib.util.module_from_spec(spec)
try:
# 执行模块代码
spec.loader.exec_module(module)
# 检查并合并NODE_CLASS_MAPPINGS
if hasattr(module, 'NODE_CLASS_MAPPINGS'):
NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS)
# 检查并合并NODE_DISPLAY_NAME_MAPPINGS
if hasattr(module, 'NODE_DISPLAY_NAME_MAPPINGS'):
NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
except Exception as e:
print(f"Error loading node module {module_name}: {str(e)}")
continue
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
# 打印加载信息
print(f'\033[92m[GoohaiTools]\033[0m \033[93m{len(NODE_CLASS_MAPPINGS)} nodes\033[0m loaded | \033[94mColorWidget enabled\033[0m')
@@ -0,0 +1,259 @@
import os
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
import torch
class 孤海_图像添加水印:
def __init__(self):
# 修改为上级目录下的fonts文件夹
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
self.font_dir = os.path.join(parent_dir, "fonts")
# 确保字体文件夹存在
if not os.path.exists(self.font_dir):
os.makedirs(self.font_dir)
@classmethod
def INPUT_TYPES(cls):
# 获取可用字体列表 - 同样修改为上级目录下的fonts文件夹
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
font_dir = os.path.join(parent_dir, "fonts")
font_files = []
if os.path.exists(font_dir):
font_files = [f for f in os.listdir(font_dir) if f.endswith(('.ttf', '.otf', '.ttc'))]
return {
"required": {
"图像": ("IMAGE",),
"水印文本": ("STRING", {"default": "水印"}),
"字体": (font_files,),
"水印大小百分比": ("INT", {"default": 5, "min": 0, "max": 100, "step": 1}),
"水印不透明度": ("INT", {"default": 50, "min": 0, "max": 100, "step": 1}),
"水平位置": (["居中", "靠左", "靠右"],),
"垂直位置": (["居中", "靠上", "靠下"],),
"X偏移百分比": ("INT", {"default": 0, "min": 0, "max": 50, "step": 1}),
"Y偏移百分比": ("INT", {"default": 0, "min": 0, "max": 50, "step": 1}),
"文字颜色": ("COLORCODE", {"default": "#FFFFFF"}),
"水印平铺": ("BOOLEAN", {"default": False}),
"水印角度": ("INT", {"default": 0, "min": -90, "max": 90, "step": 1}),
"水印间距": ("INT", {"default": 10, "min": 0, "max": 50, "step": 1}),
"输出透明通道": ("BOOLEAN", {"default": False}),
},
"optional": {
"水印图像": ("IMAGE",),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "添加水印"
CATEGORY = "孤海工具箱"
def 添加水印(self, 图像, 水印文本, 字体, 水印大小百分比, 水印不透明度,
水平位置, 垂直位置, X偏移百分比, Y偏移百分比,
文字颜色, 水印平铺, 水印角度, 水印间距, 输出透明通道,
水印图像=None):
# 将PyTorch张量转换为PIL图像
img = self.张量转PIL(图像)
# 确保图像有Alpha通道用于处理透明度
if img.mode in ('RGB', 'L'):
img = img.convert('RGBA')
# 处理水印
if 水印图像 is not None:
# 使用图像水印
watermark = self.张量转PIL(水印图像)
result = self.应用图像水印(img, watermark, 水印大小百分比,
水印不透明度, 水平位置,
垂直位置, X偏移百分比,
Y偏移百分比, 水印角度)
else:
# 使用文字水印
result = self.应用文字水印(img, 水印文本, 字体, 水印大小百分比,
水印不透明度, 水平位置,
垂直位置, X偏移百分比,
Y偏移百分比, 文字颜色, 水印平铺,
水印角度, 水印间距)
# 处理输出通道
if not 输出透明通道 and result.mode == 'RGBA':
result = result.convert('RGB')
# 将PIL图像转换回PyTorch张量
return (self.PIL转张量(result),)
def 应用图像水印(self, 原图, 水印图, 大小百分比, 不透明度,
水平位置, 垂直位置, X偏移, Y偏移, 角度):
# 调整水印大小 - 修改为按水印图像自身的百分比
水印宽, 水印高 = 水印图.size
比例 = 大小百分比 / 100.0
新水印尺寸 = (int(水印宽 * 比例), int(水印高 * 比例))
水印 = 水印图.resize(新水印尺寸, Image.Resampling.LANCZOS)
# 确保水印有Alpha通道
if 水印.mode != 'RGBA':
水印 = 水印.convert('RGBA')
# 调整水印透明度
alpha = 水印.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(不透明度 / 100)
水印.putalpha(alpha)
# 旋转水印
if 角度 != 0:
水印 = 水印.rotate(角度, expand=True, resample=Image.Resampling.BICUBIC)
# 计算水印位置
水印宽, 水印高 = 水印.size
原图宽, 原图高 = 原图.size
x, y = self.计算位置(原图宽, 原图高, 水印宽, 水印高,
水平位置, 垂直位置, X偏移, Y偏移)
# 创建一个临时图像来应用水印
临时图层 = Image.new('RGBA', 原图.size, (0, 0, 0, 0))
临时图层.paste(水印, (x, y), 水印)
# 合并水印和原图
return Image.alpha_composite(原图, 临时图层)
def 应用文字水印(self, 原图, 文字, 字体名, 大小百分比, 不透明度,
水平位置, 垂直位置, X偏移, Y偏移, 颜色,
平铺, 角度, 间距):
# 文字水印保持原来的逻辑 - 按底图高度的百分比
原图宽, 原图高 = 原图.size
文字大小 = int(原图高 * (大小百分比 / 100))
# 加载字体(使用修改后的上级目录路径)
字体路径 = os.path.join(self.font_dir, 字体名)
try:
字体 = ImageFont.truetype(字体路径, 文字大小)
except:
# 加载失败时使用默认字体
字体 = ImageFont.load_default()
# 获取文字大小和偏移量
文字宽, 文字高, 偏移_y = self.获取文字大小(文字, 字体)
# 创建足够大的文字图层(增加一些安全边距)
安全边距 = int(文字大小 * 0.1) # 10%的安全边距
文字图层 = Image.new('RGBA',
(文字宽 + 2 * 安全边距,
文字高 + 2 * 安全边距),
(0, 0, 0, 0))
draw = ImageDraw.Draw(文字图层)
# 解析颜色
颜色带透明 = self.十六进制转RGBA(颜色, 不透明度)
# 绘制文字(调整位置以避免截断)
draw.text((安全边距, 安全边距 - 偏移_y), 文字, font=字体, fill=颜色带透明)
# 旋转文字
if 角度 != 0:
文字图层 = 文字图层.rotate(角度, expand=True, resample=Image.Resampling.BICUBIC)
文字宽, 文字高 = 文字图层.size
# 创建临时图像来应用水印
临时图层 = Image.new('RGBA', 原图.size, (0, 0, 0, 0))
if 平铺:
# 平铺水印
间距像素 = int(原图高 * (间距 / 100))
# 计算每行每列可以放置多少水印
列数 = (原图宽 // (文字宽 + 间距像素)) + 2
行数 = (原图高 // (文字高 + 间距像素)) + 2
for i in range(列数):
for j in range(行数):
x = i * (文字宽 + 间距像素) - 文字宽
y = j * (文字高 + 间距像素) - 文字高
临时图层.paste(文字图层, (x, y), 文字图层)
else:
# 单一水印
x, y = self.计算位置(原图宽, 原图高, 文字宽, 文字高,
水平位置, 垂直位置, X偏移, Y偏移)
临时图层.paste(文字图层, (x, y), 文字图层)
# 合并水印和原图
return Image.alpha_composite(原图, 临时图层)
def 计算位置(self, 原图宽, 原图高, 水印宽, 水印高,
水平位置, 垂直位置, X偏移, Y偏移):
# 计算X偏移像素
X偏移像素 = int(原图宽 * (X偏移 / 100))
# 计算水平位置
if 水平位置 == "靠左":
x = X偏移像素
elif 水平位置 == "靠右":
x = 原图宽 - 水印宽 - X偏移像素
else: # 居中
x = (原图宽 - 水印宽) // 2 + X偏移像素
# 计算Y偏移像素
Y偏移像素 = int(原图高 * (Y偏移 / 100))
# 计算垂直位置
if 垂直位置 == "靠上":
y = Y偏移像素
elif 垂直位置 == "靠下":
y = 原图高 - 水印高 - Y偏移像素
else: # 居中
y = (原图高 - 水印高) // 2 + Y偏移像素
return x, y
def 获取文字大小(self, 文字, 字体):
# 改进的文字尺寸计算方法,考虑基线偏移
临时图像 = Image.new('RGBA', (1000, 1000), (0, 0, 0, 0)) # 使用较大的临时图像
draw = ImageDraw.Draw(临时图像)
# 获取文本边界框
bbox = draw.textbbox((0, 0), 文字, font=字体)
left, top, right, bottom = bbox
# 计算文字实际宽高
文字宽 = right - left
文字高 = bottom - top
# 计算基线偏移(文字实际顶部到绘制点的距离)
偏移_y = top
return 文字宽, 文字高, 偏移_y
def 十六进制转RGBA(self, 十六进制颜色, 不透明度):
# 移除#号
十六进制颜色 = 十六进制颜色.lstrip('#')
# 解析RGB值
r = int(十六进制颜色[0:2], 16)
g = int(十六进制颜色[2:4], 16)
b = int(十六进制颜色[4:6], 16)
# 计算透明度
a = int(255 * (不透明度 / 100))
return (r, g, b, a)
def 张量转PIL(self, 张量):
# 将ComfyUI的张量格式转换为PIL图像
if len(张量.shape) == 4:
张量 = 张量[0] # 取第一个图像
img = 张量.cpu().numpy()
img = np.clip(img * 255.0, 0, 255).astype(np.uint8)
img = Image.fromarray(img)
return img
def PIL转张量(self, img):
# 将PIL图像转换为ComfyUI的张量格式
img_np = np.array(img).astype(np.float32) / 255.0
if len(img_np.shape) == 3:
img_np = img_np[None, ...]
return torch.from_numpy(img_np)
# 节点注册映射
NODE_CLASS_MAPPINGS = {
"孤海-图像添加水印": 孤海_图像添加水印
}
NODE_DISPLAY_NAME_MAPPINGS = {
"孤海-图像添加水印": "孤海-图像添加水印"
}
@@ -0,0 +1,631 @@
[
".github/workflows/publish_action.yml",
".gitignore",
"LICENSE",
"README.md",
"README_CN.MD",
"__init__.py",
"api_key.ini.example",
"custom_size.ini.example",
"face_landmarker/face_landmarker.task",
"florence2_models/__init__.py",
"florence2_models/configuration_florence2.py",
"florence2_models/modeling_florence2.py",
"florence2_models/processing_florence2.py",
"florence2_ultra.py",
"font/Alibaba-PuHuiTi-Heavy.ttf",
"image/add_blind_watermark_node.jpg",
"image/bbox_join_node.jpg",
"image/birefnet_ultra_example.jpg",
"image/birefnet_ultra_node.jpg",
"image/birefnet_ultra_v2_example.jpg",
"image/birefnet_ultra_v2_node.jpg",
"image/blend_mode_result.jpg",
"image/blend_mode_v2_example.jpg",
"image/collage_example.jpg",
"image/collage_node.jpg",
"image/create_qrcode_node.jpg",
"image/data_nodes_example.jpg",
"image/decode_qrcode_node.jpg",
"image/deepseek_api_example.jpg",
"image/deepseek_api_node.jpg",
"image/deepseek_api_v2_node.jpg",
"image/draw_bbox_mask_example.jpg",
"image/draw_bbox_mask_node.jpg",
"image/draw_bbox_mask_v2_example.jpg",
"image/draw_bbox_mask_v2_node.jpg",
"image/evf_sam_ultra_example.jpg",
"image/evf_sam_ultra_node.jpg",
"image/florence2_image2prompt_example.jpg",
"image/florence2_image2prompt_node.jpg",
"image/florence2_ultra_example.jpg",
"image/florence2_ultra_node.jpg",
"image/gemini_example.jpg",
"image/gemini_image_edit_example.jpg",
"image/gemini_image_edit_node.jpg",
"image/gemini_node.jpg",
"image/gemini_v2_example.jpg",
"image/gemini_v2_node.jpg",
"image/get_color_tone_example.jpg",
"image/get_color_tone_node.jpg",
"image/get_color_tone_v2_example.jpg",
"image/get_color_tone_v2_example2.jpg",
"image/get_color_tone_v2_node.jpg",
"image/human_parts_node.jpg",
"image/human_parts_ultra_example.jpg",
"image/image_auto_crop_example.jpg",
"image/image_auto_crop_node.jpg",
"image/image_auto_crop_v2_node.jpg",
"image/image_auto_crop_v3_node.jpg",
"image/image_reward_filter_example.jpg",
"image/image_reward_filter_node.jpg",
"image/jimeng_image_to_image_api_example.jpg",
"image/jimeng_image_to_image_api_node.jpg",
"image/joycaption2_example.jpg",
"image/joycaption2_extra_options_node.jpg",
"image/joycaption2_node.jpg",
"image/joycaption2_split_node.jpg",
"image/joycaption_beta1_example.jpg",
"image/joycaption_beta1_extra_options_node.jpg",
"image/joycaption_beta_1_node.jpg",
"image/lama_example.jpg",
"image/lama_node.jpg",
"image/light_leak_example.jpg",
"image/light_leak_node.jpg",
"image/llama_vision_example.jpg",
"image/llama_vision_node.jpg",
"image/load_ben_model_node.jpg",
"image/load_birefnet_model_node.jpg",
"image/load_birefnet_model_v2_node.jpg",
"image/load_florence2_model_node.jpg",
"image/load_image_example.jpg",
"image/load_image_example_psd_file.jpg",
"image/load_image_node.jpg",
"image/load_joycaption2_model_node.jpg",
"image/load_joycaption_beta1_model_node.jpg",
"image/load_sam2_model_node.jpg",
"image/load_segmentanything_model_node.jpg",
"image/load_smollm2_node.jpg",
"image/load_smolvlm_model_node.jpg",
"image/mask_by_different_example.jpg",
"image/mask_by_different_node.jpg",
"image/mediapipe_facial_segment_example.jpg",
"image/mediapipe_facial_segment_node.jpg",
"image/node-menu.jpg",
"image/node-search.jpg",
"image/object_detector_fl2_node.jpg",
"image/object_detector_gemini_example.jpg",
"image/object_detector_gemini_node.jpg",
"image/object_detector_gemini_v2_node.jpg",
"image/object_detector_mask_node.jpg",
"image/object_detector_yolo8_node.jpg",
"image/object_detector_yolo_world_node.jpg",
"image/outer_glow_example.jpg",
"image/person_mask_ultra_example.jpg",
"image/person_mask_ultra_node.jpg",
"image/person_mask_ultra_v2_node.jpg",
"image/phi_prompt_example.jpg",
"image/phi_prompt_node.jpg",
"image/prompt_embellish_example.jpg",
"image/prompt_embellish_node.jpg",
"image/prompt_tagger_example.jpg",
"image/prompt_tagger_example1.jpg",
"image/prompt_tagger_node.jpg",
"image/qwen_image2prompt_example.jpg",
"image/sam2_example.jpg",
"image/sam2_ultra_node.jpg",
"image/sam2_ultra_v2_node.jpg",
"image/sam2_video_ultra_node.jpg",
"image/saveimage_plus_example.jpg",
"image/saveimage_plus_node.jpg",
"image/saveimage_plus_v2_node.jpg",
"image/sd3_negative_conditioning_example.jpg",
"image/sd3_negative_conditioning_node.jpg",
"image/sd3_negative_conditioning_node_note.jpg",
"image/segment_anything_ultra_compare.jpg",
"image/segment_anything_ultra_example.jpg",
"image/segment_anything_ultra_node.jpg",
"image/segment_anything_ultra_v2_node.jpg",
"image/segment_anything_ultra_v3_example.jpg",
"image/segment_anything_ultra_v3_node.jpg",
"image/show_blind_watermark_node.jpg",
"image/smollm2_example.jpg",
"image/smollm2_node.jpg",
"image/smolvlm_example.jpg",
"image/smolvlm_node.jpg",
"image/transparent_background_ultra_example.jpg",
"image/transparent_background_ultra_node.jpg",
"image/ultra_v2_nodes_example.jpg",
"image/userprompt_generator_replace_word_node.jpg",
"image/userprompt_generator_txt2img_node.jpg",
"image/userprompt_generator_txt2img_with_reference_node.jpg",
"image/water_color_example.jpg",
"image/water_color_node.jpg",
"image/watermark_example.jpg",
"image/yolov8_detect_example.jpg",
"image/yolov8_detect_node.jpg",
"image/zhipuglm4_example.jpg",
"image/zhipuglm4_node.jpg",
"image/zhipuglm4v_node.jpg",
"install_requirements.bat",
"install_requirements_aki.bat",
"js/dz_node_palette.js",
"locales/en/nodeDefs.json",
"locales/fr/nodeDefs.json",
"locales/ja/nodeDefs.json",
"locales/ko/nodeDefs.json",
"locales/ru/nodeDefs.json",
"locales/zh/nodeDefs.json",
"py/BiRefNet_legacy/__init__.py",
"py/BiRefNet_legacy/backbones/__init__.py",
"py/BiRefNet_legacy/backbones/build_backbone.py",
"py/BiRefNet_legacy/backbones/pvt_v2.py",
"py/BiRefNet_legacy/backbones/swin_v1.py",
"py/BiRefNet_legacy/baseline.py",
"py/BiRefNet_legacy/config.py",
"py/BiRefNet_legacy/dataset.py",
"py/BiRefNet_legacy/modules/__init__.py",
"py/BiRefNet_legacy/modules/aspp.py",
"py/BiRefNet_legacy/modules/attentions.py",
"py/BiRefNet_legacy/modules/decoder_blocks.py",
"py/BiRefNet_legacy/modules/deform_conv.py",
"py/BiRefNet_legacy/modules/ing.py",
"py/BiRefNet_legacy/modules/lateral_blocks.py",
"py/BiRefNet_legacy/modules/mlp.py",
"py/BiRefNet_legacy/modules/utils.py",
"py/BiRefNet_legacy/preproc.py",
"py/BiRefNet_legacy/refinement/__init__.py",
"py/BiRefNet_legacy/refinement/refiner.py",
"py/BiRefNet_legacy/refinement/stem_layer.py",
"py/BiRefNet_v2/LICENSE",
"py/BiRefNet_v2/README.md",
"py/BiRefNet_v2/__init__.py",
"py/BiRefNet_v2/config.py",
"py/BiRefNet_v2/dataset.py",
"py/BiRefNet_v2/eval_existingOnes.py",
"py/BiRefNet_v2/evaluation/metrics.py",
"py/BiRefNet_v2/gen_best_ep.py",
"py/BiRefNet_v2/image_proc.py",
"py/BiRefNet_v2/inference.py",
"py/BiRefNet_v2/loss.py",
"py/BiRefNet_v2/make_a_copy.sh",
"py/BiRefNet_v2/models/backbones/build_backbone.py",
"py/BiRefNet_v2/models/backbones/pvt_v2.py",
"py/BiRefNet_v2/models/backbones/swin_v1.py",
"py/BiRefNet_v2/models/birefnet.py",
"py/BiRefNet_v2/models/modules/aspp.py",
"py/BiRefNet_v2/models/modules/decoder_blocks.py",
"py/BiRefNet_v2/models/modules/deform_conv.py",
"py/BiRefNet_v2/models/modules/lateral_blocks.py",
"py/BiRefNet_v2/models/modules/mlp.py",
"py/BiRefNet_v2/models/modules/prompt_encoder.py",
"py/BiRefNet_v2/models/modules/utils.py",
"py/BiRefNet_v2/models/refinement/refiner.py",
"py/BiRefNet_v2/models/refinement/stem_layer.py",
"py/BiRefNet_v2/requirements.txt",
"py/BiRefNet_v2/rm_cache.sh",
"py/BiRefNet_v2/sub.sh",
"py/BiRefNet_v2/test.sh",
"py/BiRefNet_v2/train.py",
"py/BiRefNet_v2/train.sh",
"py/BiRefNet_v2/train_test.sh",
"py/BiRefNet_v2/tutorials/BiRefNet_inference.ipynb",
"py/BiRefNet_v2/tutorials/BiRefNet_pth2onnx.ipynb",
"py/BiRefNet_v2/utils.py",
"py/Jimeng_API.py",
"py/Qwen_image2prompt.py",
"py/ben_ultra.py",
"py/birefnet_legacy.py",
"py/birefnet_ultra.py",
"py/birefnet_ultra_v2.py",
"py/blendmodes.py",
"py/briarmbg.py",
"py/collage.py",
"py/deepseek.py",
"py/evf_sam/__init__.py",
"py/evf_sam/evf_sam_inference.py",
"py/evf_sam/model/EfficientSAM/efficient_sam/__init__.py",
"py/evf_sam/model/EfficientSAM/efficient_sam/build_efficient_sam.py",
"py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam.py",
"py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_decoder.py",
"py/evf_sam/model/EfficientSAM/efficient_sam/efficient_sam_encoder.py",
"py/evf_sam/model/EfficientSAM/efficient_sam/mlp.py",
"py/evf_sam/model/EfficientSAM/efficient_sam/two_way_transformer.py",
"py/evf_sam/model/__init__.py",
"py/evf_sam/model/configuration_evf.py",
"py/evf_sam/model/evf_effisam.py",
"py/evf_sam/model/evf_sam.py",
"py/evf_sam/model/evf_sam2.py",
"py/evf_sam/model/evf_sam2_video.py",
"py/evf_sam/model/segment_anything/__init__.py",
"py/evf_sam/model/segment_anything/automatic_mask_generator.py",
"py/evf_sam/model/segment_anything/build_sam.py",
"py/evf_sam/model/segment_anything/modeling/__init__.py",
"py/evf_sam/model/segment_anything/modeling/common.py",
"py/evf_sam/model/segment_anything/modeling/image_encoder.py",
"py/evf_sam/model/segment_anything/modeling/mask_decoder.py",
"py/evf_sam/model/segment_anything/modeling/prompt_encoder.py",
"py/evf_sam/model/segment_anything/modeling/sam.py",
"py/evf_sam/model/segment_anything/modeling/transformer.py",
"py/evf_sam/model/segment_anything/predictor.py",
"py/evf_sam/model/segment_anything/utils/__init__.py",
"py/evf_sam/model/segment_anything/utils/amg.py",
"py/evf_sam/model/segment_anything/utils/onnx.py",
"py/evf_sam/model/segment_anything/utils/transforms.py",
"py/evf_sam/model/segment_anything_2/sam2/__init__.py",
"py/evf_sam/model/segment_anything_2/sam2/automatic_mask_generator.py",
"py/evf_sam/model/segment_anything_2/sam2/build_sam.py",
"py/evf_sam/model/segment_anything_2/sam2/csrc/connected_components.cu",
"py/evf_sam/model/segment_anything_2/sam2/modeling/__init__.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/__init__.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/hieradet.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/image_encoder.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/backbones/utils.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/memory_attention.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/memory_encoder.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/position_encoding.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/sam/__init__.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/sam/mask_decoder.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/sam/prompt_encoder.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/sam/transformer.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_base.py",
"py/evf_sam/model/segment_anything_2/sam2/modeling/sam2_utils.py",
"py/evf_sam/model/segment_anything_2/sam2/sam2_image_predictor.py",
"py/evf_sam/model/segment_anything_2/sam2/sam2_video_predictor.py",
"py/evf_sam/model/segment_anything_2/sam2/utils/__init__.py",
"py/evf_sam/model/segment_anything_2/sam2/utils/amg.py",
"py/evf_sam/model/segment_anything_2/sam2/utils/misc.py",
"py/evf_sam/model/segment_anything_2/sam2/utils/transforms.py",
"py/evf_sam/model/segment_anything_2/sam2_configs/__init__.py",
"py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_b+.yaml",
"py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_l.yaml",
"py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_s.yaml",
"py/evf_sam/model/segment_anything_2/sam2_configs/sam2_hiera_t.yaml",
"py/evf_sam/model/segment_anything_2/setup.py",
"py/evf_sam/model/unilm/beit3/README.md",
"py/evf_sam/model/unilm/beit3/datasets.py",
"py/evf_sam/model/unilm/beit3/engine_for_finetuning.py",
"py/evf_sam/model/unilm/beit3/get_started/get_started_for_captioning.md",
"py/evf_sam/model/unilm/beit3/get_started/get_started_for_image_classification.md",
"py/evf_sam/model/unilm/beit3/get_started/get_started_for_nlvr2.md",
"py/evf_sam/model/unilm/beit3/get_started/get_started_for_retrieval.md",
"py/evf_sam/model/unilm/beit3/get_started/get_started_for_vqav2.md",
"py/evf_sam/model/unilm/beit3/glossary.py",
"py/evf_sam/model/unilm/beit3/modeling_finetune.py",
"py/evf_sam/model/unilm/beit3/modeling_utils.py",
"py/evf_sam/model/unilm/beit3/optim_factory.py",
"py/evf_sam/model/unilm/beit3/randaug.py",
"py/evf_sam/model/unilm/beit3/requirements.txt",
"py/evf_sam/model/unilm/beit3/run_beit3_finetuning.py",
"py/evf_sam/model/unilm/beit3/utils.py",
"py/evf_sam/utils/ade20k_classes.json",
"py/evf_sam/utils/aug.py",
"py/evf_sam/utils/data_processing.py",
"py/evf_sam/utils/dataset.py",
"py/evf_sam/utils/grefcoco.py",
"py/evf_sam/utils/grefer.py",
"py/evf_sam/utils/refer.py",
"py/evf_sam/utils/refer_seg_dataset.py",
"py/evf_sam/utils/sem_seg_dataset.py",
"py/evf_sam/utils/utils.py",
"py/evf_sam_ultra.py",
"py/florence2_ultra.py",
"py/gemini.py",
"py/get_color_tone.py",
"py/get_color_tone_v2.py",
"py/human_parts_ultra.py",
"py/image_auto_crop.py",
"py/image_auto_crop_v2.py",
"py/image_auto_crop_v3.py",
"py/image_reward_filter.py",
"py/imagefunc.py",
"py/iopaint/__init__.py",
"py/iopaint/__main__.py",
"py/iopaint/api.py",
"py/iopaint/batch_processing.py",
"py/iopaint/benchmark.py",
"py/iopaint/cli.py",
"py/iopaint/const.py",
"py/iopaint/download.py",
"py/iopaint/file_manager/__init__.py",
"py/iopaint/file_manager/file_manager.py",
"py/iopaint/file_manager/storage_backends.py",
"py/iopaint/file_manager/utils.py",
"py/iopaint/helper.py",
"py/iopaint/imghdr.py",
"py/iopaint/installer.py",
"py/iopaint/model/__init__.py",
"py/iopaint/model/anytext/__init__.py",
"py/iopaint/model/anytext/anytext_model.py",
"py/iopaint/model/anytext/anytext_pipeline.py",
"py/iopaint/model/anytext/anytext_sd15.yaml",
"py/iopaint/model/anytext/cldm/__init__.py",
"py/iopaint/model/anytext/cldm/cldm.py",
"py/iopaint/model/anytext/cldm/ddim_hacked.py",
"py/iopaint/model/anytext/cldm/embedding_manager.py",
"py/iopaint/model/anytext/cldm/hack.py",
"py/iopaint/model/anytext/cldm/model.py",
"py/iopaint/model/anytext/cldm/recognizer.py",
"py/iopaint/model/anytext/ldm/__init__.py",
"py/iopaint/model/anytext/ldm/models/__init__.py",
"py/iopaint/model/anytext/ldm/models/autoencoder.py",
"py/iopaint/model/anytext/ldm/models/diffusion/__init__.py",
"py/iopaint/model/anytext/ldm/models/diffusion/ddim.py",
"py/iopaint/model/anytext/ldm/models/diffusion/ddpm.py",
"py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/__init__.py",
"py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py",
"py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/sampler.py",
"py/iopaint/model/anytext/ldm/models/diffusion/plms.py",
"py/iopaint/model/anytext/ldm/models/diffusion/sampling_util.py",
"py/iopaint/model/anytext/ldm/modules/__init__.py",
"py/iopaint/model/anytext/ldm/modules/attention.py",
"py/iopaint/model/anytext/ldm/modules/diffusionmodules/__init__.py",
"py/iopaint/model/anytext/ldm/modules/diffusionmodules/model.py",
"py/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py",
"py/iopaint/model/anytext/ldm/modules/diffusionmodules/upscaling.py",
"py/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py",
"py/iopaint/model/anytext/ldm/modules/distributions/__init__.py",
"py/iopaint/model/anytext/ldm/modules/distributions/distributions.py",
"py/iopaint/model/anytext/ldm/modules/ema.py",
"py/iopaint/model/anytext/ldm/modules/encoders/__init__.py",
"py/iopaint/model/anytext/ldm/modules/encoders/modules.py",
"py/iopaint/model/anytext/ldm/util.py",
"py/iopaint/model/anytext/main.py",
"py/iopaint/model/anytext/ocr_recog/RNN.py",
"py/iopaint/model/anytext/ocr_recog/RecCTCHead.py",
"py/iopaint/model/anytext/ocr_recog/RecModel.py",
"py/iopaint/model/anytext/ocr_recog/RecMv1_enhance.py",
"py/iopaint/model/anytext/ocr_recog/RecSVTR.py",
"py/iopaint/model/anytext/ocr_recog/__init__.py",
"py/iopaint/model/anytext/ocr_recog/common.py",
"py/iopaint/model/anytext/ocr_recog/ppocr_keys_v1.txt",
"py/iopaint/model/anytext/utils.py",
"py/iopaint/model/base.py",
"py/iopaint/model/controlnet.py",
"py/iopaint/model/ddim_sampler.py",
"py/iopaint/model/fcf.py",
"py/iopaint/model/helper/__init__.py",
"py/iopaint/model/helper/controlnet_preprocess.py",
"py/iopaint/model/helper/cpu_text_encoder.py",
"py/iopaint/model/helper/g_diffuser_bot.py",
"py/iopaint/model/instruct_pix2pix.py",
"py/iopaint/model/kandinsky.py",
"py/iopaint/model/lama.py",
"py/iopaint/model/ldm.py",
"py/iopaint/model/manga.py",
"py/iopaint/model/mat.py",
"py/iopaint/model/mi_gan.py",
"py/iopaint/model/opencv2.py",
"py/iopaint/model/original_sd_configs/__init__.py",
"py/iopaint/model/original_sd_configs/sd_xl_base.yaml",
"py/iopaint/model/original_sd_configs/sd_xl_refiner.yaml",
"py/iopaint/model/original_sd_configs/v1-inference.yaml",
"py/iopaint/model/original_sd_configs/v2-inference-v.yaml",
"py/iopaint/model/paint_by_example.py",
"py/iopaint/model/plms_sampler.py",
"py/iopaint/model/power_paint/__init__.py",
"py/iopaint/model/power_paint/pipeline_powerpaint.py",
"py/iopaint/model/power_paint/pipeline_powerpaint_controlnet.py",
"py/iopaint/model/power_paint/power_paint.py",
"py/iopaint/model/power_paint/powerpaint_tokenizer.py",
"py/iopaint/model/sd.py",
"py/iopaint/model/sdxl.py",
"py/iopaint/model/utils.py",
"py/iopaint/model/zits.py",
"py/iopaint/model_info.py",
"py/iopaint/model_manager.py",
"py/iopaint/plugins/__init__.py",
"py/iopaint/plugins/anime_seg.py",
"py/iopaint/plugins/base_plugin.py",
"py/iopaint/plugins/briarmbg.py",
"py/iopaint/plugins/gfpgan_plugin.py",
"py/iopaint/plugins/gfpganer.py",
"py/iopaint/plugins/interactive_seg.py",
"py/iopaint/plugins/realesrgan.py",
"py/iopaint/plugins/remove_bg.py",
"py/iopaint/plugins/restoreformer.py",
"py/iopaint/plugins/segment_anything/__init__.py",
"py/iopaint/plugins/segment_anything/build_sam.py",
"py/iopaint/plugins/segment_anything/modeling/__init__.py",
"py/iopaint/plugins/segment_anything/modeling/common.py",
"py/iopaint/plugins/segment_anything/modeling/image_encoder.py",
"py/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py",
"py/iopaint/plugins/segment_anything/modeling/mask_decoder.py",
"py/iopaint/plugins/segment_anything/modeling/prompt_encoder.py",
"py/iopaint/plugins/segment_anything/modeling/sam.py",
"py/iopaint/plugins/segment_anything/modeling/sam_hq.py",
"py/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py",
"py/iopaint/plugins/segment_anything/modeling/transformer.py",
"py/iopaint/plugins/segment_anything/predictor.py",
"py/iopaint/plugins/segment_anything/predictor_hq.py",
"py/iopaint/plugins/segment_anything/utils/__init__.py",
"py/iopaint/plugins/segment_anything/utils/transforms.py",
"py/iopaint/runtime.py",
"py/iopaint/schema.py",
"py/iopaint/tests/__init__.py",
"py/iopaint/tests/test_adjust_mask.py",
"py/iopaint/tests/test_anytext.py",
"py/iopaint/tests/test_controlnet.py",
"py/iopaint/tests/test_instruct_pix2pix.py",
"py/iopaint/tests/test_load_img.py",
"py/iopaint/tests/test_low_mem.py",
"py/iopaint/tests/test_match_histograms.py",
"py/iopaint/tests/test_model.py",
"py/iopaint/tests/test_model_md5.py",
"py/iopaint/tests/test_model_switch.py",
"py/iopaint/tests/test_outpainting.py",
"py/iopaint/tests/test_paint_by_example.py",
"py/iopaint/tests/test_plugins.py",
"py/iopaint/tests/test_save_exif.py",
"py/iopaint/tests/test_sd_model.py",
"py/iopaint/tests/test_sdxl.py",
"py/iopaint/tests/utils.py",
"py/iopaint/web_app/assets/Inter-Black-jiII8dog.woff2",
"py/iopaint/web_app/assets/Inter-BlackItalic-1413vuen.woff2",
"py/iopaint/web_app/assets/Inter-Bold-srYz_-1B.woff2",
"py/iopaint/web_app/assets/Inter-BoldItalic-dE_gZyur.woff2",
"py/iopaint/web_app/assets/Inter-ExtraBold-TduDdwUu.woff2",
"py/iopaint/web_app/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2",
"py/iopaint/web_app/assets/Inter-ExtraLight-w5HAp5iF.woff2",
"py/iopaint/web_app/assets/Inter-ExtraLightItalic-ZptecSuc.woff2",
"py/iopaint/web_app/assets/Inter-Italic-f6M78thn.woff2",
"py/iopaint/web_app/assets/Inter-Light-DFhX0qo-.woff2",
"py/iopaint/web_app/assets/Inter-LightItalic-fu56_DRc.woff2",
"py/iopaint/web_app/assets/Inter-Medium-dDRaJ8tM.woff2",
"py/iopaint/web_app/assets/Inter-MediumItalic-zr3roggP.woff2",
"py/iopaint/web_app/assets/Inter-Regular-dEFHw1tF.woff2",
"py/iopaint/web_app/assets/Inter-SemiBold-PyS8DO2L.woff2",
"py/iopaint/web_app/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2",
"py/iopaint/web_app/assets/Inter-Thin-eKObIkJC.woff2",
"py/iopaint/web_app/assets/Inter-ThinItalic-L6uBn3RP.woff2",
"py/iopaint/web_app/assets/index-8BlaS7ws.js",
"py/iopaint/web_app/assets/index-CXO-mkQB.js",
"py/iopaint/web_app/assets/index-NQyCh9rO.js",
"py/iopaint/web_app/assets/index-QuEBEP4v.js",
"py/iopaint/web_app/assets/index-TI-UMrGI.js",
"py/iopaint/web_app/assets/index-Tqq3L7kY.js",
"py/iopaint/web_app/assets/index-UXaKiZjP.css",
"py/iopaint/web_app/assets/index-_6nUWG_P.js",
"py/iopaint/web_app/assets/index-c6LmMFap.js",
"py/iopaint/web_app/assets/index-hrusMZZs.js",
"py/iopaint/web_app/assets/index-iK_rIxV0.css",
"py/iopaint/web_app/assets/index-kS3ik1bw.js",
"py/iopaint/web_app/assets/index-p0ivNJpo.css",
"py/iopaint/web_app/assets/index-qFliSBYV.js",
"py/iopaint/web_app/assets/kofi_button_black-XI_Dr2zg.png",
"py/iopaint/web_app/index.html",
"py/iopaint/web_config.py",
"py/joycaption_alpha_2.py",
"py/joycaption_beta_1.py",
"py/lama.py",
"py/llama_vision.py",
"py/loadpsd.py",
"py/local_groundingdino/datasets/__init__.py",
"py/local_groundingdino/datasets/transforms.py",
"py/local_groundingdino/models/GroundingDINO/__init__.py",
"py/local_groundingdino/models/GroundingDINO/backbone/__init__.py",
"py/local_groundingdino/models/GroundingDINO/backbone/backbone.py",
"py/local_groundingdino/models/GroundingDINO/backbone/position_encoding.py",
"py/local_groundingdino/models/GroundingDINO/backbone/swin_transformer.py",
"py/local_groundingdino/models/GroundingDINO/bertwarper.py",
"py/local_groundingdino/models/GroundingDINO/fuse_modules.py",
"py/local_groundingdino/models/GroundingDINO/groundingdino.py",
"py/local_groundingdino/models/GroundingDINO/ms_deform_attn.py",
"py/local_groundingdino/models/GroundingDINO/transformer.py",
"py/local_groundingdino/models/GroundingDINO/transformer_vanilla.py",
"py/local_groundingdino/models/GroundingDINO/utils.py",
"py/local_groundingdino/models/__init__.py",
"py/local_groundingdino/models/registry.py",
"py/local_groundingdino/util/__init__.py",
"py/local_groundingdino/util/box_ops.py",
"py/local_groundingdino/util/get_tokenlizer.py",
"py/local_groundingdino/util/inference.py",
"py/local_groundingdino/util/misc.py",
"py/local_groundingdino/util/slconfig.py",
"py/local_groundingdino/util/slio.py",
"py/local_groundingdino/util/utils.py",
"py/mask_by_different.py",
"py/mediapipe_facial_segment.py",
"py/object_detector.py",
"py/person_mask_Ultra.py",
"py/person_mask_ultra_v2.py",
"py/phi_nodes.py",
"py/prompt_embellish.py",
"py/prompt_tagger.py",
"py/qrcode.py",
"py/sam2/__init__.py",
"py/sam2/automatic_mask_generator.py",
"py/sam2/modeling/__init__.py",
"py/sam2/modeling/backbones/__init__.py",
"py/sam2/modeling/backbones/hieradet.py",
"py/sam2/modeling/backbones/image_encoder.py",
"py/sam2/modeling/backbones/utils.py",
"py/sam2/modeling/memory_attention.py",
"py/sam2/modeling/memory_encoder.py",
"py/sam2/modeling/position_encoding.py",
"py/sam2/modeling/sam/__init__.py",
"py/sam2/modeling/sam/mask_decoder.py",
"py/sam2/modeling/sam/prompt_encoder.py",
"py/sam2/modeling/sam/transformer.py",
"py/sam2/modeling/sam2_base.py",
"py/sam2/modeling/sam2_utils.py",
"py/sam2/sam2_configs/__init__.py",
"py/sam2/sam2_configs/sam2.1_hiera_b+.yaml",
"py/sam2/sam2_configs/sam2.1_hiera_l.yaml",
"py/sam2/sam2_configs/sam2.1_hiera_s.yaml",
"py/sam2/sam2_configs/sam2.1_hiera_t.yaml",
"py/sam2/sam2_configs/sam2_hiera_b+.yaml",
"py/sam2/sam2_configs/sam2_hiera_l.yaml",
"py/sam2/sam2_configs/sam2_hiera_s.yaml",
"py/sam2/sam2_configs/sam2_hiera_t.yaml",
"py/sam2/sam2_image_predictor.py",
"py/sam2/sam2_video_predictor.py",
"py/sam2/utils/__init__.py",
"py/sam2/utils/amg.py",
"py/sam2/utils/misc.py",
"py/sam2/utils/transforms.py",
"py/sam_2_ultra.py",
"py/sam_hq/automatic.py",
"py/sam_hq/build_sam_hq.py",
"py/sam_hq/modeling/image_encoder.py",
"py/sam_hq/modeling/mask_decoder_hq.py",
"py/sam_hq/modeling/tiny_vit.py",
"py/sam_hq/predictor.py",
"py/save_image_plus.py",
"py/sd3_negative_conditioning.py",
"py/segment_anything_func.py",
"py/segment_anything_ultra.py",
"py/segment_anything_ultra_v2.py",
"py/segment_anything_ultra_v3.py",
"py/smol.py",
"py/transparent_background_ultra.py",
"py/user_prompt_generator.py",
"py/watermark.py",
"py/yolov8_detect.py",
"py/zhipu_glm4.py",
"pyproject.toml",
"repair_dependency.bat",
"repair_dependency_aki.bat",
"repair_dependency_list.txt",
"requirements.txt",
"resource_dir.ini.example",
"whl/docopt-0.6.2-py2.py3-none-any.whl",
"whl/hydra_core-1.3.2-py3-none-any.whl",
"workflow/1280x720_seven_person.jpg",
"workflow/1280x720car.jpg",
"workflow/1280x768_city.png",
"workflow/1344x768_beach.png",
"workflow/1344x768_girl2.png",
"workflow/1344x768_hair.png",
"workflow/1344x768_redcar.png",
"workflow/1920x1080table.png",
"workflow/3840x2160car.jpg",
"workflow/512x512.png",
"workflow/512x512bkgd.jpg",
"workflow/768x1344_beach.png",
"workflow/768x1344_dress.png",
"workflow/collage_example.json",
"workflow/deepseek_api_example.json",
"workflow/draw_bbox_mask_example.json",
"workflow/draw_bbox_mask_v2_example.json",
"workflow/florence2_image2prompt_example.json",
"workflow/florence2_ultra_example.json",
"workflow/fox_512x512.png",
"workflow/gemini_example.json",
"workflow/gemini_image_edit_example.json",
"workflow/get_color_tone_v2_example.json",
"workflow/get_main_color_and_color_name_example.json",
"workflow/girl_dino_1024.png",
"workflow/image_reward_filter_example.json",
"workflow/joycaption2_example.json",
"workflow/lama_example.json",
"workflow/phi_prompt_example.json",
"workflow/prompt_embellish_example.json",
"workflow/prompt_tagger_example.json",
"workflow/sam2_ultra_example.json",
"workflow/sam2_video_ultra_example.json",
"workflow/sd3_negative_conditioning.json",
"workflow/ultra_v2_nodes_example.json",
"workflow/watermark_example.json",
"workflow/zhipu_glm4_example.json"
]
@@ -0,0 +1 @@
{"changelog":"","createdAt":"2026-04-08T04:28:28.060712Z","dependencies":["numpy","matplotlib","scikit_image","scikit_learn","opencv-contrib-python","pymatting","timm","blend_modes","transformers","diffusers","loguru","colour-science","huggingface_hub","segment_anything","addict","omegaconf","yapf","wget","iopath","mediapipe","typer_config","fastapi","rich","google-generativeai","ultralytics","transparent-background","accelerate","onnxruntime","bitsandbytes","peft","protobuf","hydra-core","blind-watermark","qrcode","pyzbar","psd-tools","wandb","zhipuai","openai","google-genai","fastapi","typer-config"],"deprecated":false,"downloadUrl":"https://cdn.comfy.org/chflame163/ComfyUI_LayerStyle_Advance/2.0.38/node.zip","id":"db305def-250b-448d-88b6-e43acbeb03af","node_id":"ComfyUI_LayerStyle_Advance","status":"NodeVersionStatusActive","supported_accelerators":[],"supported_comfyui_frontend_version":"","supported_comfyui_version":"","supported_os":[],"tags":[],"version":"2.0.38"}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 chflame163
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,48 @@
import importlib.util
import os
import sys
import json
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
python = sys.executable
def get_ext_dir(subpath=None, mkdir=False):
dir = os.path.dirname(__file__)
if subpath is not None:
dir = os.path.join(dir, subpath)
dir = os.path.abspath(dir)
if mkdir and not os.path.exists(dir):
os.makedirs(dir)
return dir
def serialize(obj):
if isinstance(obj, (str, int, float, bool, list, dict, type(None))):
return obj
return str(obj) # 转为字符串
py = get_ext_dir("py")
files = os.listdir(py)
all_nodes = {}
for file in files:
if not file.endswith(".py"):
continue
name = os.path.splitext(file)[0]
imported_module = importlib.import_module(".py.{}".format(name), __name__)
try:
NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS, **imported_module.NODE_CLASS_MAPPINGS}
NODE_DISPLAY_NAME_MAPPINGS = {**NODE_DISPLAY_NAME_MAPPINGS, **imported_module.NODE_DISPLAY_NAME_MAPPINGS}
serialized_CLASS_MAPPINGS = {k: serialize(v) for k, v in imported_module.NODE_CLASS_MAPPINGS.items()}
serialized_DISPLAY_NAME_MAPPINGS = {k: serialize(v) for k, v in imported_module.NODE_DISPLAY_NAME_MAPPINGS.items()}
all_nodes[file]={"NODE_CLASS_MAPPINGS": serialized_CLASS_MAPPINGS, "NODE_DISPLAY_NAME_MAPPINGS": serialized_DISPLAY_NAME_MAPPINGS}
except:
pass
WEB_DIRECTORY = "./js"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,112 @@
# layerstyle advance
from .imagefunc import *
class EncodeBlindWaterMark:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(self):
return {
"required": {
"image": ("IMAGE", ), #
"watermark_image": ("IMAGE",), #
},
"optional": {
}
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = 'watermark_encode'
CATEGORY = '😺dzNodes/LayerUtility/SystemIO'
def watermark_encode(self, image, watermark_image):
NODE_NAME = 'Add BlindWaterMark'
l_images = []
w_images = []
ret_images = []
for l in image:
l_images.append(torch.unsqueeze(l, 0))
for w in watermark_image:
w_images.append(torch.unsqueeze(w, 0))
for i in range(len(l_images)):
_image = tensor2pil(l_images[i])
wm_size = watermark_image_size(_image)
_wm_image = w_images[i] if i < len(w_images) else w_images[-1]
_wm_image = tensor2pil(_wm_image)
_wm_image = _wm_image.resize((wm_size, wm_size), Image.LANCZOS)
_wm_image = _wm_image.convert("L")
y, u, v, _ = image_channel_split(_image, mode='YCbCr')
_u = add_invisibal_watermark(u, _wm_image)
ret_image = image_channel_merge((y, _u, v), mode='YCbCr')
if _image.mode == "RGBA":
ret_image = RGB2RGBA(ret_image, _image.split()[-1])
ret_images.append(pil2tensor(ret_image))
log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish')
return (torch.cat(ret_images, dim=0),)
class DecodeBlindWaterMark:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(self):
return {
"required": {
"image": ("IMAGE",), #
},
"optional": {
}
}
RETURN_TYPES = ("IMAGE", )
RETURN_NAMES = ("watermark_image",)
FUNCTION = 'watermark_decode'
CATEGORY = '😺dzNodes/LayerUtility/SystemIO'
def watermark_decode(self, image):
NODE_NAME = 'Decode BlindWaterMark'
ret_images = []
for i in image:
_image = torch.unsqueeze(i,0)
_image = tensor2pil(_image)
wm_size = watermark_image_size(_image)
y, u, v, _ = image_channel_split(_image, mode='YCbCr')
ret_image = decode_watermark(u, wm_size)
ret_image = ret_image.resize((512, 512), Image.LANCZOS)
ret_image = normalize_gray(ret_image)
ret_images.append(pil2tensor(ret_image.convert('RGB')))
log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish')
return (torch.cat(ret_images, dim=0), )
NODE_CLASS_MAPPINGS = {
"LayerUtility: AddBlindWaterMark": EncodeBlindWaterMark,
"LayerUtility: ShowBlindWaterMark": DecodeBlindWaterMark
}
NODE_DISPLAY_NAME_MAPPINGS = {
"LayerUtility: AddBlindWaterMark": "LayerUtility: Add BlindWaterMark(Advance)",
"LayerUtility: ShowBlindWaterMark": "LayerUtility: Show BlindWaterMark(Advance)"
}
@@ -0,0 +1,15 @@
[project]
name = "ComfyUI_LayerStyle_Advance"
description = "The nodes detached from ComfyUI Layer Style are mainly those with complex requirements for dependency packages."
version = "2.0.38"
license = { text = "MIT License" }
dependencies = ["numpy", "matplotlib", "scikit_image", "scikit_learn", "opencv-contrib-python", "pymatting", "timm", "blend_modes", "transformers", "diffusers", "loguru", "colour-science", "huggingface_hub", "segment_anything", "addict", "omegaconf", "yapf", "wget", "iopath", "mediapipe", "typer_config", "fastapi", "rich", "google-generativeai", "ultralytics", "transparent-background", "accelerate", "onnxruntime", "bitsandbytes", "peft", "protobuf", "hydra-core", "blind-watermark", "qrcode", "pyzbar", "psd-tools", "wandb", "zhipuai", "openai","google-genai", "fastapi","typer-config"]
[project.urls]
Repository = "https://github.com/chflame163/ComfyUI_LayerStyle_Advance"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "chflame163"
DisplayName = "ComfyUI_LayerStyle_Advance"
Icon = "https://avatars.githubusercontent.com/u/130118553"
@@ -0,0 +1,42 @@
numpy
matplotlib
scikit_image
scikit_learn
opencv-contrib-python
pymatting
timm
blend_modes
transformers>=4.45.0
diffusers
loguru
colour-science
huggingface_hub>=0.23.4
segment_anything
addict
omegaconf
yapf
wget
iopath
mediapipe
typer_config
fastapi
rich
google-generativeai
google-genai>=1.5.0
pillow>=10.1.0
ultralytics>=8.2.0
transparent-background
accelerate>=0.26.0
onnxruntime
bitsandbytes>=0.41.1
peft>=0.12.0
protobuf
hydra-core
blind-watermark
qrcode
pyzbar
psd-tools
zhipuai
openai
typer-config
fastapi
@@ -0,0 +1,22 @@
{
"core": {
"repository": "Comfy-Org/ComfyUI",
"requested_ref": "v0.25.0",
"commit": "135abed8da169e33ab0b86550e05e3ae55d6df8c"
},
"camera": {
"repository": "karas17/ComfyUI-Camera-Watermark",
"requested_ref": "c461dedc6ce65e1defe7308e97e7081cedcaf2a7",
"commit": "c461dedc6ce65e1defe7308e97e7081cedcaf2a7"
},
"cr": {
"repository": "Suzie1/ComfyUI_Comfyroll_CustomNodes",
"requested_ref": "d78b780ae43fcf8c6b7c6505e6ffb4584281ceca",
"commit": "d78b780ae43fcf8c6b7c6505e6ffb4584281ceca"
},
"guhai": {
"repository": "goohai/Goohaitools-comfyui",
"requested_ref": "0b267384faaa9201c821c68dfa3dacd784da171d",
"commit": "0b267384faaa9201c821c68dfa3dacd784da171d"
}
}