webui.py 4.2 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 22 23 24 25 26 27 28 29 30 31 32
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
import modules.gfpgan_model as gfpgan
import modules.realesrgan_model as realesrgan
import modules.images as images
import modules.lowvram
import modules.txt2img
import modules.img2img


shared.sd_upscalers = {
    "RealESRGAN": lambda img: realesrgan.upscale_with_realesrgan(img, 2, 0),
    "Lanczos": lambda img: img.resize((img.width*2, img.height*2), resample=images.LANCZOS),
A
AUTOMATIC 已提交
33 34
    "None": lambda img: img
}
35 36
realesrgan.setup_realesrgan()
gfpgan.setup_gfpgan()
A
AUTOMATIC 已提交
37 38


A
first  
AUTOMATIC 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
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"]
    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 已提交
58
def run_extras(image, GFPGAN_strength, RealESRGAN_upscaling, RealESRGAN_model_index):
59
    processing.torch_gc()
A
AUTOMATIC 已提交
60

61 62
    image = image.convert("RGB")

A
AUTOMATIC 已提交
63
    outpath = opts.outdir_samples or opts.outdir_extras_samples
A
AUTOMATIC 已提交
64

65
    if gfpgan.have_gfpgan is not None and GFPGAN_strength > 0:
66

67
        restored_img = gfpgan.gfpgan_fix_faces(np.array(image, dtype=np.uint8))
A
AUTOMATIC 已提交
68 69 70 71 72 73 74
        res = Image.fromarray(restored_img)

        if GFPGAN_strength < 1.0:
            res = Image.blend(image, res, GFPGAN_strength)

        image = res

75 76
    if realesrgan.have_realesrgan and RealESRGAN_upscaling != 1.0:
        image = realesrgan.upscale_with_realesrgan(image, RealESRGAN_upscaling, RealESRGAN_model_index)
77

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

A
AUTOMATIC 已提交
80
    return image, '', ''
81 82


A
AUTOMATIC 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96
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 已提交
97
    return '', '', info
A
AUTOMATIC 已提交
98 99


100
queue_lock = threading.Lock()
101

A
AUTOMATIC 已提交
102

103 104 105 106
def wrap_gradio_gpu_call(func):
    def f(*args, **kwargs):
        with queue_lock:
            res = func(*args, **kwargs)
A
AUTOMATIC 已提交
107

108
        shared.state.job = ""
A
AUTOMATIC 已提交
109

110
        return res
A
AUTOMATIC 已提交
111

112
    return modules.ui.wrap_gradio_call(f)
A
AUTOMATIC 已提交
113 114


A
AUTOMATIC 已提交
115 116 117 118 119 120 121 122 123
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 已提交
124
sd_config = OmegaConf.load(cmd_opts.config)
125 126
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())
127

A
AUTOMATIC 已提交
128
if cmd_opts.lowvram or cmd_opts.medvram:
129
    modules.lowvram.setup_for_low_vram(shared.sd_model, cmd_opts.medvram)
A
AUTOMATIC 已提交
130
else:
131
    shared.sd_model = shared.sd_model.to(shared.device)
A
AUTOMATIC 已提交
132

133
modules.sd_hijack.model_hijack.hijack(shared.sd_model)
134

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

A
first  
AUTOMATIC 已提交
137

138
# make the program just exit at ctrl+c without waiting for anything
A
AUTOMATIC 已提交
139 140
def sigint_handler(sig, frame):
    print(f'Interrupted with singal {sig} in {frame}')
141 142
    os._exit(0)

143

144 145
signal.signal(signal.SIGINT, sigint_handler)

146 147 148 149 150
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
151 152
)

A
AUTOMATIC 已提交
153
demo.launch(share=cmd_opts.share)