Nikhil0987 commited on
Commit
4b30385
1 Parent(s): 1939ee1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +407 -132
app.py CHANGED
@@ -1,146 +1,421 @@
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
-
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
-
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
20
-
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
22
-
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
- return image
39
-
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
44
  ]
45
 
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
- }
51
- """
52
-
53
- if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
57
-
58
- with gr.Blocks(css=css) as demo:
59
-
60
- with gr.Column(elem_id="col-container"):
61
- gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
- """)
65
-
66
- with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
-
76
- run_button = gr.Button("Run", scale=0)
77
-
78
- result = gr.Image(label="Result", show_label=False)
79
-
80
- with gr.Accordion("Advanced Settings", open=False):
81
-
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
  )
88
-
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  )
96
-
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
98
-
99
- with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
125
  )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
131
- step=1,
132
- value=2,
133
  )
134
-
135
- gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
138
- )
139
 
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  )
145
 
146
- demo.queue().launch()
 
1
+ import os
2
+ import tempfile
3
+ import time
4
+ from contextlib import nullcontext
5
+ from functools import lru_cache
6
+ from typing import Any
7
+
8
  import gradio as gr
9
  import numpy as np
10
+ import rembg
 
11
  import torch
12
+ from gradio_litmodel3d import LitModel3D
13
+ from PIL import Image
14
+
15
+ import sf3d.utils as sf3d_utils
16
+ from sf3d.system import SF3D
17
+
18
+ os.environ["GRADIO_TEMP_DIR"] = os.path.join(os.environ.get("TMPDIR", "/tmp"), "gradio")
19
+
20
+ rembg_session = rembg.new_session()
21
+
22
+ COND_WIDTH = 512
23
+ COND_HEIGHT = 512
24
+ COND_DISTANCE = 1.6
25
+ COND_FOVY_DEG = 40
26
+ BACKGROUND_COLOR = [0.5, 0.5, 0.5]
27
+
28
+ # Cached. Doesn't change
29
+ c2w_cond = sf3d_utils.default_cond_c2w(COND_DISTANCE)
30
+ intrinsic, intrinsic_normed_cond = sf3d_utils.create_intrinsic_from_fov_deg(
31
+ COND_FOVY_DEG, COND_HEIGHT, COND_WIDTH
32
+ )
33
+
34
+ generated_files = []
35
+
36
+ # Delete previous gradio temp dir folder
37
+ if os.path.exists(os.environ["GRADIO_TEMP_DIR"]):
38
+ print(f"Deleting {os.environ['GRADIO_TEMP_DIR']}")
39
+ import shutil
40
+
41
+ shutil.rmtree(os.environ["GRADIO_TEMP_DIR"])
42
+
43
+ device = sf3d_utils.get_device()
44
+
45
+ model = SF3D.from_pretrained(
46
+ "stabilityai/stable-fast-3d",
47
+ config_name="config.yaml",
48
+ weight_name="model.safetensors",
49
+ )
50
+ model.eval()
51
+ model = model.to(device)
52
 
53
+ example_files = [
54
+ os.path.join("demo_files/examples", f) for f in os.listdir("demo_files/examples")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  ]
56
 
57
+
58
+ def run_model(input_image, remesh_option, vertex_count, texture_size):
59
+ start = time.time()
60
+ with torch.no_grad():
61
+ with torch.autocast(
62
+ device_type=device, dtype=torch.float16
63
+ ) if "cuda" in device else nullcontext():
64
+ model_batch = create_batch(input_image)
65
+ model_batch = {k: v.to(device) for k, v in model_batch.items()}
66
+ trimesh_mesh, _glob_dict = model.generate_mesh(
67
+ model_batch, texture_size, remesh_option, vertex_count
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  )
69
+ trimesh_mesh = trimesh_mesh[0]
70
+
71
+ # Create new tmp file
72
+ tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".glb")
73
+
74
+ trimesh_mesh.export(tmp_file.name, file_type="glb", include_normals=True)
75
+ generated_files.append(tmp_file.name)
76
+
77
+ print("Generation took:", time.time() - start, "s")
78
+
79
+ return tmp_file.name
80
+
81
+
82
+ def create_batch(input_image: Image) -> dict[str, Any]:
83
+ img_cond = (
84
+ torch.from_numpy(
85
+ np.asarray(input_image.resize((COND_WIDTH, COND_HEIGHT))).astype(np.float32)
86
+ / 255.0
87
+ )
88
+ .float()
89
+ .clip(0, 1)
90
+ )
91
+ mask_cond = img_cond[:, :, -1:]
92
+ rgb_cond = torch.lerp(
93
+ torch.tensor(BACKGROUND_COLOR)[None, None, :], img_cond[:, :, :3], mask_cond
94
+ )
95
+
96
+ batch_elem = {
97
+ "rgb_cond": rgb_cond,
98
+ "mask_cond": mask_cond,
99
+ "c2w_cond": c2w_cond.unsqueeze(0),
100
+ "intrinsic_cond": intrinsic.unsqueeze(0),
101
+ "intrinsic_normed_cond": intrinsic_normed_cond.unsqueeze(0),
102
+ }
103
+ # Add batch dim
104
+ batched = {k: v.unsqueeze(0) for k, v in batch_elem.items()}
105
+ return batched
106
+
107
+
108
+ @lru_cache
109
+ def checkerboard(squares: int, size: int, min_value: float = 0.5):
110
+ base = np.zeros((squares, squares)) + min_value
111
+ base[1::2, ::2] = 1
112
+ base[::2, 1::2] = 1
113
+
114
+ repeat_mult = size // squares
115
+ return (
116
+ base.repeat(repeat_mult, axis=0)
117
+ .repeat(repeat_mult, axis=1)[:, :, None]
118
+ .repeat(3, axis=-1)
119
+ )
120
+
121
+
122
+ def remove_background(input_image: Image) -> Image:
123
+ return rembg.remove(input_image, session=rembg_session)
124
+
125
+
126
+ def resize_foreground(
127
+ image: Image,
128
+ ratio: float,
129
+ ) -> Image:
130
+ image = np.array(image)
131
+ assert image.shape[-1] == 4
132
+ alpha = np.where(image[..., 3] > 0)
133
+ y1, y2, x1, x2 = (
134
+ alpha[0].min(),
135
+ alpha[0].max(),
136
+ alpha[1].min(),
137
+ alpha[1].max(),
138
+ )
139
+ # crop the foreground
140
+ fg = image[y1:y2, x1:x2]
141
+ # pad to square
142
+ size = max(fg.shape[0], fg.shape[1])
143
+ ph0, pw0 = (size - fg.shape[0]) // 2, (size - fg.shape[1]) // 2
144
+ ph1, pw1 = size - fg.shape[0] - ph0, size - fg.shape[1] - pw0
145
+ new_image = np.pad(
146
+ fg,
147
+ ((ph0, ph1), (pw0, pw1), (0, 0)),
148
+ mode="constant",
149
+ constant_values=((0, 0), (0, 0), (0, 0)),
150
+ )
151
+
152
+ # compute padding according to the ratio
153
+ new_size = int(new_image.shape[0] / ratio)
154
+ # pad to size, double side
155
+ ph0, pw0 = (new_size - size) // 2, (new_size - size) // 2
156
+ ph1, pw1 = new_size - size - ph0, new_size - size - pw0
157
+ new_image = np.pad(
158
+ new_image,
159
+ ((ph0, ph1), (pw0, pw1), (0, 0)),
160
+ mode="constant",
161
+ constant_values=((0, 0), (0, 0), (0, 0)),
162
+ )
163
+ new_image = Image.fromarray(new_image, mode="RGBA").resize(
164
+ (COND_WIDTH, COND_HEIGHT)
165
+ )
166
+ return new_image
167
+
168
+
169
+ def square_crop(input_image: Image) -> Image:
170
+ # Perform a center square crop
171
+ min_size = min(input_image.size)
172
+ left = (input_image.size[0] - min_size) // 2
173
+ top = (input_image.size[1] - min_size) // 2
174
+ right = (input_image.size[0] + min_size) // 2
175
+ bottom = (input_image.size[1] + min_size) // 2
176
+ return input_image.crop((left, top, right, bottom)).resize(
177
+ (COND_WIDTH, COND_HEIGHT)
178
+ )
179
+
180
+
181
+ def show_mask_img(input_image: Image) -> Image:
182
+ img_numpy = np.array(input_image)
183
+ alpha = img_numpy[:, :, 3] / 255.0
184
+ chkb = checkerboard(32, 512) * 255
185
+ new_img = img_numpy[..., :3] * alpha[:, :, None] + chkb * (1 - alpha[:, :, None])
186
+ return Image.fromarray(new_img.astype(np.uint8), mode="RGB")
187
+
188
+
189
+ def run_button(
190
+ run_btn,
191
+ input_image,
192
+ background_state,
193
+ foreground_ratio,
194
+ remesh_option,
195
+ vertex_count,
196
+ texture_size,
197
+ ):
198
+ if run_btn == "Run":
199
+ if torch.cuda.is_available():
200
+ torch.cuda.reset_peak_memory_stats()
201
+ glb_file: str = run_model(
202
+ background_state, remesh_option.lower(), vertex_count, texture_size
203
+ )
204
+ if torch.cuda.is_available():
205
+ print("Peak Memory:", torch.cuda.max_memory_allocated() / 1024 / 1024, "MB")
206
+ elif torch.backends.mps.is_available():
207
+ print(
208
+ "Peak Memory:", torch.mps.driver_allocated_memory() / 1024 / 1024, "MB"
209
  )
210
+
211
+ return (
212
+ gr.update(),
213
+ gr.update(),
214
+ gr.update(),
215
+ gr.update(),
216
+ gr.update(value=glb_file, visible=True),
217
+ gr.update(visible=True),
218
+ )
219
+ elif run_btn == "Remove Background":
220
+ rem_removed = remove_background(input_image)
221
+
222
+ sqr_crop = square_crop(rem_removed)
223
+ fr_res = resize_foreground(sqr_crop, foreground_ratio)
224
+
225
+ return (
226
+ gr.update(value="Run", visible=True),
227
+ sqr_crop,
228
+ fr_res,
229
+ gr.update(value=show_mask_img(fr_res), visible=True),
230
+ gr.update(value=None, visible=False),
231
+ gr.update(visible=False),
232
+ )
233
+
234
+
235
+ def requires_bg_remove(image, fr):
236
+ if image is None:
237
+ return (
238
+ gr.update(visible=False, value="Run"),
239
+ None,
240
+ None,
241
+ gr.update(value=None, visible=False),
242
+ gr.update(visible=False),
243
+ gr.update(visible=False),
244
+ )
245
+ alpha_channel = np.array(image.getchannel("A"))
246
+ min_alpha = alpha_channel.min()
247
+
248
+ if min_alpha == 0:
249
+ print("Already has alpha")
250
+ sqr_crop = square_crop(image)
251
+ fr_res = resize_foreground(sqr_crop, fr)
252
+ return (
253
+ gr.update(value="Run", visible=True),
254
+ sqr_crop,
255
+ fr_res,
256
+ gr.update(value=show_mask_img(fr_res), visible=True),
257
+ gr.update(visible=False),
258
+ gr.update(visible=False),
259
+ )
260
+ return (
261
+ gr.update(value="Remove Background", visible=True),
262
+ None,
263
+ None,
264
+ gr.update(value=None, visible=False),
265
+ gr.update(visible=False),
266
+ gr.update(visible=False),
267
+ )
268
+
269
+
270
+ def update_foreground_ratio(img_proc, fr):
271
+ foreground_res = resize_foreground(img_proc, fr)
272
+ return (
273
+ foreground_res,
274
+ gr.update(value=show_mask_img(foreground_res)),
275
+ )
276
+
277
+
278
+ with gr.Blocks() as demo:
279
+ img_proc_state = gr.State()
280
+ background_remove_state = gr.State()
281
+ gr.Markdown("""
282
+ # SF3D: Stable Fast 3D Mesh Reconstruction with UV-unwrapping and Illumination Disentanglement
283
+
284
+ **SF3D** is a state-of-the-art method for 3D mesh reconstruction from a single image.
285
+ This demo allows you to upload an image and generate a 3D mesh model from it.
286
+
287
+ **Tips**
288
+ 1. If the image already has an alpha channel, you can skip the background removal step.
289
+ 2. You can adjust the foreground ratio to control the size of the foreground object. This can influence the shape
290
+ 3. You can select the remeshing option to control the mesh topology. This can introduce artifacts in the mesh on thin surfaces and should be turned off in such cases.
291
+ 4. You can upload your own HDR environment map to light the 3D model.
292
+ """)
293
+ with gr.Row(variant="panel"):
294
+ with gr.Column():
295
  with gr.Row():
296
+ input_img = gr.Image(
297
+ type="pil", label="Input Image", sources="upload", image_mode="RGBA"
 
 
 
 
 
298
  )
299
+ preview_removal = gr.Image(
300
+ label="Preview Background Removal",
301
+ type="pil",
302
+ image_mode="RGB",
303
+ interactive=False,
304
+ visible=False,
 
305
  )
 
 
 
 
 
306
 
307
+ foreground_ratio = gr.Slider(
308
+ label="Foreground Ratio",
309
+ minimum=0.5,
310
+ maximum=1.0,
311
+ value=0.85,
312
+ step=0.05,
313
+ )
314
+
315
+ foreground_ratio.change(
316
+ update_foreground_ratio,
317
+ inputs=[img_proc_state, foreground_ratio],
318
+ outputs=[background_remove_state, preview_removal],
319
+ )
320
+
321
+ remesh_option = gr.Radio(
322
+ choices=["None", "Triangle", "Quad"],
323
+ label="Remeshing",
324
+ value="None",
325
+ visible=True,
326
+ )
327
+
328
+ vertex_count_slider = gr.Slider(
329
+ label="Target Vertex Count",
330
+ minimum=1000,
331
+ maximum=20000,
332
+ value=10000,
333
+ step=1000,
334
+ visible=True,
335
+ )
336
+
337
+ texture_size = gr.Slider(
338
+ label="Texture Size",
339
+ minimum=512,
340
+ maximum=2048,
341
+ value=1024,
342
+ step=256,
343
+ visible=True,
344
+ )
345
+
346
+ run_btn = gr.Button("Run", variant="primary", visible=False)
347
+
348
+ with gr.Column():
349
+ output_3d = LitModel3D(
350
+ label="3D Model",
351
+ visible=False,
352
+ clear_color=[0.0, 0.0, 0.0, 0.0],
353
+ tonemapping="aces",
354
+ contrast=1.0,
355
+ scale=1.0,
356
+ )
357
+ with gr.Column(visible=False, scale=1.0) as hdr_row:
358
+ gr.Markdown("""## HDR Environment Map
359
+
360
+ Select an HDR environment map to light the 3D model. You can also upload your own HDR environment maps.
361
+ """)
362
+
363
+ with gr.Row():
364
+ hdr_illumination_file = gr.File(
365
+ label="HDR Env Map", file_types=[".hdr"], file_count="single"
366
+ )
367
+ example_hdris = [
368
+ os.path.join("demo_files/hdri", f)
369
+ for f in os.listdir("demo_files/hdri")
370
+ ]
371
+ hdr_illumination_example = gr.Examples(
372
+ examples=example_hdris,
373
+ inputs=hdr_illumination_file,
374
+ )
375
+
376
+ hdr_illumination_file.change(
377
+ lambda x: gr.update(env_map=x.name if x is not None else None),
378
+ inputs=hdr_illumination_file,
379
+ outputs=[output_3d],
380
+ )
381
+
382
+ examples = gr.Examples(
383
+ examples=example_files,
384
+ inputs=input_img,
385
+ )
386
+
387
+ input_img.change(
388
+ requires_bg_remove,
389
+ inputs=[input_img, foreground_ratio],
390
+ outputs=[
391
+ run_btn,
392
+ img_proc_state,
393
+ background_remove_state,
394
+ preview_removal,
395
+ output_3d,
396
+ hdr_row,
397
+ ],
398
+ )
399
+
400
+ run_btn.click(
401
+ run_button,
402
+ inputs=[
403
+ run_btn,
404
+ input_img,
405
+ background_remove_state,
406
+ foreground_ratio,
407
+ remesh_option,
408
+ vertex_count_slider,
409
+ texture_size,
410
+ ],
411
+ outputs=[
412
+ run_btn,
413
+ img_proc_state,
414
+ background_remove_state,
415
+ preview_removal,
416
+ output_3d,
417
+ hdr_row,
418
+ ],
419
  )
420
 
421
+ demo.queue().launch(share=False)