File size: 15,231 Bytes
2a261b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""A1111 / Forge / reForge.



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

answers its calls. This script gives web.py what only the host can do (save an image the

way the host saves its own, run the model pass), 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/text_fix.js.

"""
import base64
import io
import os
import random
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 text_fix/ without restarting the process.
for _name in [n for n in sys.modules if n == "text_fix" or n.startswith("text_fix.")]:
    del sys.modules[_name]

from text_fix import blend_mask, web  # noqa: E402


class WebUIHost(web.Host):
    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."""
        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 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="-textfix")
        path = saved[0] if isinstance(saved, (tuple, list)) else saved
        return os.path.abspath(path or folder)

    def model_dir(self):
        from modules import paths
        return os.path.join(paths.models_path, "text_fix")

    def output_folder(self):
        opts = shared.opts
        return getattr(opts, "outdir_samples", "") or getattr(opts, "outdir_img2img_samples", "") \
            or os.path.join("outputs", "img2img-images")

    def allows_folders(self):
        flags = shared.cmd_opts
        return not (getattr(flags, "listen", False) or getattr(flags, "share", False)
                    or getattr(flags, "server_name", None) or getattr(flags, "ngrok", None))

    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="text_fix")
            try:
                return self.pass_now(image, selection, model)
            finally:
                shared.state.end()

    def pass_now(self, image, selection, model):
        """The pass itself, for a caller that has the model already: a generation of the

        host's own, in the auto mode."""
        mask = Image.fromarray(blend_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


HOST = WebUIHost()
EDITOR_LOOK = "The editor's look"


def register(_demo, app):
    web.register(app, HOST)


script_callbacks.on_app_started(register)


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

    def title(self):
        return "Text Fix"

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

    def ui(self, is_img2img):
        self.tab = "img2img" if is_img2img else "txt2img"
        from modules.ui_components import InputAccordion, ToolButton

        with InputAccordion(False, label="Text Fix: replace the text by itself",
                            elem_id="text_fix_auto_" + self.tab) as enabled:
            lines = gr.Textbox(label="New text", lines=3, elem_id="text_fix_auto_lines_" + self.tab,
                               placeholder="One line for each text found on every image, the most prominent "
                                           "first. An empty line leaves that text as it is; a dash (-) erases it.")
            with gr.Row():
                look = gr.Dropdown(label="Look", choices=self.looks(), value=EDITOR_LOOK,
                                   elem_id="text_fix_auto_look_" + self.tab)
                refresh = ToolButton("\U0001f504", elem_id="text_fix_auto_refresh_" + self.tab,
                                     tooltip="Read the presets saved in the editor again")
                blend = gr.Checkbox(label="Blend in with the model", value=True,
                                    elem_id="text_fix_auto_blend_" + self.tab)
                strength = gr.Slider(label="Denoising strength", minimum=0.05, maximum=0.6, step=0.01, value=0.3,
                                     elem_id="text_fix_auto_strength_" + self.tab)
            keep = gr.Checkbox(label="Keep the image as generated too (in the gallery, and saved as -before-textfix)",
                               value=True,
                               elem_id="text_fix_auto_keep_" + self.tab)
            gr.HTML("<p style='opacity:.7;font-size:.85em;margin:0'>The text is found by looks alone: now and then "
                    "a row of hair, an eye or a seam is taken for text and painted over. Keep the image as "
                    "generated, or check the results.</p>")
            refresh.click(fn=lambda: gr.update(choices=self.looks()), outputs=[look], show_progress=False)
        return [enabled, lines, look, blend, strength, keep]

    @staticmethod
    def looks():
        return [EDITOR_LOOK] + sorted(web.load_presets().keys())

    def postprocess(self, p, processed, enabled=False, lines="", look=None, blend=False, strength=0.3, keep=True):
        """The images as generated go into the gallery too, after the ones the auto mode

        changed, so they are there whether or not the host saves images."""
        kept, self.kept = getattr(self, "kept", []), []
        first = int(getattr(processed, "index_of_first_image", 0) or 0)  # past the grid, when there is one
        for image, index in kept:
            processed.images.append(image)
            infotexts = getattr(processed, "infotexts", None)
            if isinstance(infotexts, list):
                infotexts.append(infotexts[first + index] if first + index < len(infotexts) else "")

    def process(self, p, enabled, lines, look, blend, strength, keep=True):
        self.kept = []
        if enabled and (lines or "").strip():
            p.extra_generation_params["Text Fix"] = True
            p.extra_generation_params["Text Fix lines"] = " | ".join(line.strip() for line in lines.splitlines())

    @staticmethod
    def keep_original(p, image):
        """Save the image as generated, next to the one the auto mode changes, the way the

        host saves an image before its face restoration."""
        if not p.save_samples():
            return
        index = int(getattr(p, "batch_index", 0) or 0)
        try:
            info = processing.create_infotext(p, p.prompts, p.seeds, p.subseeds, index=index,
                                              all_negative_prompts=p.negative_prompts)
        except Exception:
            info = None
        images.save_image(image, p.outpath_samples, "", p.seeds[index], p.prompts[index],
                          shared.opts.samples_format, info=info, p=p, suffix="-before-textfix")

    def postprocess_image(self, p, pp, enabled, lines, look, blend, strength, keep=True):
        """The auto mode: every image of the generation gets the list of replacements, before

        it is saved, and the model pass over the new letters when asked."""
        if not enabled or not (lines or "").strip():
            return
        try:
            original = pp.image
            rgb, done = web.auto_replace(np.asarray(original.convert("RGB")), lines, web.look_named(look))
            if not done:
                print("[Text Fix] no text found to replace on this image")
                return
            if keep:
                self.keep_original(p, original)
                index = int(getattr(p, "batch_index", 0) or 0) + int(getattr(p, "iteration", 0) or 0) * p.batch_size
                self.kept = getattr(self, "kept", []) + [(original, index)]
            image = Image.fromarray(rgb)
            if blend:
                model = dict(web.load_settings()["model"], strength=float(strength),
                             prompt=p.prompt if isinstance(p.prompt, str) else "",
                             negative=p.negative_prompt if isinstance(p.negative_prompt, str) else "")
                model, _ = web.model_prompts(model)
                model["guide"] = model.get("guide") if model.get("guide") in HOST.controlnets() else ""
                for selection in done:
                    # The generation holds the queue already: the pass runs inside it, as
                    # ADetailer's passes do.
                    image = HOST.pass_now(image, selection, dict(model, seed=random.randrange(0, 2 ** 31)))
                    image = image.convert("RGB")
            pp.image = image
        except Exception as error:  # the generation itself must not fail because of this
            print("[Text Fix] the auto mode failed on this image: %r" % (error,))

    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="text_fix_bar_" + self.tab, elem_classes=["textfix-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="text_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.textFixSession || '']; }", 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()