nyxxworks / scripts /nyxxworks_script.py
Kazzze's picture
Update to current version
e94c49d verified
Raw History Blame Contribute Delete
43.7 kB
"""A1111 / Forge / reForge.
NyxxWorks is a page of its own (ui/), served by nyxxworks/web.py. This script gives the core
what only the host can do, the model pass, and adds the routes when the host starts. It makes
no Gradio parts. The button on the host page that opens NyxxWorks is javascript/nyxxworks.js.
Nothing here may stop the host from starting: if anything fails, the host's console says so
and the host goes on without NyxxWorks.
"""
import os
import sys
import traceback
try:
from modules import processing, script_callbacks, scripts, sd_samplers, shared
_BASE = scripts.basedir()
if _BASE not in sys.path:
sys.path.append(_BASE)
# The host runs this file again on "Reload UI" but keeps imported packages. Drop ours, so a
# reload also picks up changes in nyxxworks/ without restarting the process.
for _name in [n for n in sys.modules if n == "nyxxworks" or n.startswith("nyxxworks.")]:
del sys.modules[_name]
import numpy as np # noqa: E402
from PIL import Image # noqa: E402
from nyxxworks import references as references_core # noqa: E402
from nyxxworks import shared as shared_files # noqa: E402
from nyxxworks import web # noqa: E402
from nyxxworks.host import Host # noqa: E402
from nyxxworks.tools.anatomy import passes as anatomy_passes # noqa: E402
from nyxxworks.tools.anatomy import web as anatomy_web # noqa: E402
from nyxxworks.tools.textfix import blend_mask as textfix_mask # noqa: E402
from nyxxworks.tools.textfix import web as textfix_web # noqa: E402
class WebUIHost(Host):
name = "a1111"
def model(self):
return str(getattr(shared.opts, "sd_model_checkpoint", "") or "")
def samplers(self):
try:
return [sampler.name for sampler in sd_samplers.visible_samplers()]
except Exception:
return [sampler.name for sampler in getattr(sd_samplers, "samplers", [])]
def schedulers(self):
try:
from modules import sd_schedulers
return [scheduler.label for scheduler in sd_schedulers.schedulers]
except Exception:
return [] # an A1111 older than 1.9 has no schedule types
def _ui_defaults(self):
# The defaults the host's page was saved with (--ui-config-file, ui-config.json).
from nyxxworks import a1111_config
return a1111_config.read(getattr(shared.cmd_opts, "ui_config_file", "") or "ui-config.json")
def finish_defaults(self):
# Finishing starts from the hires fix of the txt2img page as saved.
from nyxxworks import a1111_config
return a1111_config.finish_defaults(self._ui_defaults())
def detail_tabs(self):
# Going over the details follows the ADetailer tabs as saved, when there are some.
from nyxxworks import a1111_config
most = shared.opts.data.get("ad_max_models", 4) if hasattr(shared.opts, "data") else 4
return a1111_config.detail_tabs(self._ui_defaults(), most)
def can_open_folder(self):
# The host hides its own folder buttons when started with --hide-ui-dir-config
# (modules/ui_common.py); NyxxWorks follows it.
return not getattr(shared.cmd_opts, "hide_ui_dir_config", False)
def names(self):
# The host's own lists say what its samplers and schedules are underneath: a
# sampler's k-diffusion function, a schedule's short name. ComfyUI calls them by those.
try:
from modules import sd_samplers_kdiffusion, sd_schedulers
from nyxxworks import recipes
return recipes.same_names([(entry[0], entry[1]) for entry in sd_samplers_kdiffusion.samplers_k_diffusion],
[(entry.label, entry.name) for entry in sd_schedulers.schedulers])
except Exception:
return {}
def models(self):
# The host lists every model file under its checkpoints folder, also the ones it
# cannot load: the diffusion models other programs keep there (models loaded in
# parts, video models). Only what can be a checkpoint is offered.
try:
from modules import sd_models
return sorted((info.title for info in sd_models.checkpoints_list.values()
if shared_files.is_checkpoint(getattr(info, "filename", "") or "")), key=str.lower)
except Exception:
return []
def loras(self):
# The host's built-in Lora extension is the module `networks`; it is there once the
# host has loaded its scripts. Without it there are simply no names to offer.
networks = sys.modules.get("networks")
try:
return sorted(networks.available_networks.keys(), key=str.lower) if networks else []
except Exception:
return []
def upscalers(self):
try:
return [upscaler.name for upscaler in shared.sd_upscalers if upscaler.name != "None"]
except Exception:
return []
def detectors(self):
# Where the ADetailer extension keeps its models: models/adetailer, then the models
# it brings itself (face_yolov8s.pt and the like), which it has fetched into the
# Hugging Face cache, Bingsu/adetailer. Only what is on disk; nothing is fetched.
import glob
found, names = [], set()
folders = []
try:
from modules import paths
folders.append(os.path.join(paths.models_path, "adetailer"))
caches = [os.path.join(paths.models_path, "diffusers")]
except Exception:
caches = []
try:
from huggingface_hub import constants
caches.append(constants.HF_HUB_CACHE)
except Exception:
pass
for cache in caches:
folders.extend(sorted(glob.glob(os.path.join(cache, "models--Bingsu--adetailer", "snapshots", "*"))))
for folder in folders:
try:
files = sorted(os.listdir(folder))
except OSError:
continue
for name in files:
path = os.path.join(folder, name)
# A file of the same name found earlier is the one in use: the user's own first.
if name.lower() not in names and os.path.isfile(path):
names.add(name.lower())
found.append(path)
return found
def style_files(self):
# Where Style Grid looks, apart from its own folders: the host's styles files,
# then every CSV beside them in the host's folder, where downloaded packs are put.
found = []
try:
found.extend(str(path) for path in shared.prompt_styles.all_styles_files)
except Exception:
pass
try:
root = os.getcwd()
found.extend(os.path.join(root, name) for name in sorted(os.listdir(root)) if name.lower().endswith(".csv"))
except OSError:
pass
return found
# How a reference picture is followed with what Forge and reForge have built in. A pose
# needs a ControlNet model for poses. The other two need none: they are the host's
# "reference_only" preprocessor, which reads the picture through the checkpoint itself,
# at two settings of its "style fidelity" (threshold_a). Tried on reForge with an SDXL
# checkpoint: at 0.5 the one in the picture comes over and the prompt keeps the scene;
# at 1.0 the palette and the linework come over too, and more of the picture with them.
# "reference_adain" is not used: there it changed nothing at all.
#
# A style apart from what is in the picture needs an IP-Adapter: the picture is read by
# an image encoder and handed to the model's cross-attention, and of the 11 groups of
# attention layers of an SDXL model only those that carry the style get it (the host's
# own "Style" preset of block weights). That is used when the host has an adapter
# model, its preprocessor and the encoder file that preprocessor reads; nothing is
# downloaded here. Without them a style is followed with reference_only, as before.
# Which adapter: references.style_adapter(). Tried on reForge with a NoobAI-line
# checkpoint and NOOB-IPA-MARK1: the palette and the light of the reference come over
# more than with reference_only, and its colors still reach the clothes.
POSE_MODULES = ("dw_openpose_full", "openpose_full", "openpose")
LOOK_MODULE = "reference_only"
LOOK_FIDELITY = {"character": 0.5, "style": 1.0}
STYLE_BLOCKS = "0, 0, 1, 0, 0.0, 0, 1, 0, 0, 0, 0" # the host's own "Style" preset of the unit's block weights
@staticmethod
def _controlnet_script():
"""The ControlNet script of the txt2img tab: built into Forge and reForge, an
extension in A1111. None when it is not there."""
try:
for script in scripts.scripts_txt2img.alwayson_scripts:
if script.title() == "ControlNet":
return script
except Exception:
pass
return None
def _pose_model(self):
"""(preprocessor, model) to follow a pose with, or None. A model made for poses
alone is taken before one that does many things."""
try:
from lib_controlnet import global_state
global_state.update_controlnet_filenames()
modules = global_state.get_all_preprocessor_names()
models = [name for name in global_state.get_all_controlnet_names() if name and name != "None"]
except Exception:
return None
module = next((name for name in self.POSE_MODULES if name in modules), None)
model = next((name for name in models if "openpose" in name.lower()), None)
return (module, model) if module and model else None
def _style_model(self):
"""(preprocessor, model) of the IP-Adapter to follow a style with, or None: with an
SDXL checkpoint loaded, an adapter whose preprocessor and encoder file are there."""
try:
from lib_controlnet import global_state
from modules_forge.shared import preprocessor_dir
global_state.update_controlnet_filenames()
modules = global_state.get_all_preprocessor_names()
models = [name for name in global_state.get_all_controlnet_names() if name and name != "None"]
except Exception:
return None
if not getattr(shared.sd_model, "is_sdxl", False):
return None
usable = [key for key, (module, encoder) in references_core.ENCODERS.items()
if module in modules and os.path.isfile(os.path.join(preprocessor_dir, encoder))]
found = references_core.style_adapter(models, usable)
return (references_core.ENCODERS[found["encoder"]][0], found["model"]) if found else None
def references(self, model=None):
if self._controlnet_script() is None:
return []
ways = []
pose = self._pose_model()
if pose is not None:
ways.append({"kind": "pose", "with": "%s with %s" % pose})
try:
from lib_controlnet import global_state
modules = global_state.get_all_preprocessor_names()
except Exception:
modules = []
adapter = self._style_model()
if self.LOOK_MODULE in modules:
for kind in ("character",) if adapter else ("character", "style"):
ways.append({"kind": kind, "with": "%s, style fidelity %g" % (self.LOOK_MODULE, self.LOOK_FIDELITY[kind])})
if adapter:
ways.append({"kind": "style", "with": "IP-Adapter %s, the style layers only" % adapter[1]})
return ways
def _regions_runner(self, given, runner=None):
"""A runner with a script of NyxxWorks' own: before sampling it puts the regions'
attention patches on a clone of the UNet (nyxxworks.regions). Given a runner (the
one of a pose reference), the script goes into it after what is there. Says
(runner, args, done): done is filled when the patches were put on, as the host
swallows a script's errors."""
from nyxxworks import regions
done = []
def encode(p, text):
if not text.strip():
return None
made = p.sd_model.get_learned_conditioning([text])
return made["crossattn"] if isinstance(made, dict) else made
class Regional(scripts.Script):
filename = "nyxxworks-regions"
def title(self):
return "NyxxWorks regions"
def show(self, is_img2img):
return scripts.AlwaysVisible
def process_before_every_sampling(self, p, *args, **kwargs):
unet = p.sd_model.forge_objects.unet.clone()
masks = regions.split(max(1, p.width // 8), max(1, p.height // 8), given["ratios"], given["across"])
positive = [encode(p, text) for text in given["prompts"]]
if any(one is None for one in positive):
raise RuntimeError("A region has no words.")
negative = [encode(p, text) for text in given["negatives"]]
until = None
if given["bound"] > 0 and given["until"] < 1.0:
until = float(unet.model.model_sampling.percent_to_sigma(given["until"]))
made = regions.Regions(masks, positive, negative, strength=given["strength"], bound=given["bound"], bound_until=until)
made.apply(unet, unet.model.diffusion_model)
p.sd_model.forge_objects.unet = unet
done.append(made)
script = Regional()
script.args_from, script.args_to = 0, 0
if runner is None:
runner = scripts.ScriptRunner()
runner.alwayson_scripts, runner.scripts = [], []
runner.alwayson_scripts = list(runner.alwayson_scripts) + [script]
runner.scripts = list(runner.scripts) + [script]
return runner, [], done
def _runner_for(self, request):
"""The host scripts of a pass: ControlNet for reference pictures, NyxxWorks' own for
regions, both for regions with a pose reference. Says (runner, args, checks): each
check is a list that must not be empty after the pass, with what it means."""
references = request.get("_references") or []
given = request.get("regions")
if given and any(one["kind"] != "pose" for one in references):
# A character or a style reference works through the same cross-attention the
# regions take over: one would undo the other.
raise RuntimeError("Regions go together with a pose reference only, not with a character or a style reference.")
runner, units, checks = None, None, []
if references:
runner, units, followed = self._reference_runner(references)
checks.append((followed, "ControlNet did not take part in the pass; see the host's console."))
if given:
runner, _, done = self._regions_runner(given, runner)
checks.append((done, "The regions did not take part in the pass; see the host's console."))
return runner, units, checks
@staticmethod
def _checked(checks):
for done, what in checks:
if not done:
raise RuntimeError(what)
def _reference_runner(self, references):
"""A script runner with the host's ControlNet alone, one unit for each reference.
Returns (runner, script_args, done): `done` gets an entry when ControlNet has handed
the references to the sampler."""
import copy
from lib_controlnet.external_code import ControlNetUnit
found = self._controlnet_script()
if found is None:
raise RuntimeError("The host's ControlNet is not loaded: take the reference cards out of the request.")
units = []
adapter = self._style_model()
for reference in references:
picture = np.ascontiguousarray(np.asarray(reference["image"].convert("RGB")))
if reference["kind"] == "style" and adapter:
units.append(ControlNetUnit(enabled=True, module=adapter[0], model=adapter[1],
weight=float(reference["weight"]),
image={"image": picture, "mask": np.zeros_like(picture)},
guidance_start=0.0, guidance_end=1.0, ipa_block_weight=self.STYLE_BLOCKS))
continue
if reference["kind"] == "pose":
pose = self._pose_model()
if pose is None:
raise RuntimeError("The host has no ControlNet model for poses any more.")
module, model = pose
fidelity = -1 # not a setting of a pose
else:
module, model = self.LOOK_MODULE, "None"
fidelity = self.LOOK_FIDELITY[reference["kind"]]
units.append(ControlNetUnit(enabled=True, module=module, model=model, weight=float(reference["weight"]),
image={"image": picture, "mask": np.zeros_like(picture)}, threshold_a=fidelity,
guidance_start=0.0, guidance_end=1.0, pixel_perfect=True))
net = copy.copy(found) # its args_from and args_to belong to the page
net.args_from, net.args_to = 0, len(units)
done = []
def before_sampling(p, *given, **kwargs):
type(found).process_before_every_sampling(net, p, *given, **kwargs)
done.append(True)
net.process_before_every_sampling = before_sampling
runner = scripts.ScriptRunner()
runner.alwayson_scripts = [net]
runner.scripts = [net]
return runner, units, done
def _pass(self, p, request, job, runner=None, args=None):
"""Run one model pass and say (processed, interrupted). It waits its turn in the
host's queue like a generation of the host's own page would; the caller holds no lock.
runner, args: the host scripts that take part and what they are given; none by default."""
from modules.call_queue import queue_lock
with queue_lock:
if request.get("scheduler"):
p.scheduler = request["scheduler"]
if request.get("model") and request["model"] != self.model():
# The checkpoint is changed for good, as picking it on the host page would:
# changing it back after every picture would load it twice per picture.
p.override_settings = {"sd_model_checkpoint": request["model"]}
p.override_settings_restore_afterwards = False
# The scripts of the host page (ADetailer, style pickers, letterers) take no
# part: NyxxWorks does those things at its own stations. reForge reads
# p.scripts, so it gets a runner with nothing in it rather than None.
# A request with reference cards brings a runner with the host's ControlNet alone.
p.scripts = runner if runner is not None else scripts.ScriptRunner()
p.script_args = list(args or [])
shared.state.begin(job=job)
try:
processed = processing.process_images(p)
interrupted = bool(getattr(shared.state, "interrupted", False))
finally:
shared.state.end()
p.close()
return processed, interrupted
def generate(self, request, count, on_image, stopped):
"""Text to image, one picture at a time."""
strength = request.get("variation")
for index in range(count):
if stopped():
return
params = dict(request)
if strength is None:
params["seed"] = int(request["seed"]) + index
else:
params["subseed"] = int(request["subseed"]) + index
p = processing.StableDiffusionProcessingTxt2Img(
sd_model=shared.sd_model,
outpath_samples=shared.opts.outdir_samples or shared.opts.outdir_txt2img_samples,
prompt=request["prompt"],
negative_prompt=request["negative"],
seed=int(params["seed"]),
subseed=int(params.get("subseed", -1)),
subseed_strength=float(strength or 0.0),
steps=int(request["steps"]),
cfg_scale=float(request["cfg"]),
sampler_name=request["sampler"],
width=int(request["width"]),
height=int(request["height"]),
batch_size=1,
n_iter=1,
do_not_save_samples=True,
do_not_save_grid=True,
)
runner, units, checks = self._runner_for(request)
processed, interrupted = self._pass(p, request, "nyxxworks", runner, units)
if interrupted or stopped():
return # a picture given up half-way is not a picture
# A picture meant to follow a reference or regions must not pass for one that did.
self._checked(checks)
if not processed.images:
raise RuntimeError("The model pass gave no image.")
infotext = processed.infotexts[0] if getattr(processed, "infotexts", None) else ""
params["model"] = self.model()
on_image(processed.images[0], params, infotext)
def finish(self, image, params, how):
"""Enlarge the picture with the chosen upscaler, then image to image over the whole
of it with the prompt and settings it was made with."""
from modules import images
width = max(64, int(round(image.width * how["scale"] / 8.0)) * 8)
height = max(64, int(round(image.height * how["scale"] / 8.0)) * 8)
enlarged = images.resize_image(0, image, width, height, upscaler_name=how.get("upscaler") or None)
seed = params.get("seed")
# What the hires fix of the host's page sets for its pass (how["pass"]), over what
# the picture was made with.
done = how.get("pass") or {}
p = processing.StableDiffusionProcessingImg2Img(
sd_model=shared.sd_model,
outpath_samples=shared.opts.outdir_samples or shared.opts.outdir_img2img_samples,
prompt=str(params.get("prompt") or ""),
negative_prompt=str(params.get("negative") or ""),
init_images=[enlarged],
resize_mode=0,
denoising_strength=float(how["denoise"]),
seed=int(seed) if isinstance(seed, int) and seed >= 0 else -1,
steps=int(done.get("steps") or params.get("steps") or 25),
cfg_scale=float(done.get("cfg") or params.get("cfg") or 5.0),
sampler_name=str(done.get("sampler") or params.get("sampler") or "Euler a"),
width=width,
height=height,
batch_size=1,
n_iter=1,
do_not_save_samples=True,
do_not_save_grid=True,
)
if done.get("steps"):
# Hires steps are the steps the pass runs, whatever the strength; an img2img
# pass otherwise runs only the strength's share of its steps.
p.override_settings = {"img2img_fix_steps": True}
p.override_settings_restore_afterwards = True
# A picture made with regions is finished with them: the base prompt alone would
# tell the model nothing of who stands where. (References are not used again here.)
runner, units, checks = self._runner_for({"regions": params["regions"]}) if params.get("regions") else (None, None, [])
# The checkpoint stays the one that is loaded: the name a picture carries is the
# host's own wording of it, not always one the host can load by.
processed, _ = self._pass(p, {"scheduler": done.get("scheduler") or params.get("scheduler")}, "nyxxworks finish", runner, units)
self._checked(checks)
if not processed.images:
raise RuntimeError("The model pass gave no image.")
infotext = processed.infotexts[0] if getattr(processed, "infotexts", None) else ""
return processed.images[0], infotext
def repaint(self, image, mask, params, how):
"""A masked inpaint of the spot, "only masked": the spot with some of what is around
it is repainted large and put back, so a small spot gets the model's full attention.
It starts from what is there; at full strength nothing of it is left."""
# A step of detailing may bring settings of its own (ADetailer's tab: detail.repaint_how);
# the Fix station's repaint brings none and gets the numbers below.
size = how.get("size") or [1024, 1024]
p = processing.StableDiffusionProcessingImg2Img(
sd_model=shared.sd_model,
outpath_samples=shared.opts.outdir_samples or shared.opts.outdir_img2img_samples,
prompt=how["prompt"],
negative_prompt=str(how.get("negative") or params.get("negative") or ""),
init_images=[image],
mask=mask,
mask_blur=int(how.get("blur", 8)),
inpainting_fill=1,
inpaint_full_res=True,
inpaint_full_res_padding=int(how.get("padding", 64)),
denoising_strength=float(how["strength"]),
seed=int(how["seed"]),
steps=int(how.get("steps") or params.get("steps") or 25),
cfg_scale=float(how.get("cfg") or params.get("cfg") or 5.0),
sampler_name=str(how.get("sampler") or params.get("sampler") or "Euler a"),
width=max(64, int(size[0]) // 8 * 8),
height=max(64, int(size[1]) // 8 * 8),
batch_size=1,
n_iter=1,
do_not_save_samples=True,
do_not_save_grid=True,
)
processed, _ = self._pass(p, {"scheduler": how.get("scheduler") or params.get("scheduler")}, "nyxxworks repaint")
if not processed.images:
raise RuntimeError("The model pass gave no image.")
out = processed.images[0].convert("RGB")
if out.size != image.size:
out = out.resize(image.size, Image.LANCZOS)
infotext = processed.infotexts[0] if getattr(processed, "infotexts", None) else ""
return out, infotext
def progress(self):
state = shared.state
steps = getattr(state, "sampling_steps", 0) or 0
return min(1.0, getattr(state, "sampling_step", 0) / float(steps)) if steps else 0.0
def interrupt(self):
shared.state.interrupt()
def anatomy(self):
return AnatomyHost()
def text(self):
return TextHost()
class TextHost(textfix_web.Host):
"""What the text tool needs of the A1111 family: its blending pass over the new
letters, guided by their edges with the host's ControlNet when asked. Taken from
scripts/text_fix_script.py of sd-text-fix; see SOURCES.md."""
name = "a1111"
def can_blend(self):
return True
def samplers(self):
try:
return [sampler.name for sampler in sd_samplers.samplers_for_img2img]
except Exception:
return []
@staticmethod
def controlnet_script():
"""The ControlNet script of the img2img tab: built into Forge and reForge, an
extension in AUTOMATIC1111. None when there is none."""
runner = getattr(scripts, "scripts_img2img", None)
for script in getattr(runner, "alwayson_scripts", []) or []:
try:
if script.title() == "ControlNet":
return script
except Exception:
continue
return None
def controlnets(self):
if self.controlnet_script() is None:
return []
names = []
try: # Forge and reForge
from lib_controlnet import global_state
names = list(global_state.get_all_controlnet_names())
except ImportError:
try: # the AUTOMATIC1111 extension
from scripts import global_state
names = list(getattr(global_state, "cn_models", {}).keys())
except ImportError:
names = []
return [name for name in names if name and name != "None"]
def guide(self, p, image, model):
"""Guide the pass by the edges of the drawn letters: a ControlNet unit with the canny
preprocessor over the image as drawn, so the model may repaint the surface but keeps
the letters' shapes. Only the ControlNet script runs alongside the pass."""
import base64
import io
script = self.controlnet_script()
if script is None:
raise RuntimeError("ControlNet is not installed: turn off the guide by the letters' edges.")
buffer = io.BytesIO()
image.save(buffer, "PNG")
unit = {
"enabled": True, "module": "canny", "model": model["guide"], "weight": float(model["guideWeight"]),
"image": "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode("ascii"),
"resize_mode": "Crop and Resize", "processor_res": int(model["resolution"]), "threshold_a": 100,
"threshold_b": 200, "guidance_start": 0.0, "guidance_end": 1.0, "pixel_perfect": True,
"control_mode": "Balanced",
}
count = script.args_to - script.args_from
units = [unit] + [{"enabled": False} for _ in range(max(0, count - 1))]
runner = scripts.ScriptRunner()
runner.scripts = [script]
runner.alwayson_scripts = [script]
p.scripts = runner
p.script_args = [None] * script.args_from + units
def model_dir(self):
# The same folder as sd-text-fix uses: the detector's models are downloaded once
# for both.
from modules import paths
return os.path.join(paths.models_path, "text_fix")
def blend(self, image, selection, model):
"""A light inpainting pass over the new text: the model adds the light, the fabric
and the soft edges, the letters keep their shape. Waits for the host's queue."""
from modules.call_queue import queue_lock
with queue_lock:
shared.state.begin(job="nyxxworks text")
try:
return self.pass_now(image, selection, model)
finally:
shared.state.end()
def pass_now(self, image, selection, model):
mask = Image.fromarray(textfix_mask(image.size[::-1], selection).astype(np.uint8) * 255, "L")
p = processing.StableDiffusionProcessingImg2Img(
sd_model=shared.sd_model,
outpath_samples=shared.opts.outdir_samples or shared.opts.outdir_img2img_samples,
prompt=model.get("prompt") or "",
negative_prompt=model.get("negative") or "",
init_images=[image],
mask=mask,
mask_blur=int(max(2, round(0.3 * selection.height()))),
inpainting_fill=1, # start from what is there: the letters just drawn
inpaint_full_res=True,
inpaint_full_res_padding=int(model["padding"]),
denoising_strength=float(model["strength"]),
steps=int(model["steps"]),
cfg_scale=float(model["cfg"]),
sampler_name=model["sampler"],
width=int(model["resolution"]),
height=int(model["resolution"]),
seed=int(model.get("seed", -1)),
do_not_save_samples=True,
do_not_save_grid=True,
)
# No scripts of the page take part in this pass, but ControlNet when the pass is
# guided by the letters. reForge still reads p.scripts, so it gets a runner with
# nothing in it rather than None.
p.scripts = scripts.ScriptRunner()
p.script_args = []
if model.get("guide"):
self.guide(p, image, model)
try:
processed = processing.process_images(p)
finally:
p.close()
return processed.images[0] if processed.images else image
# The host's soft inpainting (extensions-builtin/soft-inpainting in A1111 1.8+, Forge and
# reForge), and its arguments: enabled, then its own defaults for schedule bias, preservation
# strength, transition contrast boost, mask influence, difference threshold and difference
# contrast.
SOFT_TITLE = "Soft Inpainting"
SOFT_ARGS = [True, 1.0, 0.5, 4.0, 0.0, 0.5, 2.0]
class AnatomyHost(anatomy_web.Host):
"""What the anatomy tool needs of the A1111 family: its masked model pass, with the
host's ControlNet for a guide and its soft inpainting for soft edges. Taken from
scripts/anatomy_fix_script.py of sd-anatomy-fix; see SOURCES.md."""
name = "a1111"
def can_inpaint(self):
return True
def samplers(self):
try:
return [sampler.name for sampler in sd_samplers.samplers_for_img2img]
except Exception:
return []
def controlnets(self):
"""The ControlNet models the host's built-in ControlNet knows; none without it."""
try:
from lib_controlnet import global_state
global_state.update_controlnet_filenames()
return [name for name in global_state.get_all_controlnet_names() if name and name != "None"]
except Exception:
return []
@staticmethod
def _host_script(title):
"""The page's img2img script of that title, or None."""
for script in scripts.scripts_img2img.alwayson_scripts:
if script.title() == title:
return script
return None
def can_soften(self):
return self._host_script(SOFT_TITLE) is not None
def _runner(self, guide, soft):
"""A script runner with only the host scripts this pass needs: its ControlNet for a
guide, its soft inpainting for soft edges. The other scripts of the page (ADetailer
and the like) must not take part in this pass, so the page's own runner is not used.
Copies of the scripts are taken: their args_from and args_to belong to the page.
Returns (runner, script_args, done): `done` gets an entry when ControlNet has handed
the guide to the sampler."""
import copy
runner = scripts.ScriptRunner()
mine, args, done = [], [], []
if guide is not None:
found = self._host_script("ControlNet")
if found is None:
raise RuntimeError("The host's ControlNet is not loaded: the Guide needs it.")
net = copy.copy(found)
net.args_from, net.args_to = len(args), len(args) + 1
args.append(self._controlnet_unit(guide))
# The host reports a failing script to its console and goes on without it. The
# step that hands the guide to the sampler is wrapped, so it is known whether it
# got done.
def before_sampling(p, *given, **kwargs):
type(found).process_before_every_sampling(net, p, *given, **kwargs)
done.append(True)
net.process_before_every_sampling = before_sampling
mine.append(net)
if soft:
found = self._host_script(SOFT_TITLE)
if found is None:
raise RuntimeError("The host has no soft inpainting: turn Soft edges off.")
# A fresh one: it keeps the masks and overlays of its pass on itself.
fresh = type(found)()
fresh.filename, fresh.alwayson = found.filename, True
fresh.args_from, fresh.args_to = len(args), len(args) + len(SOFT_ARGS)
args.extend(SOFT_ARGS)
mine.append(fresh)
runner.alwayson_scripts = mine
runner.scripts = list(mine)
return runner, args, done
@staticmethod
def _controlnet_unit(guide):
from lib_controlnet.external_code import ControlNetUnit
# The guide is the size of the picture; the "None" preprocessor crops it with the
# inpainting mask, as the picture is cropped for "only masked".
picture = np.ascontiguousarray(guide.image)
return ControlNetUnit(enabled=True, module="None", model=guide.model, weight=float(guide.weight),
image={"image": picture, "mask": np.zeros_like(picture)},
guidance_start=0.0, guidance_end=float(guide.end), pixel_perfect=False)
def inpaint(self, image, area, prompt, negative, strength, seed, model, guide=None):
"""One masked inpaint of the area, "only masked" at the chosen resolution, with the
loaded checkpoint. It waits its turn in the host's queue like a generation would.
With a guide, the host's ControlNet follows it. With the strength map in
`model["levels"]`, the mask is the soft mask of the pass and the host's soft inpainting
repaints each pixel as strongly as it says."""
from modules.call_queue import queue_lock
levels = model.get("levels")
soft = levels is not None
if soft:
given = anatomy_passes.soft_mask(area, levels, strength, float(model["blur"]))
mask = Image.fromarray((given * 255).round().astype(np.uint8), "L")
else:
mask = Image.fromarray(area.astype(np.uint8) * 255, "L")
with queue_lock:
p = processing.StableDiffusionProcessingImg2Img(
sd_model=shared.sd_model,
outpath_samples=shared.opts.outdir_samples or shared.opts.outdir_img2img_samples,
prompt=prompt,
negative_prompt=negative,
init_images=[Image.fromarray(image)],
mask=mask,
mask_blur=int(model["blur"]),
inpainting_fill=1, # start from what is there: the draft
inpaint_full_res=True,
inpaint_full_res_padding=int(model["padding"]),
denoising_strength=float(strength),
steps=int(model["steps"]),
cfg_scale=float(model["cfg"]),
sampler_name=model["sampler"],
width=int(model["resolution"]),
height=int(model["resolution"]),
seed=int(seed),
do_not_save_samples=True,
do_not_save_grid=True,
)
# Only the scripts this pass needs take part. reForge reads p.scripts, so a pass
# with none gets a runner with nothing in it rather than None.
p.scripts, p.script_args, done = self._runner(guide, soft)
shared.state.begin(job="nyxxworks anatomy")
try:
processed = processing.process_images(p)
finally:
shared.state.end()
p.close()
# A pass meant to follow a guide must not pass for one that did.
if guide is not None and not done:
raise RuntimeError("ControlNet did not take part in the pass; see the host's console.")
if not processed.images:
raise RuntimeError("The model pass gave no image.")
out = processed.images[0].convert("RGB")
if out.size != (image.shape[1], image.shape[0]):
out = out.resize((image.shape[1], image.shape[0]), Image.LANCZOS)
return np.asarray(out)
def _register(_demo, app):
try:
web.register(app, WebUIHost())
except Exception:
traceback.print_exc()
print("NyxxWorks: could not add its routes; the host goes on without it.", file=sys.stderr)
script_callbacks.on_app_started(_register)
except Exception:
traceback.print_exc()
print("NyxxWorks: did not load; the host goes on without it.", file=sys.stderr)