"""The editor's server side: the images being worked on, and the routes the page calls.
The same routes are added to an A1111-family host (FastAPI, see register) and to ComfyUI
(aiohttp, see register_aiohttp). Everything a route does is a plain function that returns
(status, body), so both hosts share it.
A selection is never sent to the page as pixels. The page holds a recipe for it: where it
was clicked, or which of the found lines it is, and the clicks that extended it. The server
turns a recipe into a Selection of the image it belongs to and keeps the answer, so the same
recipe is cheap to ask about again. A recipe means the same thing on the same image the next
time, which is what lets a ComfyUI node keep its selections in a widget.
"""
import collections
import io
import json
import os
import random
import re
import sys
import threading
import time
import uuid
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from PIL import Image, PngImagePlugin
from .core import (EFFECTS, Look, Selection, blend_mask, erase, find_all, follow_path, join, locate, match_fonts,
paint, parse_color, replace, reshape, shape_of, warp)
from .fonts import list_fonts
from . import neural
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXTENSION = os.path.basename(BASE_DIR)
SETTINGS_FILE = os.path.join(BASE_DIR, "user_settings.json")
PRESETS_FILE = os.path.join(BASE_DIR, "user_presets.json")
PREFIX = "/text_fix"
MAX_SESSIONS = 8
UNDO_STEPS = 8
MISSING_PAGE = ("
"
"Text Fix: the editor is not built
ui/dist/index.html is missing. Reinstall the "
"extension, or build the editor with npm run build in the ui folder.
")
# How the text is drawn, as the page names it. Each entry: default, and the Look argument.
LOOK_DEFAULTS = {
"font": "Arial Bold", "color": "#ffffff", "ownColor": True, "size": 1.0, "fill": 0.6, "matchWeight": True,
"weight": 0.0, "uneven": 0.0, "seed": 0, "shading": 0.6, "opacity": 1.0, "soften": 0.7, "shiftX": 0.0,
"shiftY": 0.0, "twoColors": False, "color2": "#ff5a3c", "split": 1.0, "outline": 0.0,
"outlineColor": "#000000", "shadow": 0.0, "shadowColor": "#000000", "shadowX": 0.06, "shadowY": 0.08,
"shadowBlur": 0.04, "effect": "none", "effectStrength": 1.0, "relief": 0.0,
}
COLOR_KEYS = ("color", "color2", "outlineColor", "shadowColor")
WARP_ROWS, WARP_COLS = 3, 4 # the grid of a hand warp
MODEL_DEFAULTS = {
"strength": 0.3, "steps": 24, "cfg": 5.0, "sampler": "Euler a", "resolution": 1024, "padding": 64,
"variants": 1, "cleanPrompt": True, "guide": "", "guideWeight": 0.6,
}
MAX_VARIANTS = 4
# Tags of a prompt that ask the model for text. In a pass over new letters they make it write
# letters of its own, so the pass leaves them out.
ASKS_FOR_TEXT = re.compile(
r"\b(text|texts|letter|letters|lettering|lettered|word|words|wording|writing|written|typography|"
r"typeface|font|fonts|calligraphy|inscription|inscribed|caption|captions|headline|slogan|logo|logos|"
r"label|labels|says|saying|signage|graffiti|watermark|signature|speech bubble|title|subtitles?)\b",
re.IGNORECASE)
QUOTED = re.compile(r"[\"“”][^\"“”]*[\"“”]")
NO_TEXT = ("text", "letters", "watermark")
def clean_prompt(prompt):
# type: (str) -> Tuple[str, List[str]]
"""The prompt without the tags that ask for text, and the tags left out. A tag is a part
between commas; LoRA and embedding calls (<...>) are kept whatever their names say."""
kept, removed = [], []
for tag in (prompt or "").split(","):
words = tag.strip()
if not words:
continue
if "<" not in words and (ASKS_FOR_TEXT.search(words) or QUOTED.search(words)):
removed.append(words.strip("()[]{} "))
# Keep the brackets of a weighted group the tag opened or closed, so the rest
# of the prompt is read the same way.
brackets = "".join(char for char in words if char in "()[]")
weight = re.search(r":\s*[\d.]+\s*\)\s*$", words)
if weight:
brackets = brackets.replace(")", "", 1)
kept.append(":" + weight.group(0).split(":", 1)[1].strip())
if brackets:
kept.append(brackets)
continue
kept.append(words)
text = ", ".join(kept)
text = re.sub(r",\s*([)\]])", r"\1", text)
text = re.sub(r",\s*:", ":", text)
text = re.sub(r"([(\[])\s*,\s*", r"\1", text)
text = re.sub(r"\(\s*:[\d.\s]+\)|\(\s*\)|\[\s*\]", "", text)
text = re.sub(r"(,\s*){2,}", ", ", text).strip(" ,")
return text, removed
def negative_without_text(negative):
# type: (str) -> str
"""The negative prompt with "text, letters, watermark" at its end, unless it has them."""
have = set(part.strip().lower() for part in (negative or "").split(","))
wanted = [word for word in NO_TEXT if word not in have]
if not wanted:
return negative
return ", ".join([part for part in [(negative or "").strip(" ,")] if part] + wanted)
LIMITS = {
"size": (0.5, 2.0), "fill": (0.0, 1.0), "weight": (-1.0, 1.0), "uneven": (0.0, 1.0), "seed": (0, 1000),
"shading": (0.0, 1.0), "opacity": (0.3, 1.0), "soften": (0.0, 3.0), "shiftX": (-2.0, 2.0), "shiftY": (-2.0, 2.0),
"strength": (0.05, 0.6), "steps": (4, 60), "cfg": (1.0, 15.0), "resolution": (512, 1536), "padding": (16, 256),
"reach": (0.1, 1.0), "variants": (1, MAX_VARIANTS), "guideWeight": (0.1, 1.5), "split": (0.0, 1.0), "outline": (0.0, 0.3), "shadow": (0.0, 1.0), "shadowX": (-0.5, 0.5),
"shadowY": (-0.5, 0.5), "shadowBlur": (0.0, 0.5), "effectStrength": (0.0, 1.0), "relief": (0.0, 1.0),
}
_lock = threading.Lock()
_sessions = collections.OrderedDict() # type: collections.OrderedDict
NODE_IMAGES = {} # type: Dict[str, Image.Image] # ComfyUI: the image each node last worked on
# ---------------------------------------------------------------- values from the page
def _number(value, default, limits=None, whole=False):
try:
number = float(value)
except (TypeError, ValueError):
return default
if number != number: # NaN
return default
if limits:
number = min(max(number, limits[0]), limits[1])
return int(round(number)) if whole else number
def clean_look(given):
# type: (Any) -> Dict[str, Any]
"""The page's look settings, each checked and in range; what is missing takes its default."""
given = given if isinstance(given, dict) else {}
out = dict(LOOK_DEFAULTS)
for key, default in LOOK_DEFAULTS.items():
if key not in given:
continue
value = given[key]
if isinstance(default, bool):
out[key] = bool(value)
elif isinstance(default, str):
if isinstance(value, str) and len(value) < 200:
out[key] = value
else:
out[key] = _number(value, default, LIMITS.get(key), whole=isinstance(default, int))
for key in COLOR_KEYS:
if parse_color(out[key]) is None:
out[key] = LOOK_DEFAULTS[key]
if out["effect"] not in EFFECTS:
out["effect"] = "none"
return out
def clean_model(given):
# type: (Any) -> Dict[str, Any]
given = given if isinstance(given, dict) else {}
out = dict(MODEL_DEFAULTS)
for key, default in MODEL_DEFAULTS.items():
if key not in given:
continue
value = given[key]
if isinstance(default, bool):
out[key] = bool(value)
elif isinstance(default, str):
if isinstance(value, str) and len(value) < 100:
out[key] = value
else:
out[key] = _number(value, default, LIMITS.get(key), whole=isinstance(default, int))
for key in ("prompt", "negative"):
value = given.get(key)
out[key] = value if isinstance(value, str) and len(value) < 20000 else ""
return out
def make_look(values):
# type: (Dict[str, Any]) -> Look
return Look(font_path=list_fonts().get(values["font"]),
color=None if values["ownColor"] else parse_color(values["color"]),
size=values["size"], fill=values["fill"], weight=None if values["matchWeight"] else values["weight"],
uneven=values["uneven"], seed=values["seed"], shading=values["shading"],
opacity=values["opacity"], soften=values["soften"], shift_x=values["shiftX"],
shift_y=values["shiftY"],
color2=parse_color(values["color2"]) if values["twoColors"] else None, split=values["split"],
outline=values["outline"], outline_color=parse_color(values["outlineColor"]),
shadow=values["shadow"], shadow_color=parse_color(values["shadowColor"]),
shadow_x=values["shadowX"], shadow_y=values["shadowY"], shadow_blur=values["shadowBlur"],
effect=values["effect"], effect_strength=values["effectStrength"], relief=values["relief"])
def clean_recipe(given, nested=False):
# type: (Any, bool) -> Optional[Dict[str, Any]]
"""A recipe from the page, or None when it is not one.
Where the letters come from, one of:
{"found": index} one of the lines the search found
{"at": [x, y], "reach": r} a click
{"join": [recipe, ...]} several lines taken as one block
and, on top of that:
"extend": [[x, y], ...] clicks that joined more letters to it
"shape": {"corners": [[x, y] x4], "bend": b} the place for the new text, set by hand
"paint": [{"points": [[x, y], ...], "radius": r}] brush strokes: more to erase
"path": [[x, y], ...] the new text written along this line instead
"warp": [[[dx, dy] x 4] x 3] the new letters bent by hand: a grid of moves
"""
if not isinstance(given, dict):
return None
recipe = {} # type: Dict[str, Any]
if isinstance(given.get("found"), int) and 0 <= given["found"] < 100:
recipe["found"] = given["found"]
elif _point(given.get("at")) is not None:
recipe["at"] = _point(given["at"])
recipe["reach"] = _number(given.get("reach"), 0.3, LIMITS["reach"])
elif not nested and isinstance(given.get("join"), list):
parts = [clean_recipe(part, nested=True) for part in given["join"][:12]]
parts = [part for part in parts if part is not None]
if not parts:
return None
recipe["join"] = parts
else:
return None
extend = given.get("extend")
if isinstance(extend, list) and "join" not in recipe:
points = [_point(item) for item in extend[:20]]
points = [point for point in points if point is not None]
if points:
recipe["extend"] = points
recipe["reach"] = _number(given.get("reach"), 0.3, LIMITS["reach"])
shape = given.get("shape")
if not nested and isinstance(shape, dict) and isinstance(shape.get("corners"), list) and len(shape["corners"]) == 4:
corners = [_fpoint(corner) for corner in shape["corners"]]
if all(corner is not None for corner in corners):
recipe["shape"] = {"corners": corners, "bend": _number(shape.get("bend"), 0.0, (-5000.0, 5000.0))}
strokes = given.get("paint")
if not nested and isinstance(strokes, list):
kept = []
for stroke in strokes[:60]:
if not isinstance(stroke, dict) or not isinstance(stroke.get("points"), list):
continue
points = [_point(point) for point in stroke["points"][:400]]
points = [point for point in points if point is not None]
if points:
kept.append({"points": points, "radius": _number(stroke.get("radius"), 6.0, (1.0, 200.0))})
if kept:
recipe["paint"] = kept
path = given.get("path")
if not nested and isinstance(path, list):
points = [_fpoint(point) for point in path[:600]]
points = [point for point in points if point is not None]
if len(points) >= 2:
recipe["path"] = points
grid = given.get("warp")
if not nested and isinstance(grid, list) and len(grid) == WARP_ROWS:
rows = []
for row in grid:
if not isinstance(row, list) or len(row) != WARP_COLS:
break
moves = [_fpoint(move) for move in row]
if any(move is None or abs(move[0]) > 2000 or abs(move[1]) > 2000 for move in moves):
break
rows.append(moves)
if len(rows) == WARP_ROWS and any(value for row in rows for move in row for value in move):
recipe["warp"] = rows
return recipe
def _fpoint(value):
"""A point with its fractions kept to a tenth of a pixel: corners dragged by hand."""
if isinstance(value, (list, tuple)) and len(value) == 2:
try:
x, y = round(float(value[0]), 1), round(float(value[1]), 1)
except (TypeError, ValueError):
return None
if -100000 < x < 100000 and -100000 < y < 100000 and x == x and y == y:
return [x, y]
return None
def _point(value):
if isinstance(value, (list, tuple)) and len(value) == 2:
try:
x, y = int(round(float(value[0]))), int(round(float(value[1])))
except (TypeError, ValueError):
return None
if 0 <= x < 100000 and 0 <= y < 100000:
return [x, y]
return None
def clean_items(given):
# type: (Any) -> List[Dict[str, Any]]
"""[{"recipe": ..., "text": ..., "erase": bool}] in the order of their numbers; broken
entries are dropped. "erase": the old letters go and nothing is written in their place."""
items = []
for entry in (given if isinstance(given, list) else [])[:50]:
if not isinstance(entry, dict):
continue
recipe = clean_recipe(entry.get("recipe"))
text = entry.get("text")
if recipe is not None:
items.append({"recipe": recipe, "text": text[:2000] if isinstance(text, str) else "",
"erase": bool(entry.get("erase"))})
return items
# ---------------------------------------------------------------- settings kept between sessions
SEARCHES = ("auto", "looks", "light", "full")
def _search(value):
"""How the text is looked for: "looks" (by looks alone), "light" or "full" (a detector),
or "auto": the light detector when its models are here, else by looks."""
return value if value in SEARCHES else "auto"
def search_in_use(choice=None):
# type: (Optional[str]) -> str
"""The search that actually runs: a detector only when its models are here and
onnxruntime can be imported."""
choice = _search(choice if choice is not None else load_settings()["search"])
if choice == "auto":
choice = "light"
if choice in ("light", "full") and neural.available() and neural.ready(choice):
return choice
return "looks"
def find_text(rgb, choice=None):
# type: (np.ndarray, Optional[str]) -> List[Selection]
"""Every line of text on an image, by the search that is set: the detector, or by looks.
A detector that fails falls back to the search by looks."""
use = search_in_use(choice)
if use != "looks":
try:
return neural.find(rgb, use)
except Exception as error:
sys.stderr.write("text_fix: the detector failed, looking by looks instead: %r\n" % (error,))
return find_all(rgb)
def reading_for(rgb, selection):
# type: (np.ndarray, Selection) -> str
"""What the old letters of a selection say, when reading is on and the reader is here."""
if not load_settings()["readOld"]:
return ""
reading = getattr(selection, "reading", None)
if reading is not None:
return reading
if not (neural.available() and neural.present("rec") and neural.present("dict")):
return ""
try:
text, sure = neural.reading_of(rgb, selection)
except Exception:
return ""
return text if sure >= 0.3 else ""
def load_settings():
# type: () -> Dict[str, Any]
try:
with io.open(SETTINGS_FILE, encoding="utf-8") as handle:
data = json.load(handle)
except (IOError, OSError, ValueError):
data = {}
data = data if isinstance(data, dict) else {}
model = clean_model(data.get("model"))
model.pop("prompt", None) # a prompt belongs to an image, not to the settings
model.pop("negative", None)
return {"look": clean_look(data.get("look")), "model": model,
"reach": _number(data.get("reach"), 0.3, LIMITS["reach"]),
"showFound": bool(data.get("showFound", True)), "search": _search(data.get("search")),
"readOld": bool(data.get("readOld", True))}
def save_settings(given):
given = given if isinstance(given, dict) else {}
model = clean_model(given.get("model"))
model.pop("prompt", None)
model.pop("negative", None)
data = {"look": clean_look(given.get("look")), "model": model,
"reach": _number(given.get("reach"), 0.3, LIMITS["reach"]),
"showFound": bool(given.get("showFound", True)), "search": _search(given.get("search")),
"readOld": bool(given.get("readOld", True))}
temporary = SETTINGS_FILE + ".tmp"
with io.open(temporary, "w", encoding="utf-8") as handle:
json.dump(data, handle, indent=2)
os.replace(temporary, SETTINGS_FILE)
return data
# ---------------------------------------------------------------- images being worked on
def prompts_of(parameters):
# type: (Optional[str]) -> Tuple[str, str]
"""Prompt and negative prompt from the generation parameters an A1111-family host
writes into its PNGs: the prompt, "Negative prompt: ...", then a line of settings."""
if not parameters:
return "", ""
lines = parameters.strip().split("\n")
if len(lines) > 1 and re.match(r"^\s*\w[\w ]*: ", lines[-1]) and "Steps:" in lines[-1]:
lines = lines[:-1]
text = "\n".join(lines)
prompt, marker, negative = text.partition("Negative prompt:")
return prompt.strip(), negative.strip() if marker else ""
class Session(object):
"""One image in the editor, with what was found on it and the steps it went through."""
def __init__(self, image, name=""):
info = image.info if isinstance(getattr(image, "info", None), dict) else {}
parameters = info.get("parameters")
self.id = uuid.uuid4().hex
self.name = name or ""
self.parameters = parameters if isinstance(parameters, str) else None
self.history = [] # type: List[Image.Image] # images "Use as the image" replaced, for Undo
self.lock = threading.Lock() # one render of this session at a time
self.version = 0
self.set_image(image.convert("RGB"))
def set_image(self, image):
self.image = image
self.rgb = np.asarray(image)
self.found = None # type: Optional[List[Selection]]
self.picked = {} # type: Dict[str, Optional[Selection]]
self.result = None # type: Optional[Image.Image]
self.variants = [] # type: List[Image.Image] # the last model pass, one per seed
self.png = {} # type: Dict[str, bytes]
def find(self):
# type: () -> List[Selection]
if self.found is None:
try:
self.found = find_text(self.rgb)
except Exception as error: # the search is a help: a click still works without it
sys.stderr.write("text_fix: the search over the image failed: %r\n" % (error,))
self.found = []
return self.found
def resolve(self, recipe):
# type: (Dict[str, Any]) -> Optional[Selection]
"""The selection a recipe stands for on this image; worked out once."""
key = json.dumps(recipe, sort_keys=True)
if key in self.picked:
return self.picked[key]
reach = recipe.get("reach", 0.3)
if "join" in recipe:
selection = join([self.resolve(part) for part in recipe["join"]])
elif "found" in recipe:
found = self.find()
selection = found[recipe["found"]] if recipe["found"] < len(found) else None
else:
selection = locate(self.rgb, recipe["at"][0], recipe["at"][1], reach=reach)
for x, y in recipe.get("extend", []):
if selection is None:
break
selection = locate(self.rgb, x, y, reach=reach, add_to=selection)
if selection is not None and "shape" in recipe:
selection = reshape(selection, recipe["shape"]["corners"], recipe["shape"]["bend"])
if selection is not None and "paint" in recipe:
selection = paint(selection, [(stroke["points"], stroke["radius"]) for stroke in recipe["paint"]])
if selection is not None and "path" in recipe:
selection = follow_path(selection, recipe["path"])
if selection is not None and "warp" in recipe:
selection = warp(selection, recipe["warp"])
self.picked[key] = selection
return selection
def new_session(image, name=""):
session = Session(image, name)
with _lock:
_sessions[session.id] = session
while len(_sessions) > MAX_SESSIONS:
_sessions.popitem(last=False)
return session
def get_session(session_id):
with _lock:
session = _sessions.get(session_id or "")
if session is not None:
_sessions.move_to_end(session.id)
return session
def result_image(session_id):
# type: (str) -> Optional[Image.Image]
"""What "Send to gallery" sends: the result, or the image when there is none."""
session = get_session(session_id)
if session is None:
return None
image = session.result or session.image
if session.parameters:
image = image.copy()
image.info["parameters"] = session.parameters
return image
def describe(selection):
# type: (Selection) -> Dict[str, Any]
"""A selection as the page draws it: its outline, its box and the color of its letters."""
corners, bend = shape_of(selection)
return {
"outline": [[round(float(x), 1), round(float(y), 1)] for x, y in selection.outline_points()],
"quad": [[round(float(x), 1), round(float(y), 1)] for x, y in selection.quad],
"corners": [[round(float(x), 1), round(float(y), 1)] for x, y in corners],
"bend": round(bend, 1),
"color": "#%02x%02x%02x" % tuple(int(c) for c in selection.color[:3]),
"width": int(round(selection.width())),
"height": int(round(selection.height())),
"path": getattr(selection, "path", None) is not None,
# The middle of the text, through which a hand warp's grid is shown: rows across the
# letters from their top to their bottom, columns along the text.
"grid": warp_grid(selection),
}
def warp_grid(selection):
"""Where the points of a hand warp sit before they are moved: WARP_ROWS x WARP_COLS
points spread over the text, as the page draws them."""
rows = []
wide, tall = selection.width(), selection.height()
path = getattr(selection, "path", None)
for r in range(WARP_ROWS):
v = tall * r / (WARP_ROWS - 1)
row = []
for c in range(WARP_COLS):
a = wide * c / (WARP_COLS - 1)
if path is not None:
lengths = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(path, axis=0), axis=1))])
x = np.interp(a, lengths, path[:, 0])
y = np.interp(a, lengths, path[:, 1])
i = min(len(path) - 2, int(np.searchsorted(lengths, a, side="right")) - 1)
ahead = path[max(0, i) + 1] - path[max(0, i)]
ahead = ahead / max(1e-6, float(np.linalg.norm(ahead)))
point = np.array([x, y]) + np.array([-ahead[1], ahead[0]]) * (v - tall / 2.0)
else:
top = np.polyval(selection.top, a)
bottom = np.polyval(selection.bottom, a)
d = top + (bottom - top) * v / tall
point = selection.along * (selection.start + a) + selection.down * d
row.append([round(float(point[0]), 1), round(float(point[1]), 1)])
rows.append(row)
return rows
def session_payload(session):
found = session.find()
prompt, negative = prompts_of(session.parameters)
return {
"session": session.id, "width": session.image.width, "height": session.image.height,
"name": session.name, "found": [describe(selection) for selection in found],
"prompt": prompt, "negative": negative, "history": len(session.history), "version": session.version,
}
def image_names():
return ("image", "result") + tuple("variant-%d" % i for i in range(MAX_VARIANTS))
def session_png(session, which):
if which.startswith("variant-") and int(which[8:]) < len(session.variants):
image, key = session.variants[int(which[8:])], which
else:
image = session.result if which == "result" and session.result is not None else session.image
key = "result" if image is session.result else "image"
with _lock:
cached = session.png.get(key)
if cached is None:
buffer = io.BytesIO()
image.save(buffer, "PNG", compress_level=1)
cached = buffer.getvalue()
with _lock:
session.png[key] = cached
return cached
def draw(session, items, look):
# type: (Session, List[Dict[str, Any]], Look) -> Tuple[Optional[np.ndarray], List[Selection]]
"""The session's image with every item done: new text drawn in, or the old letters only
erased. Items with neither are left as they are. (None, []) when nothing was done."""
rgb = session.rgb
done = []
for item in items:
text = item["text"] if item["text"].strip() else ""
if not text and not item.get("erase"):
continue
selection = session.resolve(item["recipe"])
if selection is None:
continue
rgb = erase(rgb, selection) if item.get("erase") else replace(rgb, selection, text, look)
done.append(selection)
return (rgb if done else None), done
ERASE_LINE = "-"
def by_prominence(found):
# type: (List[Selection]) -> List[Selection]
"""The lines found, the most prominent first: the largest, then the most clearly text."""
return sorted(found, key=lambda selection: (-selection.width() * selection.height(), -selection.score))
def auto_replace(rgb, lines, look):
# type: (np.ndarray, str, Look) -> Tuple[np.ndarray, List[Selection]]
"""A list of replacements applied without a click: the first line goes onto the most
prominent text found, the second onto the next one, and so on. An empty line leaves that
text as it is, a line with only a dash erases it. Returns the image and what was done."""
wanted = (lines or "").replace("\r", "").split("\n")
while wanted and not wanted[-1].strip():
wanted.pop()
if not wanted:
return rgb, []
done = []
for selection, line in zip(by_prominence(find_text(rgb)), wanted):
line = " ".join(line.split())
if not line:
continue
rgb = erase(rgb, selection) if line == ERASE_LINE else replace(rgb, selection, line, look)
done.append(selection)
return rgb, done
def look_named(name):
# type: (Any) -> Look
"""A saved preset by its name; the editor's own look when there is no such preset."""
presets = load_presets()
values = presets.get(name) if isinstance(name, str) else None
return make_look(values if values is not None else load_settings()["look"])
# ---------------------------------------------------------------- a whole folder at once
IMAGE_FILES = (".png", ".jpg", ".jpeg", ".webp")
_batch_lock = threading.Lock()
BATCH = {"running": False, "stop": False, "done": 0, "total": 0, "changed": 0, "failed": 0, "output": "",
"current": "", "error": "", "warnings": []} # type: Dict[str, Any]
def _batch_state():
with _batch_lock:
state = dict(BATCH)
state["warnings"] = list(BATCH["warnings"][-5:])
return state
def _run_batch(host, files, output, lines, look, blend, model):
for path in files:
with _batch_lock:
if BATCH["stop"]:
break
BATCH["current"] = os.path.basename(path)
try:
image = Image.open(path)
image.load()
parameters = image.info.get("parameters") if isinstance(image.info.get("parameters"), str) else None
rgb, done = auto_replace(np.asarray(image.convert("RGB")), lines, look)
result = Image.fromarray(rgb)
if done and blend:
prompt, negative = prompts_of(parameters)
pass_model, _ = model_prompts(dict(model, prompt=prompt, negative=negative))
for selection in done:
result = host.blend(result, selection, dict(pass_model, seed=random.randrange(0, 2 ** 31))).convert("RGB")
info = None
if parameters:
info = PngImagePlugin.PngInfo()
info.add_text("parameters", parameters)
name = os.path.splitext(os.path.basename(path))[0] + ".png"
result.save(os.path.join(output, name), "PNG", pnginfo=info)
with _batch_lock:
BATCH["changed"] += 1 if done else 0
if not done:
BATCH["warnings"].append("%s: no text found to replace" % os.path.basename(path))
except Exception as error: # one bad file must not stop the rest
with _batch_lock:
BATCH["failed"] += 1
BATCH["warnings"].append("%s: %s" % (os.path.basename(path), error))
with _batch_lock:
BATCH["done"] += 1
with _batch_lock:
BATCH["running"] = False
BATCH["current"] = ""
def answer_batch(body, host):
"""Start a whole folder (every image in it gets the list of replacements, and the model
pass when asked), stop it, or tell how far it got."""
body = body if isinstance(body, dict) else {}
action = body.get("action")
if action == "status":
return 200, _batch_state()
if action == "stop":
with _batch_lock:
BATCH["stop"] = True
return 200, _batch_state()
if not host.allows_folders():
return 403, {"error": "Folders can be processed only when the host is reached from this computer alone."}
folder = str(body.get("input") or "").strip().strip('"')
if not folder or not os.path.isdir(folder):
return 400, {"error": "That folder does not exist."}
lines = body.get("lines") if isinstance(body.get("lines"), str) else ""
if not lines.strip():
return 400, {"error": "Type at least one line of new text."}
files = sorted(os.path.join(folder, name) for name in os.listdir(folder) if name.lower().endswith(IMAGE_FILES))
if not files:
return 400, {"error": "There are no images in that folder."}
blend = bool(body.get("blend")) and host.can_blend()
with _batch_lock:
if BATCH["running"]:
return 409, {"error": "A folder is being processed already."}
output = os.path.join(host.output_folder(), "textfix-%s" % time.strftime("%Y%m%d-%H%M%S"))
os.makedirs(output, exist_ok=True)
BATCH.update({"running": True, "stop": False, "done": 0, "total": len(files), "changed": 0, "failed": 0,
"output": os.path.normpath(output), "current": "", "error": "", "warnings": []})
look = make_look(clean_look(body.get("look")))
model = clean_model(body.get("model"))
worker = threading.Thread(target=_run_batch, args=(host, files, output, lines, look, blend, model),
name="text_fix_batch", daemon=True)
worker.start()
return 200, _batch_state()
# ---------------------------------------------------------------- what the routes do
class Host(object):
"""What the editor needs from the host it runs in. The defaults are those of a host that
can do none of it: ComfyUI, where the model pass is left to the workflow."""
name = "comfyui"
def save(self, image, parameters, tab):
folder = os.path.join(BASE_DIR, "saved")
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, "textfix-%s.png" % time.strftime("%Y%m%d-%H%M%S"))
info = None
if parameters:
info = PngImagePlugin.PngInfo()
info.add_text("parameters", parameters)
image.save(path, "PNG", pnginfo=info)
return path
def blend(self, image, selection, model):
raise RuntimeError("The model pass runs in AUTOMATIC1111, Forge and reForge. In ComfyUI, feed the node's "
"image and mask outputs to an inpainting pass.")
def samplers(self):
return []
def controlnets(self):
"""The ControlNet models the pass can be guided by; empty when there are none."""
return []
def output_folder(self):
"""Where a processed folder goes: a new folder inside this one."""
return os.path.join(BASE_DIR, "saved")
def model_dir(self):
"""Where the detector's models are kept: text_fix in the host's models folder."""
return os.path.join(BASE_DIR, "models")
def allows_folders(self):
"""Reading a folder named on the page is let only to a host that is not reached from
other computers."""
return False
def can_blend(self):
return False
def answer_options(host):
fonts = list(list_fonts().keys()) or ["default"]
settings = load_settings()
if settings["look"]["font"] not in fonts:
settings["look"]["font"] = "Arial Bold" if "Arial Bold" in fonts else fonts[0]
try:
controlnets = list(host.controlnets())
except Exception: # ControlNet is an extra: the editor works without it
controlnets = []
return 200, {"fonts": fonts, "samplers": host.samplers(), "canBlend": host.can_blend(), "host": host.name,
"controlnets": controlnets, "presets": load_presets(), "models": models_state(),
"settings": settings, "defaults": {"look": LOOK_DEFAULTS, "model": MODEL_DEFAULTS},
"limits": LIMITS}
def answer_upload(data, name):
if not data:
return 400, {"error": "No image was sent."}
try:
image = Image.open(io.BytesIO(data))
image.load()
except Exception:
return 400, {"error": "That file is not an image this editor can open."}
if image.width * image.height > 40000000:
return 400, {"error": "The image is too large."}
return 200, session_payload(new_session(image, name))
def answer_node(body):
node = str((body or {}).get("node", ""))
image = NODE_IMAGES.get(node)
if image is None:
return 404, {"error": "Run the workflow once: the editor works on the image this node last received."}
return 200, session_payload(new_session(image, "node-%s" % node))
def _session_of(body):
session = get_session((body or {}).get("session"))
if session is None:
return None, (404, {"error": "This image is no longer open on the server. Open it again."})
return session, None
def answer_pick(body):
"""A click on the image: the selection at that point, or the last one extended by it."""
session, failure = _session_of(body)
if failure:
return failure
point = _point([body.get("x"), body.get("y")])
if point is None:
return 400, {"error": "Not a point."}
reach = _number(body.get("reach"), 0.3, LIMITS["reach"])
extend = clean_recipe(body.get("extend"))
with session.lock:
if extend is not None and "join" in extend:
return 400, {"error": "A block of joined lines cannot be extended: extend its lines before joining."}
if extend is not None:
recipe = dict(extend)
recipe.pop("shape", None) # the letters change, so does their place
recipe["extend"] = list(extend.get("extend", [])) + [point]
recipe["reach"] = reach
else:
recipe = None
for index, selection in enumerate(session.find()):
if selection.contains(point[0], point[1]):
recipe = {"found": index}
break
if recipe is None:
recipe = {"at": point, "reach": reach}
selection = session.resolve(recipe)
if selection is None:
return 200, {"recipe": None, "selection": None}
# What the old letters say, as a start for the new text (empty when reading is off).
return 200, {"recipe": recipe, "selection": describe(selection), "reading": reading_for(session.rgb, selection)}
def answer_models(body, host):
"""The detector's models: what is here, and fetching the ones a choice needs."""
body = body if isinstance(body, dict) else {}
if body.get("action") == "download":
choice = body.get("choice")
if choice not in neural.NEEDS:
return 400, {"error": "No such detector."}
if not neural.available():
return 400, {"error": "onnxruntime is not installed in this host's Python."}
neural.download(choice)
return 200, models_state()
def models_state():
sizes = {choice: sum(neural.MODELS[name][2] for name in names if not neural.present(name))
for choice, names in neural.NEEDS.items()}
return {"onnx": neural.available(), "ready": {choice: neural.ready(choice) for choice in neural.NEEDS},
"missing": sizes, "download": neural.download_state(), "inUse": search_in_use(),
"folder": neural.model_dir()}
def answer_resolve(body):
"""The selections a list of recipes stands for: for a page that opens with saved items."""
session, failure = _session_of(body)
if failure:
return failure
out = []
with session.lock:
for item in clean_items(body.get("items")):
selection = session.resolve(item["recipe"])
out.append(None if selection is None else describe(selection))
return 200, {"selections": out}
def answer_match(body):
"""The fonts most like the old letters of one selection, closest first."""
session, failure = _session_of(body)
if failure:
return failure
recipe = clean_recipe(body.get("recipe"))
if recipe is None:
return 400, {"error": "Select a line first."}
# The letters as they were found: a path or a hand shape moves the new text, not the old.
for key in ("path", "warp", "shape", "paint"):
recipe.pop(key, None)
with session.lock:
selection = session.resolve(recipe)
if selection is None:
return 200, {"fonts": []}
ranked = match_fonts(selection, list_fonts())
return 200, {"fonts": [{"name": name, "distance": round(distance, 3)} for name, distance in ranked[:5]]}
def answer_find(body):
session, failure = _session_of(body)
if failure:
return failure
with session.lock:
session.found = None
found = session.find()
return 200, {"found": [describe(selection) for selection in found]}
def answer_preview(body):
"""The new text drawn in, without the model. Cheap: runs on every change on the page."""
session, failure = _session_of(body)
if failure:
return failure
items = clean_items(body.get("items"))
look = make_look(clean_look(body.get("look")))
with session.lock:
rgb, done = draw(session, items, look)
session.result = None if rgb is None else Image.fromarray(rgb)
_forget_variants(session)
session.png.pop("result", None)
session.version += 1
version = session.version
return 200, {"version": version, "empty": rgb is None, "count": len(done)}
def _forget_variants(session):
for index in range(len(session.variants)):
session.png.pop("variant-%d" % index, None)
session.variants = []
def model_prompts(model):
# type: (Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]
"""The model settings as the pass gets them: with the tags that ask for text left out of
the prompt and "text" in the negative, unless that is turned off. Also the tags left out."""
model = dict(model)
if not model.get("cleanPrompt", True):
return model, []
model["prompt"], removed = clean_prompt(model.get("prompt") or "")
model["negative"] = negative_without_text(model.get("negative") or "")
return model, removed
def answer_blend(body, host):
session, failure = _session_of(body)
if failure:
return failure
if not host.can_blend():
return 400, {"error": "The model pass is not available here."}
items = clean_items(body.get("items"))
look = make_look(clean_look(body.get("look")))
model, removed = model_prompts(clean_model(body.get("model")))
count = int(model.get("variants", 1))
with session.lock:
rgb, done = draw(session, items, look)
if rgb is None:
return 400, {"error": "Type the new text first, or mark a line as erase only."}
drawn = Image.fromarray(rgb)
_forget_variants(session)
# One pass per variant, each with a seed of its own: the model repaints the letters a
# little differently every time, and one of them is usually right.
first = random.randrange(0, 2 ** 31 - MAX_VARIANTS)
seeds = []
try:
for index in range(count):
result = drawn
for selection in done:
result = host.blend(result, selection, dict(model, seed=first + index)).convert("RGB")
session.variants.append(result)
seeds.append(first + index)
except Exception as error: # the drawn text, and the variants made so far, are still worth showing
if not session.variants:
session.result = drawn
session.png.pop("result", None)
session.version += 1
return 200, {"version": session.version, "blended": False, "removed": removed,
"warning": "The text is drawn, but the model pass failed: %s" % error}
session.result = session.variants[0]
session.png.pop("result", None)
session.version += 1
answer = {"version": session.version, "blended": True, "count": len(done), "variants": len(session.variants),
"seeds": seeds, "removed": removed}
if len(session.variants) < count:
answer["warning"] = "Only %d of %d variants were made: the model pass failed." % (len(session.variants), count)
return 200, answer
def answer_choose(body):
"""One of the variants of the last model pass becomes the result."""
session, failure = _session_of(body)
if failure:
return failure
try:
index = int(body.get("index"))
except (TypeError, ValueError):
return 400, {"error": "Not a variant."}
with session.lock:
if not 0 <= index < len(session.variants):
return 400, {"error": "There is no such variant: run the model pass again."}
session.result = session.variants[index]
session.png.pop("result", None)
session.version += 1
return 200, {"version": session.version, "index": index}
def answer_apply(body):
""""Use as the image": the result becomes the image to go on with; the old one is kept for Undo."""
session, failure = _session_of(body)
if failure:
return failure
with session.lock:
if session.result is None:
return 400, {"error": "There is no result to use yet."}
session.history = (session.history + [session.image])[-UNDO_STEPS:]
session.set_image(session.result)
session.version += 1
return 200, session_payload(session)
def answer_undo(body):
session, failure = _session_of(body)
if failure:
return failure
with session.lock:
if not session.history:
return 400, {"error": "Nothing to undo."}
session.set_image(session.history.pop())
session.version += 1
return 200, session_payload(session)
def answer_save(body, host):
session, failure = _session_of(body)
if failure:
return failure
tab = "img2img" if (body or {}).get("tab") == "img2img" else "txt2img"
image = session.result or session.image
try:
path = host.save(image, session.parameters, tab)
except Exception as error:
return 500, {"error": "Could not save: %s" % error}
return 200, {"path": os.path.normpath(str(path))}
MAX_PRESETS = 60
def load_presets():
# type: () -> Dict[str, Dict[str, Any]]
"""The looks saved under a name, each checked as the page's look is."""
try:
with io.open(PRESETS_FILE, encoding="utf-8") as handle:
data = json.load(handle)
except (IOError, OSError, ValueError):
data = {}
if not isinstance(data, dict):
return {}
return {str(name)[:60]: clean_look(look) for name, look in list(data.items())[:MAX_PRESETS] if str(name).strip()}
def answer_presets(body):
"""Save the look under a name, or delete a saved one. Answers with all of them."""
body = body if isinstance(body, dict) else {}
name = " ".join(str(body.get("name", "")).split())[:60]
if not name:
return 400, {"error": "A preset needs a name."}
presets = load_presets()
if body.get("action") == "delete":
presets.pop(name, None)
else:
if name not in presets and len(presets) >= MAX_PRESETS:
return 400, {"error": "There are %d presets already: delete one first." % MAX_PRESETS}
presets[name] = clean_look(body.get("look"))
try:
temporary = PRESETS_FILE + ".tmp"
with io.open(temporary, "w", encoding="utf-8") as handle:
json.dump(presets, handle, indent=2, ensure_ascii=False)
os.replace(temporary, PRESETS_FILE)
except (IOError, OSError) as error:
return 500, {"error": "Could not keep the presets: %s" % error}
return 200, {"presets": presets}
def answer_settings(body):
try:
return 200, {"settings": save_settings(body)}
except (IOError, OSError) as error:
return 500, {"error": "Could not keep the settings: %s" % error}
def ui_html(base=None):
"""The built page, with its relative asset addresses turned into addresses of the host.
A fresh ?v= on each call keeps the browser from showing an old build.
"""
with io.open(os.path.join(BASE_DIR, "ui", "dist", "index.html"), encoding="utf-8") as handle:
html = handle.read()
base = base or "/file=extensions/%s/ui/dist" % EXTENSION
stamp = str(int(time.time()))
def swap(match):
return "%s=%s%s/%s?v=%s%s" % (match.group("attr"), match.group("q"), base, match.group("path")[2:],
stamp, match.group("q"))
return re.sub(r'(?P\b(?:src|href))=(?P["\'])(?P\./[^"\']+)(?P=q)', swap, html)
def font_file(name):
path = list_fonts().get(name or "")
return path if path and os.path.isfile(path) else None
def remember_node_image(node, image):
"""ComfyUI: keep the image a node received, for the editor opened on that node."""
NODE_IMAGES[str(node)] = image
while len(NODE_IMAGES) > 32:
NODE_IMAGES.pop(next(iter(NODE_IMAGES)))
# ---------------------------------------------------------------- the hosts' route tables
POSTS = {
"/find": answer_find, "/pick": answer_pick, "/resolve": answer_resolve, "/preview": answer_preview,
"/apply": answer_apply, "/undo": answer_undo, "/settings": answer_settings, "/session/node": answer_node,
"/match": answer_match, "/choose": answer_choose, "/presets": answer_presets,
}
def register(app, host):
"""Add the routes to the FastAPI app of an A1111-family host."""
neural.set_model_dir(host.model_dir())
from fastapi import Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
from starlette.concurrency import run_in_threadpool
def reply(answer):
return JSONResponse(answer[1], status_code=answer[0], headers={"Cache-Control": "no-store"})
async def body_of(request):
try:
body = await request.json()
except Exception:
body = None
return body if isinstance(body, dict) else {}
@app.get(PREFIX + "/ui")
async def page():
try:
return HTMLResponse(ui_html(), headers={"Cache-Control": "no-store"})
except (IOError, OSError):
return HTMLResponse(MISSING_PAGE, status_code=500)
@app.get(PREFIX + "/options")
async def options():
return reply(await run_in_threadpool(answer_options, host))
@app.get(PREFIX + "/font")
async def font(name: str = ""):
path = font_file(name)
if path is None:
return reply((404, {"error": "unknown font"}))
return FileResponse(path, headers={"Cache-Control": "max-age=86400"})
@app.post(PREFIX + "/session")
async def upload(request: Request, name: str = ""):
data = await request.body()
return reply(await run_in_threadpool(answer_upload, data, name))
@app.get(PREFIX + "/image/{session_id}/{which}")
async def image_bytes(session_id: str, which: str):
session = get_session(session_id)
if session is None or which not in image_names():
return reply((404, {"error": "unknown image"}))
data = await run_in_threadpool(session_png, session, which)
return Response(data, media_type="image/png", headers={"Cache-Control": "no-store"})
@app.post(PREFIX + "/blend")
async def blend(request: Request):
body = await body_of(request)
return reply(await run_in_threadpool(answer_blend, body, host))
@app.post(PREFIX + "/save")
async def save(request: Request):
body = await body_of(request)
return reply(await run_in_threadpool(answer_save, body, host))
@app.post(PREFIX + "/batch")
async def batch(request: Request):
body = await body_of(request)
return reply(await run_in_threadpool(answer_batch, body, host))
@app.post(PREFIX + "/models")
async def models(request: Request):
body = await body_of(request)
return reply(await run_in_threadpool(answer_models, body, host))
def add_post(path, function):
async def route(request: Request):
body = await body_of(request)
return reply(await run_in_threadpool(function, body))
app.add_api_route(PREFIX + path, route, methods=["POST"])
for path, function in POSTS.items():
add_post(path, function)
def register_aiohttp(routes, host=None):
"""Add the same routes to ComfyUI's PromptServer.instance.routes.
The page's files are served from ui/dist by a route of their own, so they are not in the
folder ComfyUI loads node scripts from (it would run the page's script on its own page).
"""
import asyncio
import mimetypes
from aiohttp import web as aio
host = host or Host()
neural.set_model_dir(host.model_dir())
static = PREFIX + "/static"
dist = os.path.realpath(os.path.join(BASE_DIR, "ui", "dist"))
def reply(answer):
return aio.json_response(answer[1], status=answer[0], headers={"Cache-Control": "no-store"})
async def threaded(function, *args):
return await asyncio.get_running_loop().run_in_executor(None, function, *args)
async def body_of(request):
try:
body = await request.json()
except Exception:
body = None
return body if isinstance(body, dict) else {}
@routes.get(PREFIX + "/ui")
async def page(request):
try:
return aio.Response(text=ui_html(static), content_type="text/html", headers={"Cache-Control": "no-store"})
except (IOError, OSError):
return aio.Response(text=MISSING_PAGE, content_type="text/html", status=500)
@routes.get(static + "/{path:.*}")
async def files(request):
path = os.path.realpath(os.path.join(dist, request.match_info["path"]))
if not path.startswith(dist + os.sep) or not os.path.isfile(path):
return reply((404, {"error": "no such file"}))
kind = mimetypes.guess_type(path)[0] or "application/octet-stream"
if path.endswith(".js"):
kind = "text/javascript" # Windows sometimes has this as text/plain, and a module then will not load
with open(path, "rb") as handle:
return aio.Response(body=handle.read(), content_type=kind, headers={"Cache-Control": "no-cache"})
@routes.get(PREFIX + "/options")
async def options(request):
return reply(await threaded(answer_options, host))
@routes.get(PREFIX + "/font")
async def font(request):
path = font_file(request.query.get("name", ""))
if path is None:
return reply((404, {"error": "unknown font"}))
return aio.FileResponse(path, headers={"Cache-Control": "max-age=86400"})
@routes.post(PREFIX + "/session")
async def upload(request):
data = await request.read()
return reply(await threaded(answer_upload, data, request.query.get("name", "")))
@routes.get(PREFIX + "/image/{session_id}/{which}")
async def image_bytes(request):
session = get_session(request.match_info["session_id"])
which = request.match_info["which"]
if session is None or which not in image_names():
return reply((404, {"error": "unknown image"}))
data = await threaded(session_png, session, which)
return aio.Response(body=data, content_type="image/png", headers={"Cache-Control": "no-store"})
@routes.post(PREFIX + "/blend")
async def blend(request):
return reply(await threaded(answer_blend, await body_of(request), host))
@routes.post(PREFIX + "/save")
async def save(request):
return reply(await threaded(answer_save, await body_of(request), host))
@routes.post(PREFIX + "/batch")
async def batch(request):
return reply(await threaded(answer_batch, await body_of(request), host))
@routes.post(PREFIX + "/models")
async def models(request):
return reply(await threaded(answer_models, await body_of(request), host))
def add_post(path, function):
async def route(request):
return reply(await threaded(function, await body_of(request)))
routes.post(PREFIX + path)(route)
for path, function in POSTS.items():
add_post(path, function)