File size: 12,542 Bytes
bfd34e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ac50c
bfd34e9
 
 
29ac50c
bfd34e9
29ac50c
 
 
 
 
 
 
 
bfd34e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da1e12f
 
bfd34e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import os
from collections import OrderedDict

import gradio as gr
import shutil
import uuid
import torch
from pathlib import Path
from lib.utils.iimage import IImage
from PIL import Image

from lib import models
from lib.methods import rasg, sd, sr
from lib.utils import poisson_blend, image_from_url_text


TMP_DIR = 'gradio_tmp'
if Path(TMP_DIR).exists():
    shutil.rmtree(TMP_DIR)
Path(TMP_DIR).mkdir(exist_ok=True, parents=True)

os.environ['GRADIO_TEMP_DIR'] = TMP_DIR

on_huggingspace = os.environ.get("SPACE_AUTHOR_NAME") == "PAIR"

negative_prompt_str = "text, bad anatomy, bad proportions, blurry, cropped, deformed, disfigured, duplicate, error, extra limbs, gross proportions, jpeg artifacts, long neck, low quality, lowres, malformed, morbid, mutated, mutilated, out of frame, ugly, worst quality"
positive_prompt_str = "Full HD, 4K, high quality, high resolution"

example_inputs = [
    ['assets/examples/images/a40.jpg', 'medieval castle'],
    ['assets/examples/images/a4.jpg', 'parrot'],
    ['assets/examples/images/a65.jpg', 'hoodie'],
    ['assets/examples/images/a54.jpg', 'salad'],
    ['assets/examples/images/a51.jpg', 'space helmet'],
    ['assets/examples/images/a46.jpg', 'stack of books'],
    ['assets/examples/images/a19.jpg', 'antique greek vase'],
    ['assets/examples/images/a2.jpg', 'sunglasses'],
]

thumbnails = [
    'assets/examples/sbs/a40.png',
    'assets/examples/sbs/a4.png',
    'assets/examples/sbs/a65.png',
    'assets/examples/sbs/a54.png',
    'assets/examples/sbs/a51.png',
    'assets/examples/sbs/a46.png',
    'assets/examples/sbs/a19.png',
    'assets/examples/sbs/a2.png'
]

example_previews = [
    [thumbnails[0], 'Prompt: medieval castle'],
    [thumbnails[1], 'Prompt: parrot'],
    [thumbnails[2], 'Prompt: hoodie'],
    [thumbnails[3], 'Prompt: salad'],
    [thumbnails[4], 'Prompt: space helmet'],
    [thumbnails[5], 'Prompt: laptop'],
    [thumbnails[6], 'Prompt: antique greek vase'],
    [thumbnails[7], 'Prompt: sunglasses'],
]

# Load models
inpainting_models = OrderedDict([
    ("Dreamshaper Inpainting V8", models.ds_inp.load_model()),
    ("Stable-Inpainting 2.0", models.sd2_inp.load_model()),
    ("Stable-Inpainting 1.5", models.sd15_inp.load_model())
])
sr_model = models.sd2_sr.load_model(device='cuda:1')
sam_predictor = models.sam.load_model(device='cuda:0')

inp_model = None
cached_inp_model_name  = ''

def remove_cached_inpainting_model():
    global inp_model
    global cached_inp_model_name
    del inp_model
    inp_model = None
    cached_inp_model_name = ''
    torch.cuda.empty_cache()


def set_model_from_name(inp_model_name):
    global cached_inp_model_name
    global inp_model

    if inp_model_name == cached_inp_model_name:
        print (f"Activating Cached Inpaintng Model: {inp_model_name}")
        return

    print (f"Activating Inpaintng Model: {inp_model_name}")
    inp_model = inpainting_models[inp_model_name]
    cached_inp_model_name = inp_model_name


def rasg_run(use_painta, prompt, input, seed, eta, negative_prompt, positive_prompt, ddim_steps,
guidance_scale=7.5, batch_size=4):
    torch.cuda.empty_cache()

    seed = int(seed)
    batch_size = max(1, min(int(batch_size), 4))

    image = IImage(input['image']).resize(512)
    mask = IImage(input['mask']).rgb().resize(512)

    method = ['rasg']
    if use_painta: method.append('painta')

    inpainted_images = []
    blended_images = []
    for i in range(batch_size):
        inpainted_image = rasg.run(
            ddim = inp_model,
            method = '-'.join(method),
            prompt = prompt,
            image = image.padx(64),
            mask = mask.alpha().padx(64),
            seed = seed+i*1000,
            eta = eta,
            prefix = '{}',
            negative_prompt = negative_prompt,
            positive_prompt = f', {positive_prompt}',
            dt = 1000 // ddim_steps,
            guidance_scale = guidance_scale
        ).crop(image.size)
        blended_image = poisson_blend(orig_img = image.data[0], fake_img = inpainted_image.data[0],
            mask = mask.data[0], dilation = 12)
        
        blended_images.append(blended_image)
        inpainted_images.append(inpainted_image.numpy()[0])

    return blended_images, inpainted_images


def sd_run(use_painta, prompt, input, seed, eta, negative_prompt, positive_prompt, ddim_steps,
guidance_scale=7.5, batch_size=4):
    torch.cuda.empty_cache()

    seed = int(seed)
    batch_size = max(1, min(int(batch_size), 4))

    image = IImage(input['image']).resize(512)
    mask = IImage(input['mask']).rgb().resize(512)

    method = ['default']
    if use_painta: method.append('painta')

    inpainted_images = []
    blended_images = []
    for i in range(batch_size):
        inpainted_image = sd.run(
            ddim = inp_model,
            method = '-'.join(method),
            prompt = prompt,
            image = image.padx(64),
            mask = mask.alpha().padx(64),
            seed = seed+i*1000,
            eta = eta,
            prefix = '{}',
            negative_prompt = negative_prompt,
            positive_prompt = f', {positive_prompt}',
            dt = 1000 // ddim_steps,
            guidance_scale = guidance_scale
        ).crop(image.size)

        blended_image = poisson_blend(orig_img = image.data[0], fake_img = inpainted_image.data[0],
            mask = mask.data[0], dilation = 12)

        blended_images.append(blended_image)
        inpainted_images.append(inpainted_image.numpy()[0])

    return blended_images, inpainted_images


def upscale_run(
    prompt, input, ddim_steps, seed, use_sam_mask, gallery, img_index,
negative_prompt='', positive_prompt=', high resolution professional photo'):
    torch.cuda.empty_cache()

    # Load SR model and SAM predictor
    # sr_model = models.sd2_sr.load_model()
    # sam_predictor = None
    # if use_sam_mask:
    #     sam_predictor = models.sam.load_model()

    seed = int(seed)
    img_index = int(img_index)
 
    img_index = 0 if img_index < 0 else img_index
    img_index = len(gallery) - 1 if img_index >= len(gallery) else img_index
    img_info = gallery[img_index if img_index >= 0 else 0]
    inpainted_image = image_from_url_text(img_info)
    lr_image = IImage(inpainted_image)
    hr_image = IImage(input['image']).resize(2048)
    hr_mask = IImage(input['mask']).resize(2048)
    output_image = sr.run(sr_model, sam_predictor, lr_image, hr_image, hr_mask, prompt=prompt + positive_prompt,
        noise_level=0, blend_trick=True, blend_output=True, negative_prompt=negative_prompt, 
        seed=seed, use_sam_mask=use_sam_mask)
    return output_image.numpy()[0], output_image.numpy()[0]


def switch_run(use_rasg, model_name, *args):
    set_model_from_name(model_name)
    if use_rasg:
        return rasg_run(*args)
    return sd_run(*args)


with gr.Blocks(css='style.css') as demo:
    gr.HTML(
        """
        <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
        <h1 style="font-weight: 900; font-size: 3rem; margin-bottom: 0.5rem">
            🧑‍🎨 HD-Painter Demo
        </h1>
        <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
        Hayk Manukyan<sup>1*</sup>, Andranik Sargsyan<sup>1*</sup>, Barsegh Atanyan<sup>1</sup>, Zhangyang Wang<sup>1,2</sup>, Shant Navasardyan<sup>1</sup>
        and <a href="https://www.humphreyshi.com/home">Humphrey Shi</a><sup>1,3</sup>
        </h2>
        <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
        <sup>1</sup>Picsart AI Resarch (PAIR), <sup>2</sup>UT Austin, <sup>3</sup>Georgia Tech
        </h2>
        <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
        [<a href="https://arxiv.org/abs/2312.14091" style="color:blue;">arXiv</a>] 
        [<a href="https://github.com/Picsart-AI-Research/HD-Painter" style="color:blue;">GitHub</a>]
        </h2>
        <h2 style="font-weight: 450; font-size: 1rem; margin: 0.7rem auto; max-width: 1000px">
        <b>HD-Painter</b> enables prompt-faithfull and high resolution (up to 2k) image inpainting upon any diffusion-based image inpainting method.
        </h2>
        </div>
        """)

    if on_huggingspace:
        gr.HTML("""
        <p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.
        <br/>
        <a href="https://huggingface.co/spaces/PAIR/HD-Painter?duplicate=true">
        <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
        </p>""")

    with open('script.js', 'r') as f:
        js_str = f.read()

    demo.load(_js=js_str)

    with gr.Row():
        with gr.Column():
            model_picker = gr.Dropdown(
                list(inpainting_models.keys()),
                value=0,
                label = "Please select a model!",
            )
        with gr.Column():
            use_painta = gr.Checkbox(value = True, label = "Use PAIntA")
            use_rasg = gr.Checkbox(value = True, label = "Use RASG")

    prompt = gr.Textbox(label = "Inpainting Prompt")
    with gr.Row():
        with gr.Column():
            input = gr.ImageMask(label = "Input Image", brush_color='#ff0000', elem_id="inputmask")
            
            with gr.Row():
                inpaint_btn = gr.Button("Inpaint", scale = 0)
   
            with gr.Accordion('Advanced options', open=False):
                guidance_scale = gr.Slider(minimum = 0, maximum = 30, value = 7.5, label = "Guidance Scale")
                eta = gr.Slider(minimum = 0, maximum = 1, value = 0.1, label = "eta")
                ddim_steps = gr.Slider(minimum = 10, maximum = 100, value = 50, step =  1, label = 'Number of diffusion steps')
                with gr.Row():
                    seed = gr.Number(value = 49123, label = "Seed")
                    batch_size = gr.Number(value = 1, label = "Batch size", minimum=1, maximum=4) 
                negative_prompt = gr.Textbox(value=negative_prompt_str, label = "Negative prompt", lines=3)
                positive_prompt = gr.Textbox(value=positive_prompt_str, label = "Positive prompt", lines=1)

        with gr.Column():
            with gr.Row():
                output_gallery = gr.Gallery(
                    [],
                    columns = 4,
                    preview = True,
                    allow_preview = True,
                    object_fit='scale-down',
                    elem_id='outputgallery'
                )
            with gr.Row():
                upscale_btn = gr.Button("Send to Inpainting-Specialized Super-Resolution (x4)", scale = 1)
            with gr.Row():
                use_sam_mask = gr.Checkbox(value = False, label = "Use SAM mask for background preservation (for SR only, experimental feature)")
            with gr.Row():
                hires_image = gr.Image(label = "Hi-res Image")
    
    label = gr.Markdown("## High-Resolution Generation Samples (2048px large side)")
    
    with gr.Column():
        example_container = gr.Gallery(
            example_previews,
            columns = 4,
            preview = True,
            allow_preview = True,
            object_fit='scale-down'
        )

        gr.Examples(
            [
                example_inputs[i] + [[example_previews[i]]]
                for i in range(len(example_previews))
            ],
            [input, prompt, example_container]
        )

    mock_output_gallery = gr.Gallery([], columns = 4, visible=False)
    mock_hires = gr.Image(label = "__MHRO__", visible = False)
    html_info = gr.HTML(elem_id=f'html_info', elem_classes="infotext")

    inpaint_btn.click(
        fn=switch_run, 
        inputs=[
            use_rasg,
            model_picker,
            use_painta,
            prompt,
            input,
            seed,
            eta,
            negative_prompt,
            positive_prompt,
            ddim_steps,
            guidance_scale,
            batch_size
        ], 
        outputs=[output_gallery, mock_output_gallery], 
        api_name="inpaint"
    )
    upscale_btn.click(
        fn=upscale_run, 
        inputs=[
            prompt, 
            input,
            ddim_steps,
            seed,
            use_sam_mask,
            mock_output_gallery,
            html_info
        ],
        outputs=[hires_image, mock_hires], 
        api_name="upscale",
        _js="function(a, b, c, d, e, f, g){ return [a, b, c, d, e, f, selected_gallery_index()] }",
    )

demo.queue()
demo.launch(share=True, allowed_paths=[TMP_DIR])