sd-anatomy-fix / dev /comfy.py
Kazzze's picture
Update to current version
3c9bc24 verified
Raw History Blame Contribute Delete
11 kB
"""A small ComfyUI client for prototype checks: txt2img for test pictures, and the masked
inpaint pass over a draft, done the way WebUI's "only masked" does it (crop around the
mask, work at full size, paste back with a soft edge).
python dev/comfy.py txt2img OUT_DIR --prompt "..." [--seeds 1 2 3] [--size 832 1216]
python dev/comfy.py inpaint DRAFT_DIR --prompt "..." [--strength 0.4 0.5] [--count 4] [--diff]
--diff takes the denoise per pixel from strength.png (Differential Diffusion) instead of
one --strength for the whole mask; results are diff_<n>.png and diffs.png.
DRAFT_DIR holds draft.png and mask.png from dev/bones_demo.py. Results go next to them as
pass_<strength>_<n>.png and passes.png.
"""
import argparse
import io
import json
import os
import sys
import time
import urllib.parse
import urllib.request
import uuid
import cv2
import numpy as np
from PIL import Image
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from anatomy_fix import passes # noqa: E402
URL = "http://127.0.0.1:8198"
CKPT = "nyx_v2.fp16.safetensors"
NEGATIVE = "worst quality, low quality, bad anatomy, bad hands, extra fingers, missing fingers, fused fingers"
def _post(path, data, content_type="application/json"):
req = urllib.request.Request(URL + path, data=data, headers={"Content-Type": content_type})
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read().decode("utf-8"))
def _get(path):
with urllib.request.urlopen(URL + path, timeout=60) as r:
return r.read()
def upload(array, name):
"""Put an RGB or gray array into ComfyUI's input folder; returns the stored name."""
buf = io.BytesIO()
Image.fromarray(array).save(buf, "PNG")
boundary = uuid.uuid4().hex
body = (("--%s\r\nContent-Disposition: form-data; name=\"image\"; filename=\"%s\"\r\n"
"Content-Type: image/png\r\n\r\n" % (boundary, name)).encode("utf-8") + buf.getvalue()
+ ("\r\n--%s\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n--%s--\r\n"
% (boundary, boundary)).encode("utf-8"))
return _post("/upload/image", body, "multipart/form-data; boundary=" + boundary)["name"]
def run(graph):
"""Queue a graph, wait for it, return the images it saved as RGB arrays."""
prompt_id = _post("/prompt", json.dumps({"prompt": graph, "client_id": "anatomy-fix-dev"}).encode("utf-8"))["prompt_id"]
while True:
history = json.loads(_get("/history/" + prompt_id).decode("utf-8"))
if prompt_id in history:
entry = history[prompt_id]
if entry.get("status", {}).get("status_str") == "error":
raise RuntimeError(json.dumps(entry["status"])[:2000])
break
time.sleep(0.5)
out = []
for node in entry["outputs"].values():
for img in node.get("images", []):
query = urllib.parse.urlencode({"filename": img["filename"], "subfolder": img["subfolder"], "type": img["type"]})
out.append(np.asarray(Image.open(io.BytesIO(_get("/view?" + query))).convert("RGB")))
return out
def _base(prompt, negative, seed, steps, cfg, denoise, latent):
return {
"1": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": CKPT}},
"2": {"class_type": "CLIPTextEncode", "inputs": {"text": prompt, "clip": ["1", 1]}},
"3": {"class_type": "CLIPTextEncode", "inputs": {"text": negative, "clip": ["1", 1]}},
"9": {"class_type": "KSampler", "inputs": {"model": ["1", 0], "positive": ["2", 0], "negative": ["3", 0],
"latent_image": latent, "seed": seed, "steps": steps, "cfg": cfg,
"sampler_name": "euler_ancestral", "scheduler": "normal",
"denoise": denoise}},
"10": {"class_type": "VAEDecode", "inputs": {"samples": ["9", 0], "vae": ["1", 2]}},
"11": {"class_type": "SaveImage", "inputs": {"images": ["10", 0], "filename_prefix": "anatomyfix"}},
}
def txt2img(prompt, negative, seed, width, height, steps=28, cfg=5.0):
graph = _base(prompt, negative, seed, steps, cfg, 1.0, ["4", 0])
graph["4"] = {"class_type": "EmptyLatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}}
return run(graph)[0]
UNION_TYPES = {"depth": "depth", "skeleton": "openpose", "outline": "canny/lineart/anime_lineart/mlsd"}
def inpaint(draft, mask, prompt, negative, strength, seed, side=1024, pad=48, blur=6, steps=28, cfg=5.0,
levels=None, guide=None):
"""levels: a float map of the denoise each pixel may take (strength.png). With it the
pass runs through Differential Diffusion at the map's highest value, and `strength`
is ignored. guide: a passes.Guide, applied with ControlNetApplyAdvanced; a union model
(its name says "union" or "promax") is told which kind of guide it gets."""
crop, crop_mask, box = passes.crop(draft, mask, side, pad, blur)
if levels is not None:
# The map, scaled so its top is 1, is the mask Differential Diffusion reads.
strength = float(levels.max())
x0, y0, size = box
given = cv2.resize((levels / max(strength, 1e-6))[y0:y0 + size, x0:x0 + size], (side, side),
interpolation=cv2.INTER_LINEAR)
crop_mask = (np.clip(given, 0, 1) * 255).astype(np.uint8)
name_img = upload(crop, "af_crop.png")
name_mask = upload(crop_mask, "af_mask.png")
graph = _base(prompt, negative, seed, steps, cfg, strength, ["7", 0])
if levels is not None:
graph["8"] = {"class_type": "DifferentialDiffusion", "inputs": {"model": ["1", 0]}}
graph["9"]["inputs"]["model"] = ["8", 0]
graph["4"] = {"class_type": "LoadImage", "inputs": {"image": name_img}}
graph["5"] = {"class_type": "LoadImageMask", "inputs": {"image": name_mask, "channel": "red"}}
graph["6"] = {"class_type": "VAEEncode", "inputs": {"pixels": ["4", 0], "vae": ["1", 2]}}
graph["7"] = {"class_type": "SetLatentNoiseMask", "inputs": {"samples": ["6", 0], "mask": ["5", 0]}}
if guide is not None:
x0, y0, size = box
piece = cv2.resize(guide.image[y0:y0 + size, x0:x0 + size], (side, side), interpolation=cv2.INTER_LINEAR)
graph["20"] = {"class_type": "LoadImage", "inputs": {"image": upload(piece, "af_guide.png")}}
graph["21"] = {"class_type": "ControlNetLoader", "inputs": {"control_net_name": guide.model}}
net = ["21", 0]
name = guide.model.lower()
if "union" in name or "promax" in name:
graph["22"] = {"class_type": "SetUnionControlNetType",
"inputs": {"control_net": net, "type": UNION_TYPES[guide.kind]}}
net = ["22", 0]
graph["23"] = {"class_type": "ControlNetApplyAdvanced",
"inputs": {"positive": ["2", 0], "negative": ["3", 0], "control_net": net, "image": ["20", 0],
"strength": guide.weight, "start_percent": 0.0, "end_percent": guide.end,
"vae": ["1", 2]}}
graph["9"]["inputs"]["positive"] = ["23", 0]
graph["9"]["inputs"]["negative"] = ["23", 1]
result = run(graph)[0]
return passes.paste(draft, result, mask, box, blur)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("mode", choices=["txt2img", "inpaint"])
parser.add_argument("folder")
parser.add_argument("--prompt", required=True)
parser.add_argument("--negative", default=NEGATIVE)
parser.add_argument("--seeds", type=int, nargs="+", default=[1])
parser.add_argument("--size", type=int, nargs=2, default=[832, 1216])
parser.add_argument("--strength", type=float, nargs="+", default=[0.4, 0.5])
parser.add_argument("--count", type=int, default=4)
parser.add_argument("--diff", action="store_true", help="per-pixel denoise from strength.png")
parser.add_argument("--erase-prompt", default=None,
help="passes as anatomy_fix.passes plans them from strength.png and erased.png: the "
"erased area first, with this prompt (the background, no hands); then the rest "
"with --prompt")
args = parser.parse_args()
if not os.path.isdir(args.folder):
os.makedirs(args.folder)
if args.mode == "txt2img":
for seed in args.seeds:
image = txt2img(args.prompt, args.negative, seed, args.size[0], args.size[1])
Image.fromarray(image).save(os.path.join(args.folder, "gen_%d.png" % seed))
print("gen_%d.png" % seed)
return
draft = np.asarray(Image.open(os.path.join(args.folder, "draft.png")).convert("RGB"))
mask = np.asarray(Image.open(os.path.join(args.folder, "mask.png")).convert("L")) > 127
if args.erase_prompt is not None:
levels = np.asarray(Image.open(os.path.join(args.folder, "strength.png")).convert("L")).astype(np.float32) / 255.0
erased_path = os.path.join(args.folder, "erased.png")
erased = (np.asarray(Image.open(erased_path).convert("L")) > 127) if os.path.exists(erased_path) else None
plan = passes.plan(levels, erased)
print(plan)
row = []
for n in range(args.count):
image = draft
for one in plan:
prompt = args.erase_prompt if one.role == "background" else args.prompt
image = inpaint(image, one.area, prompt, passes.negative_for(one, args.negative), one.strength,
args.seeds[0] + n)
Image.fromarray(image).save(os.path.join(args.folder, "two_%d.png" % n))
row.append(image)
print("two_%d.png" % n)
Image.fromarray(np.concatenate(row, axis=1)).save(os.path.join(args.folder, "twos.png"))
return
levels = None
if args.diff:
levels = np.asarray(Image.open(os.path.join(args.folder, "strength.png")).convert("L")).astype(np.float32) / 255.0
mask = mask | (levels > 0.02)
rows = []
for strength in ([0.0] if args.diff else args.strength):
row = []
for n in range(args.count):
image = inpaint(draft, mask, args.prompt, args.negative, strength, args.seeds[0] + n, levels=levels)
name = ("diff_%d.png" % n) if args.diff else ("pass_%.2f_%d.png" % (strength, n))
Image.fromarray(image).save(os.path.join(args.folder, name))
row.append(image)
print(name)
rows.append(np.concatenate(row, axis=1))
Image.fromarray(np.concatenate(rows, axis=0)).save(os.path.join(args.folder, "diffs.png" if args.diff else "passes.png"))
if __name__ == "__main__":
main()