cronos3k commited on
Commit
811784d
·
verified ·
1 Parent(s): d635e38

Update app.py

Browse files

no optimisations let's see if it works

Files changed (1) hide show
  1. app.py +47 -134
app.py CHANGED
@@ -1,6 +1,4 @@
1
  import gradio as gr
2
- from gradio_litmodel3d import LitModel3D
3
-
4
  import os
5
  import shutil
6
  os.environ['SPCONV_ALGO'] = 'native'
@@ -14,6 +12,7 @@ from PIL import Image
14
  from trellis.pipelines import TrellisImageTo3DPipeline
15
  from trellis.representations import Gaussian, MeshExtractResult
16
  from trellis.utils import render_utils, postprocessing_utils
 
17
 
18
 
19
  MAX_SEED = np.iinfo(np.int32).max
@@ -75,7 +74,6 @@ def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:
75
  return gs, mesh, state['trial_id']
76
 
77
  def get_seed(randomize_seed: bool, seed: int) -> int:
78
- """Get the random seed."""
79
  return np.random.randint(0, MAX_SEED) if randomize_seed else seed
80
 
81
  def image_to_3d(
@@ -86,141 +84,64 @@ def image_to_3d(
86
  slat_guidance_strength: float,
87
  slat_sampling_steps: int,
88
  req: gr.Request,
89
- progress: gr.Progress = gr.Progress()
90
  ) -> Tuple[dict, str, str, str]:
91
- """
92
- Convert an image to a 3D model with improved memory management and progress tracking.
93
- """
94
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
95
- progress(0, desc="Initializing...")
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # Clear CUDA cache before starting
98
- torch.cuda.empty_cache()
 
99
 
100
- try:
101
- # Generate 3D model with progress updates
102
- progress(0.1, desc="Running 3D generation pipeline...")
103
- outputs = pipeline.run(
104
- image,
105
- seed=seed,
106
- formats=["gaussian", "mesh"],
107
- preprocess_image=False,
108
- sparse_structure_sampler_params={
109
- "steps": ss_sampling_steps,
110
- "cfg_strength": ss_guidance_strength,
111
- },
112
- slat_sampler_params={
113
- "steps": slat_sampling_steps,
114
- "cfg_strength": slat_guidance_strength,
115
- },
116
- )
117
-
118
- progress(0.4, desc="Generating video preview...")
119
- # Generate video frames in batches to manage memory
120
- batch_size = 30 # Process 30 frames at a time
121
- num_frames = 120
122
- video = []
123
- video_geo = []
124
-
125
- for i in range(0, num_frames, batch_size):
126
- end_idx = min(i + batch_size, num_frames)
127
- batch_frames = render_utils.render_video(
128
- outputs['gaussian'][0],
129
- num_frames=end_idx - i,
130
- start_frame=i
131
- )['color']
132
- batch_geo = render_utils.render_video(
133
- outputs['mesh'][0],
134
- num_frames=end_idx - i,
135
- start_frame=i
136
- )['normal']
137
-
138
- video.extend(batch_frames)
139
- video_geo.extend(batch_geo)
140
-
141
- # Clear cache after each batch
142
- torch.cuda.empty_cache()
143
- progress(0.4 + (0.3 * i / num_frames), desc=f"Rendering frames {i} to {end_idx}...")
144
-
145
- # Combine video frames
146
- video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
147
-
148
- # Generate unique ID and save video
149
- trial_id = str(uuid.uuid4())
150
- video_path = os.path.join(user_dir, f"{trial_id}.mp4")
151
- progress(0.7, desc="Saving video...")
152
- imageio.mimsave(video_path, video, fps=15)
153
-
154
- # Clear video data from memory
155
- del video
156
- del video_geo
157
- torch.cuda.empty_cache()
158
-
159
- # Generate and save full-quality GLB
160
- progress(0.8, desc="Generating full-quality GLB...")
161
- glb = postprocessing_utils.to_glb(
162
- outputs['gaussian'][0],
163
- outputs['mesh'][0],
164
- simplify=0.0,
165
- texture_size=2048,
166
- verbose=False
167
- )
168
- glb_path = os.path.join(user_dir, f"{trial_id}_full.glb")
169
- progress(0.9, desc="Saving GLB file...")
170
- glb.export(glb_path)
171
-
172
- # Pack state for reduced version
173
- progress(0.95, desc="Finalizing...")
174
- state = pack_state(outputs['gaussian'][0], outputs['mesh'][0], trial_id)
175
-
176
- # Final cleanup
177
- torch.cuda.empty_cache()
178
- progress(1.0, desc="Complete!")
179
-
180
- return state, video_path, glb_path, glb_path
181
-
182
- except Exception as e:
183
- # Clean up on error
184
- torch.cuda.empty_cache()
185
- raise gr.Error(f"Processing failed: {str(e)}")
186
 
187
  def extract_reduced_glb(
188
  state: dict,
189
  mesh_simplify: float,
190
  texture_size: int,
191
  req: gr.Request,
192
- progress: gr.Progress = gr.Progress()
193
  ) -> Tuple[str, str]:
194
- """
195
- Extract a reduced-quality GLB file with progress tracking.
196
- """
197
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
 
198
 
199
- try:
200
- progress(0.1, desc="Unpacking model state...")
201
- gs, mesh, trial_id = unpack_state(state)
202
-
203
- progress(0.3, desc="Generating reduced GLB...")
204
- glb = postprocessing_utils.to_glb(
205
- gs, mesh,
206
- simplify=mesh_simplify,
207
- texture_size=texture_size,
208
- verbose=False
209
- )
210
-
211
- progress(0.8, desc="Saving reduced GLB...")
212
- glb_path = os.path.join(user_dir, f"{trial_id}_reduced.glb")
213
- glb.export(glb_path)
214
-
215
- progress(0.9, desc="Cleaning up...")
216
- torch.cuda.empty_cache()
217
-
218
- progress(1.0, desc="Complete!")
219
- return glb_path, glb_path
220
-
221
- except Exception as e:
222
- torch.cuda.empty_cache()
223
- raise gr.Error(f"GLB reduction failed: {str(e)}")
224
 
225
  with gr.Blocks(delete_cache=(600, 600)) as demo:
226
  gr.Markdown("""
@@ -312,20 +233,12 @@ with gr.Blocks(delete_cache=(600, 600)) as demo:
312
  )
313
 
314
  if __name__ == "__main__":
315
- # Set some CUDA memory management options
316
- torch.cuda.empty_cache()
317
- torch.backends.cudnn.benchmark = True
318
-
319
  # Initialize pipeline
320
  pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")
321
  pipeline.cuda()
322
 
323
  try:
324
- # Preload rembg with minimal memory usage
325
- test_img = np.zeros((256, 256, 3), dtype=np.uint8) # Smaller test image
326
- pipeline.preprocess_image(Image.fromarray(test_img))
327
- del test_img
328
- torch.cuda.empty_cache()
329
  except:
330
  pass
331
 
 
1
  import gradio as gr
 
 
2
  import os
3
  import shutil
4
  os.environ['SPCONV_ALGO'] = 'native'
 
12
  from trellis.pipelines import TrellisImageTo3DPipeline
13
  from trellis.representations import Gaussian, MeshExtractResult
14
  from trellis.utils import render_utils, postprocessing_utils
15
+ from gradio_litmodel3d import LitModel3D
16
 
17
 
18
  MAX_SEED = np.iinfo(np.int32).max
 
74
  return gs, mesh, state['trial_id']
75
 
76
  def get_seed(randomize_seed: bool, seed: int) -> int:
 
77
  return np.random.randint(0, MAX_SEED) if randomize_seed else seed
78
 
79
  def image_to_3d(
 
84
  slat_guidance_strength: float,
85
  slat_sampling_steps: int,
86
  req: gr.Request,
 
87
  ) -> Tuple[dict, str, str, str]:
 
 
 
88
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
89
+ outputs = pipeline.run(
90
+ image,
91
+ seed=seed,
92
+ formats=["gaussian", "mesh"],
93
+ preprocess_image=False,
94
+ sparse_structure_sampler_params={
95
+ "steps": ss_sampling_steps,
96
+ "cfg_strength": ss_guidance_strength,
97
+ },
98
+ slat_sampler_params={
99
+ "steps": slat_sampling_steps,
100
+ "cfg_strength": slat_guidance_strength,
101
+ },
102
+ )
103
 
104
+ video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']
105
+ video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']
106
+ video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
107
 
108
+ trial_id = str(uuid.uuid4())
109
+ video_path = os.path.join(user_dir, f"{trial_id}.mp4")
110
+ imageio.mimsave(video_path, video, fps=15)
111
+
112
+ # Save full-quality GLB
113
+ glb = postprocessing_utils.to_glb(
114
+ outputs['gaussian'][0],
115
+ outputs['mesh'][0],
116
+ simplify=0.0,
117
+ texture_size=2048,
118
+ verbose=False
119
+ )
120
+ glb_path = os.path.join(user_dir, f"{trial_id}_full.glb")
121
+ glb.export(glb_path)
122
+
123
+ state = pack_state(outputs['gaussian'][0], outputs['mesh'][0], trial_id)
124
+ return state, video_path, glb_path, glb_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  def extract_reduced_glb(
127
  state: dict,
128
  mesh_simplify: float,
129
  texture_size: int,
130
  req: gr.Request,
 
131
  ) -> Tuple[str, str]:
 
 
 
132
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
133
+ gs, mesh, trial_id = unpack_state(state)
134
 
135
+ glb = postprocessing_utils.to_glb(
136
+ gs, mesh,
137
+ simplify=mesh_simplify,
138
+ texture_size=texture_size,
139
+ verbose=False
140
+ )
141
+ glb_path = os.path.join(user_dir, f"{trial_id}_reduced.glb")
142
+ glb.export(glb_path)
143
+
144
+ return glb_path, glb_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  with gr.Blocks(delete_cache=(600, 600)) as demo:
147
  gr.Markdown("""
 
233
  )
234
 
235
  if __name__ == "__main__":
 
 
 
 
236
  # Initialize pipeline
237
  pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")
238
  pipeline.cuda()
239
 
240
  try:
241
+ pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8)))
 
 
 
 
242
  except:
243
  pass
244