sd-text-fix / comfy_nodes.py
Kazzze's picture
Update to current version
2a261b0 verified
Raw History Blame Contribute Delete
13.4 kB
"""ComfyUI node: place it after VAE Decode.
The node erases the gibberish text and draws the new one. Its second output is a mask of
the places it wrote on: feed the image and that mask to an inpainting pass with a low
denoise (0.25 to 0.35) to have the model blend the letters in.
The text to replace is picked in one of three ways, the first that applies:
- the editor (the "Open editor" button), which keeps its selections in the layout widget;
- a point (point_x, point_y);
- the search over the whole image, one line of `text` for each line found.
"""
import json
import cv2
import numpy as np
import torch
from PIL import Image
from .text_fix import Look, blend_mask, erase, list_fonts, locate, parse_color, preview, replace, web
AUTO = "auto"
def _layout_data(layout):
try:
data = json.loads(layout) if layout else {}
except (TypeError, ValueError):
data = {}
return data if isinstance(data, dict) else {}
def read_layout(layout):
"""The editor's selections from the node's hidden widget: [{"recipe": ..., "text": ...}]."""
return web.clean_items(_layout_data(layout).get("items"))
# The parts of the look the editor keeps in the layout widget rather than in widgets of their own.
LAYOUT_LOOK = ("color2", "split", "outline", "outline_color", "shadow", "shadow_color", "shadow_x", "shadow_y",
"shadow_blur", "effect", "effect_strength", "relief")
def add_layout_look(look, layout):
"""Outline, shadow, second color, effect and relief, as set in the editor."""
given = _layout_data(layout).get("look")
if not isinstance(given, dict):
return look
full = web.make_look(web.clean_look(given))
for name in LAYOUT_LOOK:
setattr(look, name, getattr(full, name))
return look
class TextFix(object):
@classmethod
def INPUT_TYPES(cls):
fonts = list(list_fonts().keys()) or ["default"]
return {"required": {
"image": ("IMAGE",),
"text": ("STRING", {"multiline": True, "default": "", "tooltip": (
"One line for each piece of text found, in the order of the numbers on the `found` output. "
"An empty line leaves that text as it is. Not used once lines are picked in the editor.")}),
"font": (fonts,),
"color": ("STRING", {"default": AUTO, "tooltip": "auto: the color of the old letters. Or #rrggbb."}),
"point_x": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001, "tooltip": (
"Both points at 0: the text is looked for over the whole image. Otherwise: the place of the "
"text to replace, as a share of the image's width and height.")}),
"point_y": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
"search_area": ("FLOAT", {"default": 0.3, "min": 0.1, "max": 1.0, "step": 0.05}),
}, "optional": {
# New inputs go here, at the end: a saved workflow keeps its widget values by
# position, and anything put earlier would shift them.
"size": ("FLOAT", {"default": 1.0, "min": 0.5, "max": 2.0, "step": 0.01}),
"spread": ("FLOAT", {"default": 0.6, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": (
"How far a text shorter than the old one is spread to the old width.")}),
"match_stroke": ("BOOLEAN", {"default": True, "tooltip": (
"Make the strokes as thick as the old letters' were.")}),
"unevenness": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.05}),
"shading": ("FLOAT", {"default": 0.6, "min": 0.0, "max": 1.0, "step": 0.05, "tooltip": (
"How much of the surface's light and shadow shows on the letters.")}),
"opacity": ("FLOAT", {"default": 1.0, "min": 0.3, "max": 1.0, "step": 0.01}),
"soften": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 3.0, "step": 0.1}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFF}),
"weight": ("FLOAT", {"default": 0.0, "min": -1.0, "max": 1.0, "step": 0.05, "tooltip": (
"Thinner or bolder strokes, used when match_stroke is off.")}),
"shift_x": ("FLOAT", {"default": 0.0, "min": -2.0, "max": 2.0, "step": 0.02}),
"shift_y": ("FLOAT", {"default": 0.0, "min": -2.0, "max": 2.0, "step": 0.02}),
# Written by the editor: the selected lines and their texts. Hidden on the node.
"layout": ("STRING", {"default": "", "multiline": False}),
}, "hidden": {"unique_id": "UNIQUE_ID"}}
RETURN_TYPES = ("IMAGE", "MASK", "IMAGE")
RETURN_NAMES = ("image", "mask", "found")
FUNCTION = "run"
CATEGORY = "image/postprocessing"
def run(self, image, text, font, color, point_x, point_y, search_area, size=1.0, spread=0.6,
match_stroke=True, unevenness=0.0, shading=0.6, opacity=1.0, soften=0.7, seed=0, weight=0.0,
shift_x=0.0, shift_y=0.0, layout="", unique_id=None):
look = Look(font_path=list_fonts().get(font),
color=None if color.strip().lower() in ("", AUTO) else parse_color(color),
size=size, fill=spread, weight=None if match_stroke else weight, uneven=unevenness,
shading=shading, opacity=opacity, soften=soften, seed=seed, shift_x=shift_x, shift_y=shift_y)
look = add_layout_look(look, layout)
items = read_layout(layout)
lines = text.split("\n")
frames, masks, views = [], [], []
for index, frame in enumerate(image):
rgb = (frame[..., :3].cpu().numpy() * 255.0).clip(0, 255).astype(np.uint8)
height, width = rgb.shape[:2]
if index == 0 and unique_id is not None:
web.remember_node_image(unique_id, Image.fromarray(rgb)) # what the editor opens with
if items:
session = web.Session(Image.fromarray(rgb))
found = session.find()
jobs = [(session.resolve(item["recipe"]), item["text"], item["erase"]) for item in items]
jobs = [job for job in jobs if job[0] is not None]
if len(jobs) < len(items):
print("[Text Fix] %d of the lines picked in the editor are not on this image"
% (len(items) - len(jobs)))
elif point_x > 0 or point_y > 0:
one = locate(rgb, int(point_x * (width - 1)), int(point_y * (height - 1)), reach=search_area)
found = [one] if one is not None else []
jobs = [(found[0], " ".join(text.split()), False)] if found else []
else:
found = web.find_text(rgb) # the detector when its models are here, else by looks
jobs = [(selection, line, False) for selection, line in zip(found, lines)]
if not found and not items:
print("[Text Fix] no text found in the image")
view = preview(rgb, [job[0] for job in jobs] if items else found, found if items else ())
mask = np.zeros((height, width), bool)
for selection, line, erase_only in jobs:
if erase_only:
rgb = erase(rgb, selection)
mask |= blend_mask(rgb.shape, selection)
elif line.strip():
rgb = replace(rgb, selection, line, look)
mask |= blend_mask(rgb.shape, selection)
frames.append(torch.from_numpy(rgb.astype(np.float32) / 255.0))
masks.append(torch.from_numpy(mask.astype(np.float32)))
views.append(torch.from_numpy(view.astype(np.float32) / 255.0))
return (torch.stack(frames), torch.stack(masks), torch.stack(views))
def _sampler_choices():
try:
import comfy.samplers
return comfy.samplers.KSampler.SAMPLERS, comfy.samplers.KSampler.SCHEDULERS
except ImportError: # outside ComfyUI
return ["euler_ancestral"], ["normal"]
def _crop_box(mask, padding, width, height):
"""The box the pass works on: around the mask with `padding` pixels, widened to a square
as far as the image allows, as the A1111 family's "only masked" inpainting does."""
ys, xs = np.nonzero(mask)
x0, x1 = max(0, xs.min() - padding), min(width, xs.max() + 1 + padding)
y0, y1 = max(0, ys.min() - padding), min(height, ys.max() + 1 + padding)
side = max(x1 - x0, y1 - y0)
for low, high, size, axis in ((x0, x1, width, "x"), (y0, y1, height, "y")):
grow = min(side, size) - (high - low)
low = max(0, low - grow // 2)
high = min(size, low + min(side, size))
low = max(0, high - min(side, size))
if axis == "x":
x0, x1 = low, high
else:
y0, y1 = low, high
return int(x0), int(y0), int(x1), int(y1)
class TextFixBlend(object):
"""The model pass of the A1111 family, as one node: a light inpainting pass over the new
text only. Feed it the image and the mask of the Text Fix node, and the model, the
conditioning and the VAE of the workflow."""
@classmethod
def INPUT_TYPES(cls):
samplers, schedulers = _sampler_choices()
return {"required": {
"image": ("IMAGE",),
"mask": ("MASK",),
"model": ("MODEL",),
"positive": ("CONDITIONING", {"tooltip": "Leave out of it the words that ask for text."}),
"negative": ("CONDITIONING", {"tooltip": "\"text, letters, watermark\" in it helps."}),
"vae": ("VAE",),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}),
"steps": ("INT", {"default": 24, "min": 1, "max": 100}),
"cfg": ("FLOAT", {"default": 5.0, "min": 1.0, "max": 20.0, "step": 0.5}),
"sampler_name": (samplers, {"default": "euler_ancestral" if "euler_ancestral" in samplers else samplers[0]}),
"scheduler": (schedulers,),
"denoise": ("FLOAT", {"default": 0.3, "min": 0.05, "max": 0.8, "step": 0.01, "tooltip": (
"0.25 to 0.35 keeps the letters readable; higher brings the gibberish back.")}),
"resolution": ("INT", {"default": 1024, "min": 512, "max": 2048, "step": 64, "tooltip": (
"The size the spot is enlarged to: 1024 for SDXL, 512 to 768 for SD 1.5.")}),
"padding": ("INT", {"default": 64, "min": 0, "max": 512, "step": 8, "tooltip": (
"How much of the surroundings the model sees, in pixels.")}),
}}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "run"
CATEGORY = "image/postprocessing"
def run(self, image, mask, model, positive, negative, vae, seed, steps, cfg, sampler_name, scheduler, denoise,
resolution, padding):
import comfy.utils
import nodes
out = []
for index in range(image.shape[0]):
frame = image[index]
height, width = frame.shape[:2]
spot = mask[min(index, mask.shape[0] - 1)].cpu().numpy() > 0.5
if spot.shape != (height, width) or not spot.any():
out.append(frame)
continue
x0, y0, x1, y1 = _crop_box(spot, padding, width, height)
scale = resolution / float(max(x1 - x0, y1 - y0))
w8 = max(64, int(round((x1 - x0) * scale / 8.0)) * 8)
h8 = max(64, int(round((y1 - y0) * scale / 8.0)) * 8)
crop = frame[y0:y1, x0:x1, :3].unsqueeze(0).movedim(-1, 1)
crop = comfy.utils.common_upscale(crop, w8, h8, "lanczos", "disabled").movedim(1, -1)
# The mask, softened so the repainted part runs into the rest.
soft = cv2.GaussianBlur(spot[y0:y1, x0:x1].astype(np.float32), (0, 0), max(1.0, 0.015 * max(x1 - x0, y1 - y0)))
soft = np.clip(soft * 1.6, 0.0, 1.0)
soft_big = torch.from_numpy(cv2.resize(soft, (w8, h8), interpolation=cv2.INTER_LINEAR))
latent = {"samples": vae.encode(crop[:, :, :, :3]), "noise_mask": soft_big.reshape(1, 1, h8, w8)}
sampled = nodes.common_ksampler(model, seed + index, steps, cfg, sampler_name, scheduler, positive, negative,
latent, denoise=denoise)[0]
painted = vae.decode(sampled["samples"])
if painted.dim() == 5: # some VAEs give a batch of frames
painted = painted.reshape(-1, *painted.shape[-3:])
painted = painted[:1].movedim(-1, 1)
painted = comfy.utils.common_upscale(painted, x1 - x0, y1 - y0, "lanczos", "disabled").movedim(1, -1)[0]
alpha = torch.from_numpy(soft)[..., None].to(painted.device)
result = frame.clone()
region = result[y0:y1, x0:x1, :3]
result[y0:y1, x0:x1, :3] = (region.to(painted.device) * (1 - alpha) + painted[..., :3] * alpha).to(region.device)
out.append(result.clamp(0, 1))
return (torch.stack(out),)
NODE_CLASS_MAPPINGS = {"TextFix": TextFix, "TextFixBlend": TextFixBlend}
NODE_DISPLAY_NAME_MAPPINGS = {"TextFix": "Text Fix", "TextFixBlend": "Text Fix Blend"}