junbiao.chen commited on
Commit
988efc8
·
1 Parent(s): 31dca24
Files changed (1) hide show
  1. app.py +271 -0
app.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 trellis.pipelines import TrellisTextTo3DPipeline
14
+ from trellis.representations import Gaussian, MeshExtractResult
15
+ from trellis.utils import render_utils, postprocessing_utils
16
+
17
+
18
+ MAX_SEED = np.iinfo(np.int32).max
19
+ TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
20
+ os.makedirs(TMP_DIR, exist_ok=True)
21
+
22
+
23
+ def start_session(req: gr.Request):
24
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
25
+ os.makedirs(user_dir, exist_ok=True)
26
+
27
+
28
+ def end_session(req: gr.Request):
29
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
30
+ shutil.rmtree(user_dir)
31
+
32
+
33
+ def pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:
34
+ return {
35
+ 'gaussian': {
36
+ **gs.init_params,
37
+ '_xyz': gs._xyz.cpu().numpy(),
38
+ '_features_dc': gs._features_dc.cpu().numpy(),
39
+ '_scaling': gs._scaling.cpu().numpy(),
40
+ '_rotation': gs._rotation.cpu().numpy(),
41
+ '_opacity': gs._opacity.cpu().numpy(),
42
+ },
43
+ 'mesh': {
44
+ 'vertices': mesh.vertices.cpu().numpy(),
45
+ 'faces': mesh.faces.cpu().numpy(),
46
+ },
47
+ }
48
+
49
+
50
+ def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:
51
+ gs = Gaussian(
52
+ aabb=state['gaussian']['aabb'],
53
+ sh_degree=state['gaussian']['sh_degree'],
54
+ mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
55
+ scaling_bias=state['gaussian']['scaling_bias'],
56
+ opacity_bias=state['gaussian']['opacity_bias'],
57
+ scaling_activation=state['gaussian']['scaling_activation'],
58
+ )
59
+ gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')
60
+ gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')
61
+ gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
62
+ gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
63
+ gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
64
+
65
+ mesh = edict(
66
+ vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
67
+ faces=torch.tensor(state['mesh']['faces'], device='cuda'),
68
+ )
69
+
70
+ return gs, mesh
71
+
72
+
73
+ def get_seed(randomize_seed: bool, seed: int) -> int:
74
+ """
75
+ Get the random seed.
76
+ """
77
+ return np.random.randint(0, MAX_SEED) if randomize_seed else seed
78
+
79
+
80
+ @spaces.GPU
81
+ def text_to_3d(
82
+ prompt: str,
83
+ seed: int,
84
+ ss_guidance_strength: float,
85
+ ss_sampling_steps: int,
86
+ slat_guidance_strength: float,
87
+ slat_sampling_steps: int,
88
+ req: gr.Request,
89
+ ) -> Tuple[dict, str]:
90
+ """
91
+ Convert an text prompt to a 3D model.
92
+
93
+ Args:
94
+ prompt (str): The text prompt.
95
+ seed (int): The random seed.
96
+ ss_guidance_strength (float): The guidance strength for sparse structure generation.
97
+ ss_sampling_steps (int): The number of sampling steps for sparse structure generation.
98
+ slat_guidance_strength (float): The guidance strength for structured latent generation.
99
+ slat_sampling_steps (int): The number of sampling steps for structured latent generation.
100
+
101
+ Returns:
102
+ dict: The information of the generated 3D model.
103
+ str: The path to the video of the 3D model.
104
+ """
105
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
106
+ outputs = pipeline.run(
107
+ prompt,
108
+ seed=seed,
109
+ formats=["gaussian", "mesh"],
110
+ sparse_structure_sampler_params={
111
+ "steps": ss_sampling_steps,
112
+ "cfg_strength": ss_guidance_strength,
113
+ },
114
+ slat_sampler_params={
115
+ "steps": slat_sampling_steps,
116
+ "cfg_strength": slat_guidance_strength,
117
+ },
118
+ )
119
+ video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']
120
+ video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']
121
+ video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
122
+ video_path = os.path.join(user_dir, 'sample.mp4')
123
+ imageio.mimsave(video_path, video, fps=15)
124
+ state = pack_state(outputs['gaussian'][0], outputs['mesh'][0])
125
+ torch.cuda.empty_cache()
126
+ return state, video_path
127
+
128
+
129
+ @spaces.GPU(duration=90)
130
+ def extract_glb(
131
+ state: dict,
132
+ mesh_simplify: float,
133
+ texture_size: int,
134
+ req: gr.Request,
135
+ ) -> Tuple[str, str]:
136
+ """
137
+ Extract a GLB file from the 3D model.
138
+
139
+ Args:
140
+ state (dict): The state of the generated 3D model.
141
+ mesh_simplify (float): The mesh simplification factor.
142
+ texture_size (int): The texture resolution.
143
+
144
+ Returns:
145
+ str: The path to the extracted GLB file.
146
+ """
147
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
148
+ gs, mesh = unpack_state(state)
149
+ glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
150
+ glb_path = os.path.join(user_dir, 'sample.glb')
151
+ glb.export(glb_path)
152
+ torch.cuda.empty_cache()
153
+ return glb_path, glb_path
154
+
155
+
156
+ @spaces.GPU
157
+ def extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:
158
+ """
159
+ Extract a Gaussian file from the 3D model.
160
+
161
+ Args:
162
+ state (dict): The state of the generated 3D model.
163
+
164
+ Returns:
165
+ str: The path to the extracted Gaussian file.
166
+ """
167
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
168
+ gs, _ = unpack_state(state)
169
+ gaussian_path = os.path.join(user_dir, 'sample.ply')
170
+ gs.save_ply(gaussian_path)
171
+ torch.cuda.empty_cache()
172
+ return gaussian_path, gaussian_path
173
+
174
+
175
+ with gr.Blocks(delete_cache=(600, 600)) as demo:
176
+ gr.Markdown("""
177
+ ## Text to 3D Asset with [TRELLIS](https://trellis3d.github.io/)
178
+ * Type a text prompt and click "Generate" to create a 3D asset.
179
+ * If you find the generated 3D asset satisfactory, click "Extract GLB" to extract the GLB file and download it.
180
+ """)
181
+
182
+ with gr.Row():
183
+ with gr.Column():
184
+ text_prompt = gr.Textbox(label="Text Prompt", lines=5)
185
+
186
+ with gr.Accordion(label="Generation Settings", open=False):
187
+ seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)
188
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
189
+ gr.Markdown("Stage 1: Sparse Structure Generation")
190
+ with gr.Row():
191
+ ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
192
+ ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=25, step=1)
193
+ gr.Markdown("Stage 2: Structured Latent Generation")
194
+ with gr.Row():
195
+ slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
196
+ slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=25, step=1)
197
+
198
+ generate_btn = gr.Button("Generate")
199
+
200
+ with gr.Accordion(label="GLB Extraction Settings", open=False):
201
+ mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)
202
+ texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)
203
+
204
+ with gr.Row():
205
+ extract_glb_btn = gr.Button("Extract GLB", interactive=False)
206
+ extract_gs_btn = gr.Button("Extract Gaussian", interactive=False)
207
+ gr.Markdown("""
208
+ *NOTE: Gaussian file can be very large (~50MB), it will take a while to display and download.*
209
+ """)
210
+
211
+ with gr.Column():
212
+ video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)
213
+ model_output = LitModel3D(label="Extracted GLB/Gaussian", exposure=10.0, height=300)
214
+
215
+ with gr.Row():
216
+ download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
217
+ download_gs = gr.DownloadButton(label="Download Gaussian", interactive=False)
218
+
219
+ output_buf = gr.State()
220
+
221
+ # Handlers
222
+ demo.load(start_session)
223
+ demo.unload(end_session)
224
+
225
+ generate_btn.click(
226
+ get_seed,
227
+ inputs=[randomize_seed, seed],
228
+ outputs=[seed],
229
+ ).then(
230
+ text_to_3d,
231
+ inputs=[text_prompt, seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps],
232
+ outputs=[output_buf, video_output],
233
+ ).then(
234
+ lambda: tuple([gr.Button(interactive=True), gr.Button(interactive=True)]),
235
+ outputs=[extract_glb_btn, extract_gs_btn],
236
+ )
237
+
238
+ video_output.clear(
239
+ lambda: tuple([gr.Button(interactive=False), gr.Button(interactive=False)]),
240
+ outputs=[extract_glb_btn, extract_gs_btn],
241
+ )
242
+
243
+ extract_glb_btn.click(
244
+ extract_glb,
245
+ inputs=[output_buf, mesh_simplify, texture_size],
246
+ outputs=[model_output, download_glb],
247
+ ).then(
248
+ lambda: gr.Button(interactive=True),
249
+ outputs=[download_glb],
250
+ )
251
+
252
+ extract_gs_btn.click(
253
+ extract_gaussian,
254
+ inputs=[output_buf],
255
+ outputs=[model_output, download_gs],
256
+ ).then(
257
+ lambda: gr.Button(interactive=True),
258
+ outputs=[download_gs],
259
+ )
260
+
261
+ model_output.clear(
262
+ lambda: gr.Button(interactive=False),
263
+ outputs=[download_glb],
264
+ )
265
+
266
+
267
+ # Launch the Gradio app
268
+ if __name__ == "__main__":
269
+ pipeline = TrellisTextTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-text-xlarge")
270
+ pipeline.cuda()
271
+ demo.launch()