flamehaze1115 commited on
Commit
de49b4d
1 Parent(s): d370864

Upload gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +348 -0
gradio_app.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import fire
4
+ import gradio as gr
5
+ from PIL import Image
6
+ from functools import partial
7
+
8
+ import cv2
9
+ import time
10
+ import numpy as np
11
+ from rembg import remove
12
+ from segment_anything import sam_model_registry, SamPredictor
13
+
14
+ import os
15
+ import sys
16
+ import numpy
17
+ import torch
18
+ import rembg
19
+ import threading
20
+ import urllib.request
21
+ from PIL import Image
22
+ from typing import Dict, Optional, Tuple, List
23
+ from dataclasses import dataclass
24
+ import streamlit as st
25
+ import huggingface_hub
26
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
27
+ from mvdiffusion.models.unet_mv2d_condition import UNetMV2DConditionModel
28
+ from mvdiffusion.data.single_image_dataset import SingleImageDataset as MVDiffusionDataset
29
+ from mvdiffusion.pipelines.pipeline_mvdiffusion_image import MVDiffusionImagePipeline
30
+ from diffusers import AutoencoderKL, DDPMScheduler, DDIMScheduler
31
+ from einops import rearrange
32
+ import numpy as np
33
+
34
+
35
+
36
+
37
+
38
+ def save_image(tensor):
39
+ ndarr = tensor.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
40
+ # pdb.set_trace()
41
+ im = Image.fromarray(ndarr)
42
+ return ndarr
43
+
44
+ weight_dtype = torch.float16
45
+
46
+ _TITLE = '''Wonder3D: Single Image to 3D using Cross-Domain Diffusion'''
47
+ _DESCRIPTION = '''
48
+ <div>
49
+ <a style="display:inline-block; margin-left: .5em" href="https://arxiv.org/abs/2310.15110"><img src="https://img.shields.io/badge/2310.15110-f9f7f7?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADcAAABMCAYAAADJPi9EAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAa2SURBVHja3Zt7bBRFGMAXUCDGF4rY7m7bAwuhlggKStFgLBgFEkCIIRJEEoOBYHwRFYKilUgEReVNJEGCJJpehHI3M9vZvd3bUP1DjNhEIRQQsQgSHiJgQZ5dv7krWEvvdmZ7d7vHJN+ft/f99pv5XvOtJMFCqvoCUpTdIEeRLC+L9Ox5i3Q9LACaCeK0kXoSChVcD3C/tQPHpAEsquQ73IkUcEz2kcLCknyGW5MGjkljRFVL8xJOKyi4CwCOuQAeAkfTP1+tNxLkogvgEbDgffkJqKqvuMA5ifOpqg/5qWecRstNg7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JodUDE0HR8Ll5V0lPxcrLEHZPV4AzS83OLis7FowVa3RSku7BSNxJqQAlN3hBTC2apmDSkpaw22wJemGQFUG7J4MlP3JC6A+f96V7vRyX9It3nzT/GrjIU8edM7rMSnIi10f476lzbE1K7yEiEuWro0OJBguLCwDuFOJc1Na6sRWL/cCeMIwUN9ggSVbe3v/5/EgzTKWLvEAiBrYRUkgwNI2ZaFQNT75UDxEUEx97zYnzpmiLEmbaYCbNxYtFAb0/Z4AztgUrhyxuNgxPnhfHFDHz/vTgFWUQZxTRkkJhQ6YNdVUEPAfO6ZV5BRss6LcCVb7VaAma9giy0XJZBt9IQh42NY0NSdgbLIPlLUF6rEdrdt0CUCK1wsCbkcI3ZSLc7ZSwGLbmJXbPsNxnE5xilYKAobZ77LpGZ8TAIun+/iCKQoF71IxQDI3K2CCd+ARNvXg9sykBcnHAoCZG4u66hlDoQLe6QV4CRtFSxZQ+D0BwNO2jgdkzoGoah1nj3FVlSR19taTSYxI8QLut23U8dsgzqHulJNCQpcqBnpTALCuQ6NSYLHpmR5i42gZzuIdcrMMvMJbQlxe3jXxyZnLACl7ARm/FjPIDOY8ODtpM71sxwfcZpvBeUzKWmfNINM5AS+wO0Khh7dMqKccu4+qatarZjYAwDlgetzStHtEt+XedsBOQtU9XMrRgjg4KTnc5nr+dmqadit/4C4uLm8DuA9koJTj1TL7fI5nDL+qqoo/FLGAzL7dYT17PzvAcQONYSUQRxW/QMrHZVIyik0ZuQA2mzp+Ji8BW4YM3Mbzm9inaHkJCGfrUZZjujiYailfFwA8DHIy3acwUj4v9vUVa+SmgNsl5fuyDTKovW9/IAmfLV0Pi2UncA515kjYdrwC9i9rpuHiq3JwtAAAAABJRU5ErkJggg=="></a>
50
+ <a style="display:inline-block; margin-left: .5em" href='https://github.com/SUDO-AI-3D/zero123plus'><img src='https://img.shields.io/github/stars/SUDO-AI-3D/zero123plus?style=social' /></a>
51
+ </div>
52
+ '''
53
+ _GPU_ID = 0
54
+
55
+
56
+ if not hasattr(Image, 'Resampling'):
57
+ Image.Resampling = Image
58
+
59
+
60
+ def sam_init():
61
+ sam_checkpoint = os.path.join(os.path.dirname(__file__), "sam_pt", "sam_vit_h_4b8939.pth")
62
+ model_type = "vit_h"
63
+
64
+ sam = sam_model_registry[model_type](checkpoint=sam_checkpoint).to(device=f"cuda:{_GPU_ID}")
65
+ predictor = SamPredictor(sam)
66
+ return predictor
67
+
68
+ def sam_segment(predictor, input_image, *bbox_coords):
69
+ bbox = np.array(bbox_coords)
70
+ image = np.asarray(input_image)
71
+
72
+ start_time = time.time()
73
+ predictor.set_image(image)
74
+
75
+ masks_bbox, scores_bbox, logits_bbox = predictor.predict(
76
+ box=bbox,
77
+ multimask_output=True
78
+ )
79
+
80
+ print(f"SAM Time: {time.time() - start_time:.3f}s")
81
+ out_image = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
82
+ out_image[:, :, :3] = image
83
+ out_image_bbox = out_image.copy()
84
+ out_image_bbox[:, :, 3] = masks_bbox[-1].astype(np.uint8) * 255
85
+ torch.cuda.empty_cache()
86
+ return Image.fromarray(out_image_bbox, mode='RGBA')
87
+
88
+ def expand2square(pil_img, background_color):
89
+ width, height = pil_img.size
90
+ if width == height:
91
+ return pil_img
92
+ elif width > height:
93
+ result = Image.new(pil_img.mode, (width, width), background_color)
94
+ result.paste(pil_img, (0, (width - height) // 2))
95
+ return result
96
+ else:
97
+ result = Image.new(pil_img.mode, (height, height), background_color)
98
+ result.paste(pil_img, ((height - width) // 2, 0))
99
+ return result
100
+
101
+ def preprocess(predictor, input_image, chk_group=None, segment=True, rescale=False):
102
+ RES = 1024
103
+ input_image.thumbnail([RES, RES], Image.Resampling.LANCZOS)
104
+ if chk_group is not None:
105
+ segment = "Background Removal" in chk_group
106
+ rescale = "Rescale" in chk_group
107
+ if segment:
108
+ image_rem = input_image.convert('RGBA')
109
+ image_nobg = remove(image_rem, alpha_matting=True)
110
+ arr = np.asarray(image_nobg)[:,:,-1]
111
+ x_nonzero = np.nonzero(arr.sum(axis=0))
112
+ y_nonzero = np.nonzero(arr.sum(axis=1))
113
+ x_min = int(x_nonzero[0].min())
114
+ y_min = int(y_nonzero[0].min())
115
+ x_max = int(x_nonzero[0].max())
116
+ y_max = int(y_nonzero[0].max())
117
+ input_image = sam_segment(predictor, input_image.convert('RGB'), x_min, y_min, x_max, y_max)
118
+ # Rescale and recenter
119
+ if rescale:
120
+ image_arr = np.array(input_image)
121
+ in_w, in_h = image_arr.shape[:2]
122
+ out_res = min(RES, max(in_w, in_h))
123
+ ret, mask = cv2.threshold(np.array(input_image.split()[-1]), 0, 255, cv2.THRESH_BINARY)
124
+ x, y, w, h = cv2.boundingRect(mask)
125
+ max_size = max(w, h)
126
+ ratio = 0.75
127
+ side_len = int(max_size / ratio)
128
+ padded_image = np.zeros((side_len, side_len, 4), dtype=np.uint8)
129
+ center = side_len//2
130
+ padded_image[center-h//2:center-h//2+h, center-w//2:center-w//2+w] = image_arr[y:y+h, x:x+w]
131
+ rgba = Image.fromarray(padded_image).resize((out_res, out_res), Image.LANCZOS)
132
+
133
+ rgba_arr = np.array(rgba) / 255.0
134
+ rgb = rgba_arr[...,:3] * rgba_arr[...,-1:] + (1 - rgba_arr[...,-1:])
135
+ input_image = Image.fromarray((rgb * 255).astype(np.uint8))
136
+ else:
137
+ input_image = expand2square(input_image, (127, 127, 127, 0))
138
+ return input_image, input_image.resize((320, 320), Image.Resampling.LANCZOS)
139
+
140
+
141
+ def load_wonder3d_pipeline(cfg):
142
+ # Load scheduler, tokenizer and models.
143
+ # noise_scheduler = DDPMScheduler.from_pretrained(cfg.pretrained_model_name_or_path, subfolder="scheduler")
144
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(cfg.pretrained_model_name_or_path, subfolder="image_encoder", revision=cfg.revision)
145
+ feature_extractor = CLIPImageProcessor.from_pretrained(cfg.pretrained_model_name_or_path, subfolder="feature_extractor", revision=cfg.revision)
146
+ vae = AutoencoderKL.from_pretrained(cfg.pretrained_model_name_or_path, subfolder="vae", revision=cfg.revision)
147
+ unet = UNetMV2DConditionModel.from_pretrained_2d(cfg.pretrained_unet_path, subfolder="unet", revision=cfg.revision, **cfg.unet_from_pretrained_kwargs)
148
+ unet.enable_xformers_memory_efficient_attention()
149
+
150
+ # Move text_encode and vae to gpu and cast to weight_dtype
151
+ image_encoder.to(dtype=weight_dtype)
152
+ vae.to(dtype=weight_dtype)
153
+ unet.to(dtype=weight_dtype)
154
+
155
+ pipeline = MVDiffusionImagePipeline(
156
+ image_encoder=image_encoder, feature_extractor=feature_extractor, vae=vae, unet=unet, safety_checker=None,
157
+ scheduler=DDIMScheduler.from_pretrained(cfg.pretrained_model_name_or_path, subfolder="scheduler"),
158
+ **cfg.pipe_kwargs
159
+ )
160
+
161
+ if torch.cuda.is_available():
162
+ pipeline.to('cuda:0')
163
+ # sys.main_lock = threading.Lock()
164
+ return pipeline
165
+
166
+ from mvdiffusion.data.single_image_dataset import SingleImageDataset
167
+ def prepare_data(single_image, crop_size):
168
+ dataset = SingleImageDataset(
169
+ root_dir = None,
170
+ num_views = 6,
171
+ img_wh=[256, 256],
172
+ bg_color='white',
173
+ crop_size=crop_size,
174
+ single_image=single_image
175
+ )
176
+ return dataset[0]
177
+
178
+
179
+ def run_pipeline(pipeline, cfg, single_image, guidance_scale, steps, seed, crop_size):
180
+ import pdb
181
+ # pdb.set_trace()
182
+
183
+ batch = prepare_data(single_image, crop_size)
184
+
185
+ pipeline.set_progress_bar_config(disable=True)
186
+ seed = int(seed)
187
+ generator = torch.Generator(device=pipeline.unet.device).manual_seed(seed)
188
+
189
+ # repeat (2B, Nv, 3, H, W)
190
+ imgs_in = torch.cat([batch['imgs_in']]*2, dim=0).to(weight_dtype)
191
+
192
+ # (2B, Nv, Nce)
193
+ camera_embeddings = torch.cat([batch['camera_embeddings']]*2, dim=0).to(weight_dtype)
194
+
195
+ task_embeddings = torch.cat([batch['normal_task_embeddings'], batch['color_task_embeddings']], dim=0).to(weight_dtype)
196
+
197
+ camera_embeddings = torch.cat([camera_embeddings, task_embeddings], dim=-1).to(weight_dtype)
198
+
199
+ # (B*Nv, 3, H, W)
200
+ imgs_in = rearrange(imgs_in, "Nv C H W -> (Nv) C H W")
201
+ # (B*Nv, Nce)
202
+ # camera_embeddings = rearrange(camera_embeddings, "B Nv Nce -> (B Nv) Nce")
203
+
204
+ out = pipeline(
205
+ imgs_in, camera_embeddings, generator=generator, guidance_scale=guidance_scale,
206
+ num_inference_steps=steps,
207
+ output_type='pt', num_images_per_prompt=1, **cfg.pipe_validation_kwargs
208
+ ).images
209
+
210
+ bsz = out.shape[0] // 2
211
+ normals_pred = out[:bsz]
212
+ images_pred = out[bsz:]
213
+
214
+ normals_pred = [save_image(normals_pred[i]) for i in range(bsz)]
215
+ images_pred = [save_image(images_pred[i]) for i in range(bsz)]
216
+
217
+ out = images_pred + normals_pred
218
+ return out
219
+
220
+
221
+ @dataclass
222
+ class TestConfig:
223
+ pretrained_model_name_or_path: str
224
+ pretrained_unet_path:str
225
+ revision: Optional[str]
226
+ validation_dataset: Dict
227
+ save_dir: str
228
+ seed: Optional[int]
229
+ validation_batch_size: int
230
+ dataloader_num_workers: int
231
+
232
+ local_rank: int
233
+
234
+ pipe_kwargs: Dict
235
+ pipe_validation_kwargs: Dict
236
+ unet_from_pretrained_kwargs: Dict
237
+ validation_guidance_scales: List[float]
238
+ validation_grid_nrow: int
239
+ camera_embedding_lr_mult: float
240
+
241
+ num_views: int
242
+ camera_embedding_type: str
243
+
244
+ pred_type: str # joint, or ablation
245
+
246
+ enable_xformers_memory_efficient_attention: bool
247
+
248
+ cond_on_normals: bool
249
+ cond_on_colors: bool
250
+
251
+
252
+ def run_demo():
253
+ from utils.misc import load_config
254
+ from omegaconf import OmegaConf
255
+ # parse YAML config to OmegaConf
256
+ cfg = load_config("./configs/mvdiffusion-joint-ortho-6views.yaml")
257
+ # print(cfg)
258
+ schema = OmegaConf.structured(TestConfig)
259
+ cfg = OmegaConf.merge(schema, cfg)
260
+
261
+ pipeline = load_wonder3d_pipeline(cfg)
262
+ torch.set_grad_enabled(False)
263
+ pipeline.to(f'cuda:{_GPU_ID}')
264
+
265
+ predictor = sam_init()
266
+
267
+ custom_theme = gr.themes.Soft(primary_hue="blue").set(
268
+ button_secondary_background_fill="*neutral_100",
269
+ button_secondary_background_fill_hover="*neutral_200")
270
+ custom_css = '''#disp_image {
271
+ text-align: center; /* Horizontally center the content */
272
+ }'''
273
+
274
+ with gr.Blocks(title=_TITLE, theme=custom_theme, css=custom_css) as demo:
275
+ with gr.Row():
276
+ with gr.Column(scale=1):
277
+ gr.Markdown('# ' + _TITLE)
278
+ gr.Markdown(_DESCRIPTION)
279
+ with gr.Row(variant='panel'):
280
+ with gr.Column(scale=1):
281
+ input_image = gr.Image(type='pil', image_mode='RGBA', height=320, label='Input image', tool=None)
282
+
283
+ example_folder = os.path.join(os.path.dirname(__file__), "./example_images")
284
+ example_fns = [os.path.join(example_folder, example) for example in os.listdir(example_folder)]
285
+ gr.Examples(
286
+ examples=example_fns,
287
+ inputs=[input_image],
288
+ outputs=[input_image],
289
+ cache_examples=False,
290
+ label='Examples (click one of the images below to start)',
291
+ examples_per_page=30
292
+ )
293
+ with gr.Column(scale=1):
294
+ processed_image = gr.Image(type='pil', label="Processed Image", interactive=False, height=320, tool=None, image_mode='RGBA', elem_id="disp_image")
295
+ processed_image_highres = gr.Image(type='pil', image_mode='RGBA', visible=False, tool=None)
296
+
297
+ with gr.Accordion('Advanced options', open=True):
298
+ with gr.Row():
299
+ with gr.Column():
300
+ input_processing = gr.CheckboxGroup(['Background Removal'], label='Input Image Preprocessing', value=['Background Removal'])
301
+ with gr.Column():
302
+ output_processing = gr.CheckboxGroup(['Background Removal'], label='Output Image Postprocessing', value=[])
303
+ with gr.Row():
304
+ with gr.Column():
305
+ scale_slider = gr.Slider(1, 10, value=3, step=1,
306
+ label='Classifier Free Guidance Scale')
307
+ with gr.Column():
308
+ steps_slider = gr.Slider(15, 100, value=50, step=1,
309
+ label='Number of Diffusion Inference Steps')
310
+ with gr.Row():
311
+ with gr.Column():
312
+ seed = gr.Number(42, label='Seed')
313
+ with gr.Column():
314
+ crop_size = gr.Number(192, label='Crop size')
315
+ # crop_size = 192
316
+ run_btn = gr.Button('Generate', variant='primary', interactive=True)
317
+ with gr.Row():
318
+ view_1 = gr.Image(interactive=False, height=240, show_label=False)
319
+ view_2 = gr.Image(interactive=False, height=240, show_label=False)
320
+ view_3 = gr.Image(interactive=False, height=240, show_label=False)
321
+ view_4 = gr.Image(interactive=False, height=240, show_label=False)
322
+ view_5 = gr.Image(interactive=False, height=240, show_label=False)
323
+ view_6 = gr.Image(interactive=False, height=240, show_label=False)
324
+ with gr.Row():
325
+ normal_1 = gr.Image(interactive=False, height=240, show_label=False)
326
+ normal_2 = gr.Image(interactive=False, height=240, show_label=False)
327
+ normal_3 = gr.Image(interactive=False, height=240, show_label=False)
328
+ normal_4 = gr.Image(interactive=False, height=240, show_label=False)
329
+ normal_5 = gr.Image(interactive=False, height=240, show_label=False)
330
+ normal_6 = gr.Image(interactive=False, height=240, show_label=False)
331
+
332
+
333
+ first_stage = run_btn.click(fn=partial(preprocess, predictor),
334
+ inputs=[input_image, input_processing],
335
+ outputs=[processed_image_highres, processed_image], queue=True
336
+ )
337
+
338
+
339
+ first_stage.success(fn=partial(run_pipeline, pipeline, cfg),
340
+ inputs=[processed_image_highres, scale_slider, steps_slider, seed, crop_size],
341
+ outputs=[view_1, view_2, view_3, view_4, view_5, view_6, normal_1, normal_2, normal_3, normal_4, normal_5, normal_6]
342
+ )
343
+
344
+ demo.queue().launch(share=True, max_threads=80)
345
+
346
+
347
+ if __name__ == '__main__':
348
+ fire.Fire(run_demo)