File size: 10,794 Bytes
3c9bc24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""A1111 / Forge / reForge.



The editor is a React page (ui/) shown over the host page; anatomy_fix/web.py serves it and

answers its calls. This script gives web.py what only the host can do (the model pass,

saving an image the way the host saves its own), and makes the one hidden part the page

needs: a button that carries the editor's result into a tab's gallery. The icon under

Generate and the button under the gallery are made by javascript/anatomy_fix.js.

"""
import os
import sys

import gradio as gr
import numpy as np
from PIL import Image

from modules import images, 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 anatomy_fix/ without restarting the process.
for _name in [n for n in sys.modules if n == "anatomy_fix" or n.startswith("anatomy_fix.")]:
    del sys.modules[_name]

from anatomy_fix import passes as P  # noqa: E402
from anatomy_fix import web  # noqa: E402

# 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 WebUIHost(web.Host):
    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 save(self, image, parameters, tab):
        """Save the way the host saves a generation of that tab: its folder, file name pattern,

        numbering and format, with the generation parameters of the source image kept."""
        opts = shared.opts
        folder = getattr(opts, "outdir_samples", "") or getattr(opts, "outdir_%s_samples" % tab, "") \
            or os.path.join("outputs", "%s-images" % tab)
        saved = images.save_image(image, folder, "", info=parameters, extension=getattr(opts, "samples_format", "png"),
                                  suffix="-anatomyfix")
        path = saved[0] if isinstance(saved, (tuple, list)) else saved
        return os.path.abspath(path or folder)

    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 = P.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="anatomy_fix")
            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):
    web.register(app, WebUIHost())


script_callbacks.on_app_started(register)


class AnatomyFixScript(scripts.Script):
    gallery = None
    tab = None
    placed = False

    def title(self):
        return "Anatomy Fix"

    def show(self, is_img2img):
        return scripts.AlwaysVisible

    def ui(self, is_img2img):
        self.tab = "img2img" if is_img2img else "txt2img"
        return []

    def after_component(self, component, **kwargs):
        if self.tab and kwargs.get("elem_id") == self.tab + "_gallery":
            self.gallery = component

    def before_component(self, component, **kwargs):
        # Nothing of this shows on the page. It is the hidden button that carries the
        # editor's result into the tab's gallery; the page script clicks it.
        if not self.tab or self.placed or kwargs.get("elem_id") != "html_info_" + self.tab:
            return
        self.placed = True
        with gr.Row(elem_id="anatomy_fix_bar_" + self.tab, elem_classes=["anatomyfix-hidden"]):
            # The session id comes through _js; the textbox only gives it a slot.
            session = gr.Textbox(visible=False)
            send_button = gr.Button("to gallery", visible=False, elem_id="anatomy_fix_to_gallery_" + self.tab)
        for part in (session, send_button):
            part.do_not_save_to_config = True
        if self.gallery is not None:
            send_button.click(fn=self.to_gallery, inputs=[session], outputs=[self.gallery],
                              _js="function(){ return [window.anatomyFixSession || '']; }", show_progress=False)

    def to_gallery(self, session_id):
        image = web.result_image(session_id)
        return [image] if image is not None else gr.update()