File size: 9,700 Bytes
4c1d330
 
 
 
 
a6049d1
4c1d330
 
 
 
a6049d1
4c1d330
a6049d1
4c1d330
188ed7e
 
9e2d369
 
523ab02
 
4c1d330
 
 
 
 
 
 
28d6d09
4c1d330
 
 
 
 
 
28d6d09
4c1d330
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400ac43
 
 
 
4c1d330
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90bc5e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1760b4e
 
 
72b0442
cbf89f5
 
1760b4e
 
 
90bc5e7
72b0442
9e2d369
 
 
 
cbf89f5
90bc5e7
 
72b0442
 
90bc5e7
72b0442
 
 
 
 
 
1760b4e
72b0442
 
1760b4e
72b0442
 
1760b4e
4c1d330
188ed7e
4c1d330
48db291
72b0442
90bc5e7
1760b4e
 
 
 
4c1d330
9e2d369
90bc5e7
1760b4e
 
 
 
 
 
 
 
 
 
48db291
72b0442
1760b4e
 
 
 
 
 
 
72b0442
 
 
 
 
 
 
 
 
 
1760b4e
 
cbf89f5
1760b4e
72b0442
1760b4e
 
 
48db291
1760b4e
 
 
 
 
 
 
 
 
 
 
 
 
72b0442
 
 
 
 
 
 
 
 
1760b4e
 
 
9e2d369
1760b4e
72b0442
1760b4e
 
 
 
 
 
 
 
 
cbf89f5
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
import os
import numpy as np
import torch as th
from imageio import imread
from skimage.transform import resize as imresize
from PIL import Image

from decomp_diffusion.model_and_diffusion_util import *
from decomp_diffusion.diffusion.respace import SpacedDiffusion
from decomp_diffusion.gen_image import *

from download import download_model
from upsampling import get_pipeline, upscale_image

import gradio as gr

# from huggingface_hub import login



# fix randomness
th.manual_seed(0)
np.random.seed(0)


def get_pil_im(im, resolution=64):
    im = imresize(im, (resolution, resolution))[:, :, :3]
    im = th.Tensor(im).permute(2, 0, 1)[None, :, :, :].contiguous()
    return im


# generate image components and reconstruction
def gen_image_and_components(model, gd, im, num_components=4, sample_method='ddim', batch_size=1, image_size=64, device='cuda', num_images=1):
    """Generate row of orig image, individual components, and reconstructed image"""
    orig_img = get_pil_im(im, resolution=image_size).to(device)
    latent = model.encode_latent(orig_img)
    model_kwargs = {'latent': latent}

    assert sample_method in ('ddpm', 'ddim')
    sample_loop_func = gd.p_sample_loop if sample_method == 'ddpm' else gd.ddim_sample_loop
    if sample_method == 'ddim':
        model = gd._wrap_model(model)
        
    # generate imgs
    for i in range(num_images):
        all_samples = [orig_img]
        # individual components
        for j in range(num_components):
            model_kwargs['latent_index'] = j
            sample = sample_loop_func(
                model,
                (batch_size, 3, image_size, image_size),
                device=device,
                clip_denoised=True,
                progress=True,
                model_kwargs=model_kwargs,
                cond_fn=None,
            )[:batch_size]

            # save indiv comp
            all_samples.append(sample)
        # reconstruction
        model_kwargs['latent_index'] = None
        sample = sample_loop_func(
            model,
            (batch_size, 3, image_size, image_size),
            device=device,
            clip_denoised=True,
            progress=True,
            model_kwargs=model_kwargs,
            cond_fn=None,
        )[:batch_size]
        # save indiv reconstruction
        all_samples.append(sample)

        samples = th.cat(all_samples, dim=0).cpu()   
        grid = make_grid(samples, nrow=samples.shape[0], padding=0)
        return grid
        

# def decompose_image(im):
#     sample_method = 'ddim'
#     result = gen_image_and_components(clevr_model, GD[sample_method], im, sample_method=sample_method, num_images=1, device=device)
#     return result.permute(1, 2, 0).numpy()


# load diffusion
GD = {} # diffusion objects for ddim and ddpm
diffusion_kwargs = diffusion_defaults()
gd = create_gaussian_diffusion(**diffusion_kwargs)
GD['ddpm'] = gd

# set up ddim sampling
desired_timesteps = 50 
num_timesteps = diffusion_kwargs['steps']

spacing = num_timesteps // desired_timesteps
spaced_ts = list(range(0, num_timesteps + 1, spacing))
betas = get_named_beta_schedule(diffusion_kwargs['noise_schedule'], num_timesteps)
diffusion_kwargs['betas'] = betas
del diffusion_kwargs['steps'], diffusion_kwargs['noise_schedule']
gd = SpacedDiffusion(spaced_ts, rescale_timesteps=True, original_num_steps=num_timesteps, **diffusion_kwargs)

GD['ddim'] = gd


def combine_components_slice(model, gd, im1, im2, indices=None, sample_method='ddim', device='cuda', num_images=4, model_kwargs={}, desc='', save_dir='', dataset='clevr', image_size=64):
    """Combine by adding components together
    """
    assert sample_method in ('ddpm', 'ddim')
    
    im1 = get_pil_im(im1, resolution=image_size).to(device)
    im2 = get_pil_im(im2, resolution=image_size).to(device)

    latent1 = model.encode_latent(im1)
    latent2 = model.encode_latent(im2)

    num_comps = model.num_components 

    # get latent slices
    if indices == None:
        half = num_comps // 2
        indices = [1] * half + [0] * half # first half 1, second half 0
        indices = th.Tensor(indices) == 1
        indices = indices.reshape(num_comps, 1)
    elif type(indices) == str:
        indices = indices.split(',')
        indices = [int(ind) for ind in indices]
        indices = th.Tensor(indices).reshape(-1, 1) == 1
    assert len(indices) == num_comps
    indices = indices.to(device)

    latent1 = latent1.reshape(num_comps, -1).to(device)
    latent2 = latent2.reshape(num_comps, -1).to(device)

    combined_latent = th.where(indices, latent1, latent2)
    combined_latent = combined_latent.reshape(1, -1)
    model_kwargs['latent'] = combined_latent
    
    sample_loop_func = gd.p_sample_loop if sample_method == 'ddpm' else gd.ddim_sample_loop
    if sample_method == 'ddim':
        model = gd._wrap_model(model)

    # sampling loop
    sample = sample_loop_func(
            model,
            (1, 3, image_size, image_size),
            device=device,
            clip_denoised=True,
            progress=True,
            model_kwargs=model_kwargs,
            cond_fn=None,
        )[:1]

    return sample[0].cpu()


def decompose_image_demo(im, model):
    sample_method = 'ddim'
    result = gen_image_and_components(MODELS[model], GD[sample_method], im, sample_method=sample_method, num_images=1, device=device)
    # result = Image.fromarray(result.permute(1, 2, 0).numpy())
    return result.permute(1, 2, 0).numpy()


def combine_images_demo(im1, im2, model):
    sample_method = 'ddim'
    result = combine_components_slice(MODELS[model], GD[sample_method], im1, im2, indices='1,0,1,0', sample_method=sample_method, num_images=1, device=device)
    result = result.permute(1, 2, 0).numpy()
    # result = Image.fromarray(result.permute(1, 2, 0).numpy())
    # if model == 'CelebA-HQ':
    #     return upscale_image(result, pipe)
    return result


def load_model(dataset, extra_kwargs={}, device='cuda'):
    ckpt_path = download_model(dataset) 

    model_kwargs = unet_model_defaults()
    # model parameters
    model_kwargs.update(extra_kwargs)
    model = create_diffusion_model(**model_kwargs)
    model.eval()
    model.to(device)

    print(f'loading from {ckpt_path}')
    checkpoint = th.load(ckpt_path, map_location='cpu')

    model.load_state_dict(checkpoint)
    return model


device = 'cuda' if th.cuda.is_available() else 'cpu'

clevr_model = load_model('clevr', extra_kwargs=dict(emb_dim=64, enc_channels=128), device=device)
celeb_model = load_model('celebahq', extra_kwargs=dict(enc_channels=128), device=device)

MODELS = {
    'CLEVR': clevr_model,
    'CelebA-HQ': celeb_model
}

# pipe = get_pipeline()

with gr.Blocks() as demo:
    gr.Markdown(
        """<h1 style="text-align: center;"><b>Unsupervised Compositional Image Decomposition with Diffusion Models
</b> - <a href="https://jsu27.github.io/decomp-diffusion-web/">Project Page</a></h1>""")
    
    gr.Markdown(
        """<p style="font-size: 18px;">We introduce Decomp Diffusion, an unsupervised approach that discovers compositional concepts from images, represented by diffusion models.
</p>""")
    
    gr.Markdown(
            """<br> <h4>Decomposition and reconstruction of images</h4>""")
    with gr.Row():
        with gr.Column():
            with gr.Row():
                decomp_input = gr.Image(type='numpy', label='Input')
            with gr.Row():
                decomp_model = gr.Radio(
                    ['CLEVR', 'CelebA-HQ'], type="value", label='Model',
                    value='CLEVR')
                
            with gr.Row():

                # image_examples = [os.path.join(os.path.dirname(__file__), 'sample_images/clevr_im_10.png'), 'CLEVR']
                decomp_examples = [['sample_images/clevr_im_10.png', 'CLEVR'],
                                    ['sample_images/celebahq_im_15.jpg', 'CelebA-HQ']]
                decomp_img_examples = gr.Examples(
                    examples=decomp_examples,
                    inputs=[decomp_input, decomp_model]
                )
            
        with gr.Column():
            decomp_output = gr.Image(type='numpy')
            decomp_button = gr.Button("Generate")
    


    gr.Markdown(
            """<br> <h4>Combination of images</h4>""")
    with gr.Row().style(equal_height=True):
        with gr.Column(scale=2):

            with gr.Row():
                with gr.Column():
                    comb_input1 = gr.Image(type='numpy', label='Input 1')
                with gr.Column():
                    comb_input2 = gr.Image(type='numpy', label='Input 2')

            with gr.Row():
                comb_model = gr.Radio(
                    ['CLEVR', 'CelebA-HQ'], type="value", label='Model',
                    value='CLEVR')
            
            with gr.Row():

                comb_examples = [['sample_images/clevr_im_10.png', 'sample_images/clevr_im_25.png', 'CLEVR'],
                                    ['sample_images/celebahq_im_15.jpg', 'sample_images/celebahq_im_21.jpg', 'CelebA-HQ']]
                comb_img_examples = gr.Examples(
                    examples=comb_examples,
                    inputs=[comb_input1, comb_input2, comb_model]
                )
            

        with gr.Column(scale=1):
            comb_output = gr.Image(type='numpy')
            comb_button = gr.Button("Generate")
    

    decomp_button.click(decompose_image_demo,
                       inputs=[decomp_input, decomp_model],
                       outputs=decomp_output)
    comb_button.click(combine_images_demo,
                       inputs=[comb_input1, comb_input2, comb_model],
                       outputs=comb_output)


demo.launch(debug=True)