webui.py 6.0 KB
Newer Older
1
import os
2
import threading
3

4
from modules.paths import script_path
5

A
first  
AUTOMATIC 已提交
6 7 8
import torch
import numpy as np
from omegaconf import OmegaConf
9 10
from PIL import Image

11
import signal
A
first  
AUTOMATIC 已提交
12 13

from ldm.util import instantiate_from_config
A
AUTOMATIC 已提交
14

15 16 17 18 19 20 21
from modules.shared import opts, cmd_opts, state
import modules.shared as shared
import modules.ui
from modules.ui import plaintext_to_html
import modules.scripts
import modules.processing as processing
import modules.sd_hijack
A
AUTOMATIC 已提交
22 23 24
import modules.codeformer_model
import modules.gfpgan_model
import modules.face_restoration
25
import modules.realesrgan_model as realesrgan
A
AUTOMATIC 已提交
26
import modules.esrgan_model as esrgan
27 28 29 30 31 32
import modules.images as images
import modules.lowvram
import modules.txt2img
import modules.img2img


A
AUTOMATIC 已提交
33 34 35 36
modules.codeformer_model.setup_codeformer()
modules.gfpgan_model.setup_gfpgan()
shared.face_restorers.append(modules.face_restoration.FaceRestoration())

A
AUTOMATIC 已提交
37
esrgan.load_models(cmd_opts.esrgan_models_path)
38
realesrgan.setup_realesrgan()
A
AUTOMATIC 已提交
39

A
first  
AUTOMATIC 已提交
40 41 42 43 44 45
def load_model_from_config(config, ckpt, verbose=False):
    print(f"Loading model from {ckpt}")
    pl_sd = torch.load(ckpt, map_location="cpu")
    if "global_step" in pl_sd:
        print(f"Global Step: {pl_sd['global_step']}")
    sd = pl_sd["state_dict"]
46

A
first  
AUTOMATIC 已提交
47 48 49 50 51 52 53 54 55 56 57 58
    model = instantiate_from_config(config.model)
    m, u = model.load_state_dict(sd, strict=False)
    if len(m) > 0 and verbose:
        print("missing keys:")
        print(m)
    if len(u) > 0 and verbose:
        print("unexpected keys:")
        print(u)

    model.eval()
    return model

A
AUTOMATIC 已提交
59
cached_images = {}
A
first  
AUTOMATIC 已提交
60

A
AUTOMATIC 已提交
61

62
def run_extras(image, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility):
63
    processing.torch_gc()
A
AUTOMATIC 已提交
64

65 66
    image = image.convert("RGB")

A
AUTOMATIC 已提交
67
    outpath = opts.outdir_samples or opts.outdir_extras_samples
A
AUTOMATIC 已提交
68

69 70
    if gfpgan_visibility > 0:
        restored_img = modules.gfpgan_model.gfpgan_fix_faces(np.array(image, dtype=np.uint8))
A
AUTOMATIC 已提交
71 72
        res = Image.fromarray(restored_img)

73 74 75 76 77 78 79 80 81 82 83
        if gfpgan_visibility < 1.0:
            res = Image.blend(image, res, gfpgan_visibility)

        image = res

    if codeformer_visibility > 0:
        restored_img = modules.codeformer_model.codeformer.restore(np.array(image, dtype=np.uint8), w=codeformer_weight)
        res = Image.fromarray(restored_img)

        if codeformer_visibility < 1.0:
            res = Image.blend(image, res, codeformer_visibility)
A
AUTOMATIC 已提交
84 85 86 87 88 89 90

        image = res

    if upscaling_resize != 1.0:
        def upscale(image, scaler_index, resize):
            small = image.crop((image.width // 2, image.height // 2, image.width // 2 + 10, image.height // 2 + 10))
            pixels = tuple(np.array(small).flatten().tolist())
91
            key = (resize, scaler_index, image.width, image.height, gfpgan_visibility, codeformer_visibility, codeformer_weight) + pixels
A
AUTOMATIC 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105

            c = cached_images.get(key)
            if c is None:
                upscaler = shared.sd_upscalers[scaler_index]
                c = upscaler.upscale(image, image.width * resize, image.height * resize)
                cached_images[key] = c

            return c

        res = upscale(image, extras_upscaler_1, upscaling_resize)

        if extras_upscaler_2 != 0 and extras_upscaler_2_visibility>0:
            res2 = upscale(image, extras_upscaler_2, upscaling_resize)
            res = Image.blend(res, res2, extras_upscaler_2_visibility)
A
AUTOMATIC 已提交
106 107 108

        image = res

A
AUTOMATIC 已提交
109 110
    while len(cached_images) > 2:
        del cached_images[next(iter(cached_images.keys()))]
111

112
    images.save_image(image, outpath, "", None, '', opts.samples_format, short_filename=True, no_prompt=True)
113

A
AUTOMATIC 已提交
114
    return image, '', ''
115 116


A
AUTOMATIC 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130
def run_pnginfo(image):
    info = ''
    for key, text in image.info.items():
        info += f"""
<div>
<p><b>{plaintext_to_html(str(key))}</b></p>
<p>{plaintext_to_html(str(text))}</p>
</div>
""".strip()+"\n"

    if len(info) == 0:
        message = "Nothing found in the image."
        info = f"<div><p>{message}<p></div>"

A
AUTOMATIC 已提交
131
    return '', '', info
A
AUTOMATIC 已提交
132 133


134
queue_lock = threading.Lock()
135

A
AUTOMATIC 已提交
136

137 138
def wrap_gradio_gpu_call(func):
    def f(*args, **kwargs):
A
AUTOMATIC 已提交
139
        shared.state.sampling_step = 0
A
AUTOMATIC 已提交
140
        shared.state.job_count = -1
A
AUTOMATIC 已提交
141
        shared.state.job_no = 0
A
AUTOMATIC 已提交
142 143
        shared.state.current_latent = None
        shared.state.current_image = None
144
        shared.state.current_image_sampling_step = 0
A
AUTOMATIC 已提交
145

146 147
        with queue_lock:
            res = func(*args, **kwargs)
A
AUTOMATIC 已提交
148

149
        shared.state.job = ""
A
AUTOMATIC 已提交
150
        shared.state.job_count = 0
A
AUTOMATIC 已提交
151

152
        return res
A
AUTOMATIC 已提交
153

154
    return modules.ui.wrap_gradio_call(f)
A
AUTOMATIC 已提交
155

156
modules.scripts.load_scripts(os.path.join(script_path, "scripts"))
A
AUTOMATIC 已提交
157

A
AUTOMATIC 已提交
158 159 160 161 162 163 164 165 166
try:
    # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start.

    from transformers import logging

    logging.set_verbosity_error()
except Exception:
    pass

A
AUTOMATIC 已提交
167
sd_config = OmegaConf.load(cmd_opts.config)
168 169
shared.sd_model = load_model_from_config(sd_config, cmd_opts.ckpt)
shared.sd_model = (shared.sd_model if cmd_opts.no_half else shared.sd_model.half())
170

A
AUTOMATIC 已提交
171
if cmd_opts.lowvram or cmd_opts.medvram:
172
    modules.lowvram.setup_for_low_vram(shared.sd_model, cmd_opts.medvram)
A
AUTOMATIC 已提交
173
else:
174
    shared.sd_model = shared.sd_model.to(shared.device)
A
AUTOMATIC 已提交
175

176
modules.sd_hijack.model_hijack.hijack(shared.sd_model)
177

178 179

def webui():
A
AUTOMATIC 已提交
180 181
    # make the program just exit at ctrl+c without waiting for anything
    def sigint_handler(sig, frame):
A
AUTOMATIC 已提交
182
        print(f'Interrupted with signal {sig} in {frame}')
A
AUTOMATIC 已提交
183
        os._exit(0)
A
first  
AUTOMATIC 已提交
184

A
AUTOMATIC 已提交
185
    signal.signal(signal.SIGINT, sigint_handler)
186

A
AUTOMATIC 已提交
187 188 189 190 191 192
    demo = modules.ui.create_ui(
        txt2img=wrap_gradio_gpu_call(modules.txt2img.txt2img),
        img2img=wrap_gradio_gpu_call(modules.img2img.img2img),
        run_extras=wrap_gradio_gpu_call(run_extras),
        run_pnginfo=run_pnginfo
    )
193

O
orionaskatu 已提交
194
    demo.launch(share=cmd_opts.share, server_name="0.0.0.0" if cmd_opts.listen else None, server_port=cmd_opts.port)
195 196 197

if __name__ == "__main__":
    webui()