🎨 Redesign from AnyCoder

#4
by Stable-X - opened
Files changed (1) hide show
  1. app.py +0 -445
app.py CHANGED
@@ -1,445 +0,0 @@
1
- import gradio as gr
2
- import spaces
3
- from gradio_litmodel3d import LitModel3D
4
-
5
- import os
6
- import shutil
7
- os.environ['SPCONV_ALGO'] = 'native'
8
- from typing import *
9
- import torch
10
- import numpy as np
11
- import imageio
12
- from easydict import EasyDict as edict
13
- from PIL import Image
14
- from trellis.pipelines import TrellisVGGTTo3DPipeline
15
- from trellis.representations import Gaussian, MeshExtractResult
16
- from trellis.utils import render_utils, postprocessing_utils
17
-
18
-
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
22
- # TMP_DIR = "tmp/Trellis-demo"
23
- # os.environ['GRADIO_TEMP_DIR'] = 'tmp'
24
- os.makedirs(TMP_DIR, exist_ok=True)
25
-
26
- def start_session(req: gr.Request):
27
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
28
- os.makedirs(user_dir, exist_ok=True)
29
-
30
-
31
- def end_session(req: gr.Request):
32
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
33
- shutil.rmtree(user_dir)
34
-
35
- @spaces.GPU
36
- def preprocess_image(image: Image.Image) -> Image.Image:
37
- """
38
- Preprocess the input image for 3D generation.
39
-
40
- This function is called when a user uploads an image or selects an example.
41
- It applies background removal and other preprocessing steps necessary for
42
- optimal 3D model generation.
43
-
44
- Args:
45
- image (Image.Image): The input image from the user
46
-
47
- Returns:
48
- Image.Image: The preprocessed image ready for 3D generation
49
- """
50
- processed_image = pipeline.preprocess_image(image)
51
- return processed_image
52
-
53
- @spaces.GPU
54
- def preprocess_videos(video: str) -> List[Tuple[Image.Image, str]]:
55
- """
56
- Preprocess the input video for multi-image 3D generation.
57
-
58
- This function is called when a user uploads a video.
59
- It extracts frames from the video and processes each frame to prepare them
60
- for the multi-image 3D generation pipeline.
61
-
62
- Args:
63
- video (str): The path to the input video file
64
-
65
- Returns:
66
- List[Tuple[Image.Image, str]]: The list of preprocessed images ready for 3D generation
67
- """
68
- vid = imageio.get_reader(video, 'ffmpeg')
69
- fps = vid.get_meta_data()['fps']
70
- images = []
71
- for i, frame in enumerate(vid):
72
- if i % max(int(fps * 1), 1) == 0:
73
- img = Image.fromarray(frame)
74
- W, H = img.size
75
- img = img.resize((int(W / H * 512), 512))
76
- images.append(img)
77
- vid.close()
78
- processed_images = [pipeline.preprocess_image(image) for image in images]
79
- return processed_images
80
-
81
- @spaces.GPU
82
- def preprocess_images(images: List[Tuple[Image.Image, str]]) -> List[Image.Image]:
83
- """
84
- Preprocess a list of input images for multi-image 3D generation.
85
-
86
- This function is called when users upload multiple images in the gallery.
87
- It processes each image to prepare them for the multi-image 3D generation pipeline.
88
-
89
- Args:
90
- images (List[Tuple[Image.Image, str]]): The input images from the gallery
91
-
92
- Returns:
93
- List[Image.Image]: The preprocessed images ready for 3D generation
94
- """
95
- images = [image[0] for image in images]
96
- processed_images = [pipeline.preprocess_image(image) for image in images]
97
- return processed_images
98
-
99
-
100
- def pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:
101
- return {
102
- 'gaussian': {
103
- **gs.init_params,
104
- '_xyz': gs._xyz.cpu().numpy(),
105
- '_features_dc': gs._features_dc.cpu().numpy(),
106
- '_scaling': gs._scaling.cpu().numpy(),
107
- '_rotation': gs._rotation.cpu().numpy(),
108
- '_opacity': gs._opacity.cpu().numpy(),
109
- },
110
- 'mesh': {
111
- 'vertices': mesh.vertices.cpu().numpy(),
112
- 'faces': mesh.faces.cpu().numpy(),
113
- },
114
- }
115
-
116
-
117
- def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:
118
- gs = Gaussian(
119
- aabb=state['gaussian']['aabb'],
120
- sh_degree=state['gaussian']['sh_degree'],
121
- mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
122
- scaling_bias=state['gaussian']['scaling_bias'],
123
- opacity_bias=state['gaussian']['opacity_bias'],
124
- scaling_activation=state['gaussian']['scaling_activation'],
125
- )
126
- gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')
127
- gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')
128
- gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
129
- gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
130
- gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
131
-
132
- mesh = edict(
133
- vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
134
- faces=torch.tensor(state['mesh']['faces'], device='cuda'),
135
- )
136
-
137
- return gs, mesh
138
-
139
-
140
- def get_seed(randomize_seed: bool, seed: int) -> int:
141
- """
142
- Get the random seed for generation.
143
-
144
- This function is called by the generate button to determine whether to use
145
- a random seed or the user-specified seed value.
146
-
147
- Args:
148
- randomize_seed (bool): Whether to generate a random seed
149
- seed (int): The user-specified seed value
150
-
151
- Returns:
152
- int: The seed to use for generation
153
- """
154
- return np.random.randint(0, MAX_SEED) if randomize_seed else seed
155
-
156
-
157
- @spaces.GPU(duration=120)
158
- def generate_and_extract_glb(
159
- multiimages: List[Tuple[Image.Image, str]],
160
- seed: int,
161
- ss_guidance_strength: float,
162
- ss_sampling_steps: int,
163
- slat_guidance_strength: float,
164
- slat_sampling_steps: int,
165
- multiimage_algo: Literal["multidiffusion", "stochastic"],
166
- mesh_simplify: float,
167
- texture_size: int,
168
- req: gr.Request,
169
- ) -> Tuple[dict, str, str, str]:
170
- """
171
- Convert an image to a 3D model and extract GLB file.
172
-
173
- Args:
174
- image (Image.Image): The input image.
175
- multiimages (List[Tuple[Image.Image, str]]): The input images in multi-image mode.
176
- is_multiimage (bool): Whether is in multi-image mode.
177
- seed (int): The random seed.
178
- ss_guidance_strength (float): The guidance strength for sparse structure generation.
179
- ss_sampling_steps (int): The number of sampling steps for sparse structure generation.
180
- slat_guidance_strength (float): The guidance strength for structured latent generation.
181
- slat_sampling_steps (int): The number of sampling steps for structured latent generation.
182
- multiimage_algo (Literal["multidiffusion", "stochastic"]): The algorithm for multi-image generation.
183
- mesh_simplify (float): The mesh simplification factor.
184
- texture_size (int): The texture resolution.
185
-
186
- Returns:
187
- dict: The information of the generated 3D model.
188
- str: The path to the video of the 3D model.
189
- str: The path to the extracted GLB file.
190
- str: The path to the extracted GLB file (for download).
191
- """
192
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
193
- image_files = [image[0] for image in multiimages]
194
-
195
- # Generate 3D model
196
- outputs, _, _ = pipeline.run(
197
- image=image_files,
198
- seed=seed,
199
- formats=["gaussian", "mesh"],
200
- preprocess_image=False,
201
- sparse_structure_sampler_params={
202
- "steps": ss_sampling_steps,
203
- "cfg_strength": ss_guidance_strength,
204
- },
205
- slat_sampler_params={
206
- "steps": slat_sampling_steps,
207
- "cfg_strength": slat_guidance_strength,
208
- },
209
- mode=multiimage_algo,
210
- )
211
-
212
- # Render video
213
- # import uuid
214
- # output_id = str(uuid.uuid4())
215
- # os.makedirs(f"{TMP_DIR}/{output_id}", exist_ok=True)
216
- # video_path = f"{TMP_DIR}/{output_id}/preview.mp4"
217
- # glb_path = f"{TMP_DIR}/{output_id}/mesh.glb"
218
-
219
- video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']
220
- video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']
221
- video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
222
- video_path = os.path.join(user_dir, 'sample.mp4')
223
- imageio.mimsave(video_path, video, fps=15)
224
-
225
- # Extract GLB
226
- gs = outputs['gaussian'][0]
227
- mesh = outputs['mesh'][0]
228
- glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
229
- glb_path = os.path.join(user_dir, 'sample.glb')
230
- glb.export(glb_path)
231
-
232
- # Pack state for optional Gaussian extraction
233
- state = pack_state(gs, mesh)
234
-
235
- torch.cuda.empty_cache()
236
- return state, video_path, glb_path, glb_path
237
-
238
-
239
- @spaces.GPU
240
- def extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:
241
- """
242
- Extract a Gaussian splatting file from the generated 3D model.
243
-
244
- This function is called when the user clicks "Extract Gaussian" button.
245
- It converts the 3D model state into a .ply file format containing
246
- Gaussian splatting data for advanced 3D applications.
247
-
248
- Args:
249
- state (dict): The state of the generated 3D model containing Gaussian data
250
- req (gr.Request): Gradio request object for session management
251
-
252
- Returns:
253
- Tuple[str, str]: Paths to the extracted Gaussian file (for display and download)
254
- """
255
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
256
- gs, _ = unpack_state(state)
257
- gaussian_path = os.path.join(user_dir, 'sample.ply')
258
- gs.save_ply(gaussian_path)
259
- torch.cuda.empty_cache()
260
- return gaussian_path, gaussian_path
261
-
262
-
263
- def prepare_multi_example() -> List[Image.Image]:
264
- multi_case = list(set([i.split('_')[0] for i in os.listdir("assets/example_multi_image")]))
265
- images = []
266
- for case in multi_case:
267
- _images = []
268
- for i in range(1, 9):
269
- if os.path.exists(f'assets/example_multi_image/{case}_{i}.png'):
270
- img = Image.open(f'assets/example_multi_image/{case}_{i}.png')
271
- W, H = img.size
272
- img = img.resize((int(W / H * 512), 512))
273
- _images.append(np.array(img))
274
- if len(_images) > 0:
275
- images.append(Image.fromarray(np.concatenate(_images, axis=1)))
276
- return images
277
-
278
-
279
- def split_image(image: Image.Image) -> List[Image.Image]:
280
- """
281
- Split a multi-view image into separate view images.
282
-
283
- This function is called when users select multi-image examples that contain
284
- multiple views in a single concatenated image. It automatically splits them
285
- based on alpha channel boundaries and preprocesses each view.
286
-
287
- Args:
288
- image (Image.Image): A concatenated image containing multiple views
289
-
290
- Returns:
291
- List[Image.Image]: List of individual preprocessed view images
292
- """
293
- image = np.array(image)
294
- alpha = image[..., 3]
295
- alpha = np.any(alpha>0, axis=0)
296
- start_pos = np.where(~alpha[:-1] & alpha[1:])[0].tolist()
297
- end_pos = np.where(alpha[:-1] & ~alpha[1:])[0].tolist()
298
- images = []
299
- for s, e in zip(start_pos, end_pos):
300
- images.append(Image.fromarray(image[:, s:e+1]))
301
- return [preprocess_image(image) for image in images]
302
-
303
- # Create interface
304
- demo = gr.Blocks(
305
- title="ReconViaGen",
306
- css="""
307
- .slider .inner { width: 5px; background: #FFF; }
308
- .viewport { aspect-ratio: 4/3; }
309
- .tabs button.selected { font-size: 20px !important; color: crimson !important; }
310
- h1, h2, h3 { text-align: center; display: block; }
311
- .md_feedback li { margin-bottom: 0px !important; }
312
- """
313
- )
314
- with demo:
315
- gr.Markdown("""
316
- # πŸ’» ReconViaGen
317
- <p align="center">
318
- <a title="Github" href="https://github.com/GAP-LAB-CUHK-SZ/ReconViaGen" target="_blank" rel="noopener noreferrer" style="display: inline-block;">
319
- <img src="https://img.shields.io/github/stars/GAP-LAB-CUHK-SZ/ReconViaGen?label=GitHub%20%E2%98%85&logo=github&color=C8C" alt="badge-github-stars">
320
- </a>
321
- <a title="Website" href="https://jiahao620.github.io/reconviagen/" target="_blank" rel="noopener noreferrer" style="display: inline-block;">
322
- <img src="https://www.obukhov.ai/img/badges/badge-website.svg">
323
- </a>
324
- <a title="arXiv" href="https://jiahao620.github.io/reconviagen/" target="_blank" rel="noopener noreferrer" style="display: inline-block;">
325
- <img src="https://www.obukhov.ai/img/badges/badge-pdf.svg">
326
- </a>
327
- </p>
328
-
329
- ✨This demo is partial. We will release the whole model later. Stay tuned!✨
330
- """)
331
-
332
- with gr.Row():
333
- with gr.Column():
334
- with gr.Tabs() as input_tabs:
335
- with gr.Tab(label="Input Video or Images", id=0) as multiimage_input_tab:
336
- input_video = gr.Video(label="Upload Video", interactive=True, height=300)
337
- image_prompt = gr.Image(label="Image Prompt", format="png", visible=False, image_mode="RGBA", type="pil", height=300)
338
- multiimage_prompt = gr.Gallery(label="Image Prompt", format="png", type="pil", height=300, columns=3)
339
- gr.Markdown("""
340
- Input different views of the object in separate images.
341
- """)
342
-
343
- with gr.Accordion(label="Generation Settings", open=False):
344
- seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)
345
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=False)
346
- gr.Markdown("Stage 1: Sparse Structure Generation")
347
- with gr.Row():
348
- ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
349
- ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=30, step=1)
350
- gr.Markdown("Stage 2: Structured Latent Generation")
351
- with gr.Row():
352
- slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
353
- slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
354
- multiimage_algo = gr.Radio(["stochastic", "multidiffusion"], label="Multi-image Algorithm", value="multidiffusion")
355
-
356
- with gr.Accordion(label="GLB Extraction Settings", open=False):
357
- mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)
358
- texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)
359
-
360
- generate_btn = gr.Button("Generate & Extract GLB", variant="primary")
361
- extract_gs_btn = gr.Button("Extract Gaussian", interactive=False)
362
- gr.Markdown("""
363
- *NOTE: Gaussian file can be very large (~50MB), it will take a while to display and download.*
364
- """)
365
-
366
- with gr.Column():
367
- video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)
368
- model_output = LitModel3D(label="Extracted GLB/Gaussian", exposure=10.0, height=300)
369
-
370
- with gr.Row():
371
- download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
372
- download_gs = gr.DownloadButton(label="Download Gaussian", interactive=False)
373
-
374
- output_buf = gr.State()
375
-
376
- # Example images at the bottom of the page
377
- with gr.Row() as multiimage_example:
378
- examples_multi = gr.Examples(
379
- examples=prepare_multi_example(),
380
- inputs=[image_prompt],
381
- fn=split_image,
382
- outputs=[multiimage_prompt],
383
- run_on_click=True,
384
- examples_per_page=8,
385
- )
386
-
387
- # Handlers
388
- demo.load(start_session)
389
- demo.unload(end_session)
390
-
391
- input_video.upload(
392
- preprocess_videos,
393
- inputs=[input_video],
394
- outputs=[multiimage_prompt],
395
- )
396
- input_video.clear(
397
- lambda: tuple([None, None]),
398
- outputs=[input_video, multiimage_prompt],
399
- )
400
- multiimage_prompt.upload(
401
- preprocess_images,
402
- inputs=[multiimage_prompt],
403
- outputs=[multiimage_prompt],
404
- )
405
-
406
- generate_btn.click(
407
- get_seed,
408
- inputs=[randomize_seed, seed],
409
- outputs=[seed],
410
- ).then(
411
- generate_and_extract_glb,
412
- inputs=[multiimage_prompt, seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps, multiimage_algo, mesh_simplify, texture_size],
413
- outputs=[output_buf, video_output, model_output, download_glb],
414
- ).then(
415
- lambda: tuple([gr.Button(interactive=True), gr.Button(interactive=True)]),
416
- outputs=[extract_gs_btn, download_glb],
417
- )
418
-
419
- video_output.clear(
420
- lambda: tuple([gr.Button(interactive=False), gr.Button(interactive=False), gr.Button(interactive=False)]),
421
- outputs=[extract_gs_btn, download_glb, download_gs],
422
- )
423
-
424
- extract_gs_btn.click(
425
- extract_gaussian,
426
- inputs=[output_buf],
427
- outputs=[model_output, download_gs],
428
- ).then(
429
- lambda: gr.Button(interactive=True),
430
- outputs=[download_gs],
431
- )
432
-
433
- model_output.clear(
434
- lambda: tuple([gr.Button(interactive=False), gr.Button(interactive=False)]),
435
- outputs=[download_glb, download_gs],
436
- )
437
-
438
-
439
- # Launch the Gradio app
440
- if __name__ == "__main__":
441
- pipeline = TrellisVGGTTo3DPipeline.from_pretrained("Stable-X/trellis-vggt-v0-2")
442
- pipeline.cuda()
443
- pipeline.VGGT_model.cuda()
444
- pipeline.birefnet_model.cuda()
445
- demo.launch()