JeffreyXiang commited on
Commit
a1e3f5f
·
1 Parent(s): fdcc6ec
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. app.py +344 -77
  2. assets/app/basecolor.png +0 -0
  3. assets/app/clay.png +0 -0
  4. assets/app/hdri_city.png +0 -0
  5. assets/app/hdri_courtyard.png +0 -0
  6. assets/app/hdri_forest.png +0 -0
  7. assets/app/hdri_interior.png +0 -0
  8. assets/app/hdri_night.png +0 -0
  9. assets/app/hdri_studio.png +0 -0
  10. assets/app/hdri_sunrise.png +0 -0
  11. assets/app/hdri_sunset.png +0 -0
  12. assets/app/normal.png +0 -0
  13. assets/example_images/0a34fae7ba57cb8870df5325b9c30ea474def1b0913c19c596655b85a79fdee4.webp +0 -3
  14. assets/example_images/2bb0932314bae71eec94d0d01a20d3f761ade9664e013b9a9a43c00a2f44163a.webp +0 -3
  15. assets/example_images/3723615e3766742ae35b09517152a58c36d62b707bc60d7f76f8a6c922add2c0.webp +0 -3
  16. assets/example_images/454e7d8a30486c0635369936e7bec5677b78ae5f436d0e46af0d533738be859f.webp +0 -3
  17. assets/example_images/50b70c5f88a5961d2c786158655d2fce5c3b214b2717956500a66a4e5b5fbe37.webp +0 -3
  18. assets/example_images/51b1b31d40476b123db70a51ae0b5f8b8d0db695b616bc2ec4e6324eb178fc14.webp +0 -3
  19. assets/example_images/52284bf45134c59a94be150a5b18b9cc3619ada4b30ded8d8d0288383b8c016f.webp +0 -3
  20. assets/example_images/5c80e5e03a3b60b6f03eaf555ba1dafc0e4230c472d7e8c8e2c5ca0a0dfcef10.webp +0 -3
  21. assets/example_images/61fea9d08e0bd9a067c9f696621dc89165afb5aab318d0701bc025d7863dabf0.webp +0 -3
  22. assets/example_images/6b6d89d46d7f53e6409dbe695a9ef8f97c5257e641da35015a78579e903acdad.webp +0 -0
  23. assets/example_images/7b540da337f576ffce2adc36c7459b9bbbfd845ab2160a6abbe986f1f906f6cd.webp +0 -0
  24. assets/example_images/7d7659d5943e85a73a4ffe33c6dd48f5d79601e9bf11b103516f419ce9fbf713.webp +0 -3
  25. assets/example_images/8aa698c59aab48d4ce69a558d9159107890e3d64e522af404d9635ad0be21f88.webp +0 -3
  26. assets/example_images/9c306c7bd0e857285f536fb500c0828e5fad4e23c3ceeab92c888c568fa19101.webp +0 -3
  27. assets/example_images/a13d176cd7a7d457b42d1b32223bcff1a45dafbbb42c6a272b97d65ac2f2eb52.webp +0 -0
  28. assets/example_images/be7deb26f4fdd2080d4288668af4c39e526564282c579559ff8a4126ca4ed6c1.webp +0 -3
  29. assets/example_images/c3d714bc125f06ce1187799d5ca10736b4064a24c141e627089aad2bdedf7aa5.webp +0 -3
  30. assets/example_images/c9340e744541f310bf89838f652602961d3e5950b31cd349bcbfc7e59e15cd2e.webp +0 -3
  31. assets/example_images/cd3c309f17eee5ad6afe4e001765893ade20b653f611365c93d158286b4cee96.webp +0 -3
  32. assets/example_images/cdf996a6cc218918eeb90209891ce306a230e6d9cca2a3d9bbb37c6d7b6bd318.webp +0 -3
  33. assets/example_images/e10465728ebea1e055524f97ac5d47cebf82a672f07a05409aa07d826c9d9f37.webp +0 -0
  34. assets/example_images/ee8ecf658fde9c58830c021b2e30d0d5e7e492ef52febe7192a6c74fbf1b0472.webp +0 -3
  35. assets/example_images/f5332118a0cda9cd13fe13d4be2b00437e702d1f9af51ebb6b75219a572a6ce9.webp +0 -3
  36. assets/example_images/f8a7eafe26a4f3ebd26a9e7d0289e4a40b5a93e9234e94ec3e1071c352acc65a.webp +0 -3
  37. assets/example_images/f94e2b76494ce2cf1874611273e5fb3d76b395793bb5647492fa85c2ce0a248b.webp +0 -0
  38. requirements.txt +0 -1
  39. trellis2/models/__init__.py +0 -0
  40. trellis2/models/sc_vaes/fdg_vae.py +0 -0
  41. trellis2/models/sc_vaes/sparse_unet_vae.py +0 -0
  42. trellis2/models/sparse_elastic_mixin.py +0 -0
  43. trellis2/models/sparse_structure_flow.py +0 -0
  44. trellis2/models/sparse_structure_vae.py +0 -0
  45. trellis2/models/structured_latent_flow.py +0 -0
  46. trellis2/modules/attention/__init__.py +0 -0
  47. trellis2/modules/attention/config.py +0 -0
  48. trellis2/modules/attention/full_attn.py +0 -0
  49. trellis2/modules/attention/modules.py +0 -0
  50. trellis2/modules/attention/rope.py +0 -0
app.py CHANGED
@@ -15,7 +15,8 @@ from typing import *
15
  import torch
16
  import numpy as np
17
  from PIL import Image
18
- import tempfile
 
19
  from trellis2.modules.sparse import SparseTensor
20
  from trellis2.pipelines import Trellis2ImageTo3DPipeline
21
  from trellis2.renderers import EnvMap
@@ -25,7 +26,247 @@ import o_voxel
25
 
26
  MAX_SEED = np.iinfo(np.int32).max
27
  TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
28
- os.makedirs(TMP_DIR, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  def start_session(req: gr.Request):
@@ -38,19 +279,20 @@ def end_session(req: gr.Request):
38
  shutil.rmtree(user_dir)
39
 
40
 
41
- def remove_background(input: Image.Image) -> Image.Image:
42
- with tempfile.NamedTemporaryFile(suffix='.png') as f:
43
- input = input.convert('RGB')
44
- input.save(f.name)
45
- output = rmbg_client.predict(handle_file(f.name), api_name="/image")[0][0]
46
- output = Image.open(output)
47
- return output
48
 
49
 
50
- def preprocess_image(input: Image.Image) -> Image.Image:
51
  """
52
  Preprocess the input image.
53
  """
 
54
  # if has alpha channel, use it directly; otherwise, remove background
55
  has_alpha = False
56
  if input.mode == 'RGBA':
@@ -64,7 +306,7 @@ def preprocess_image(input: Image.Image) -> Image.Image:
64
  if has_alpha:
65
  output = input
66
  else:
67
- output = remove_background(input)
68
  output_np = np.array(output)
69
  alpha = output_np[:, :, 3]
70
  bbox = np.argwhere(alpha > 0.8 * 255)
@@ -126,24 +368,7 @@ def image_to_3d(
126
  req: gr.Request,
127
  progress=gr.Progress(track_tqdm=True),
128
  ) -> str:
129
- """
130
- Convert an image to a 3D model.
131
-
132
- Args:
133
- image (Image.Image): The input image.
134
- seed (int): The random seed.
135
- ss_guidance_strength (float): The guidance strength for sparse structure generation.
136
- ss_sampling_steps (int): The number of sampling steps for sparse structure generation.
137
- shape_slat_guidance_strength (float): The guidance strength for shape slat generation.
138
- shape_slat_sampling_steps (int): The number of sampling steps for shape slat generation.
139
- tex_slat_guidance_strength (float): The guidance strength for texture slat generation.
140
- tex_slat_sampling_steps (int): The number of sampling steps for texture slat generation.
141
-
142
- Returns:
143
- str: The path to the preview video of the 3D model.
144
- str: The path to the 3D model.
145
- """
146
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
147
  outputs, latents = pipeline.run(
148
  image,
149
  seed=seed,
@@ -175,13 +400,66 @@ def image_to_3d(
175
  )
176
  mesh = outputs[0]
177
  mesh.simplify(16777216) # nvdiffrast limit
178
- images = render_utils.make_pbr_vis_frames(
179
- render_utils.render_snapshot(mesh, resolution=1024, r=2, fov=36, envmap=envmap),
180
- resolution=1024
181
- )
182
  state = pack_state(latents)
183
  torch.cuda.empty_cache()
184
- return state, [Image.fromarray(image) for image in images]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
 
187
  @spaces.GPU(duration=60)
@@ -206,6 +484,7 @@ def extract_glb(
206
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
207
  shape_slat, tex_slat, res = unpack_state(state)
208
  mesh = pipeline.decode_latent(shape_slat, tex_slat, res)[0]
 
209
  glb = o_voxel.postprocess.to_glb(
210
  vertices=mesh.vertices,
211
  faces=mesh.faces,
@@ -229,36 +508,6 @@ def extract_glb(
229
  return glb_path, glb_path
230
 
231
 
232
- css = """
233
- .stepper-wrapper {
234
- padding: 0;
235
- }
236
-
237
- .stepper-container {
238
- padding: 0;
239
- align-items: center;
240
- }
241
-
242
- .step-button {
243
- flex-direction: row;
244
- }
245
-
246
- .step-connector {
247
- transform: none;
248
- }
249
-
250
- .step-number {
251
- width: 16px;
252
- height: 16px;
253
- }
254
-
255
- .step-label {
256
- position: relative;
257
- bottom: 0;
258
- }
259
- """
260
-
261
-
262
  with gr.Blocks(delete_cache=(600, 600)) as demo:
263
  gr.Markdown("""
264
  ## Image to 3D Asset with [TRELLIS.2](https://microsoft.github.io/trellis.2)
@@ -270,11 +519,13 @@ with gr.Blocks(delete_cache=(600, 600)) as demo:
270
  with gr.Column(scale=1, min_width=360):
271
  image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=400)
272
 
273
- resolution = gr.Radio(["512", "1024", "1536"], label="Resolution", value="512")
274
  seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)
275
  randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
276
- decimation_target = gr.Slider(10000, 500000, label="Decimation Target", value=100000, step=10000)
277
  texture_size = gr.Slider(1024, 4096, label="Texture Size", value=2048, step=1024)
 
 
278
 
279
  with gr.Accordion(label="Advanced Settings", open=False):
280
  gr.Markdown("Stage 1: Sparse Structure Generation")
@@ -296,22 +547,20 @@ with gr.Blocks(delete_cache=(600, 600)) as demo:
296
  tex_slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
297
  tex_slat_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=3.0, step=0.1)
298
 
299
- generate_btn = gr.Button("Generate")
300
-
301
  with gr.Column(scale=10):
302
  with gr.Walkthrough(selected=0) as walkthrough:
303
  with gr.Step("Preview", id=0):
304
- preview_output = gr.Gallery(label="3D Asset Preview", height=800, show_label=True, preview=True)
305
  extract_btn = gr.Button("Extract GLB")
306
  with gr.Step("Extract", id=1):
307
- glb_output = gr.Model3D(label="Extracted GLB", height=800, show_label=True, display_mode="solid", clear_color=(0.25, 0.25, 0.25, 1.0))
308
  download_btn = gr.DownloadButton(label="Download GLB")
309
 
310
  with gr.Column(scale=1, min_width=172):
311
  examples = gr.Examples(
312
  examples=[
313
- f'assets/example_images/{image}'
314
- for image in os.listdir("assets/example_images")
315
  ],
316
  inputs=[image_prompt],
317
  fn=preprocess_image,
@@ -361,15 +610,33 @@ with gr.Blocks(delete_cache=(600, 600)) as demo:
361
 
362
  # Launch the Gradio app
363
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
364
  rmbg_client = Client("briaai/BRIA-RMBG-2.0")
365
  pipeline = Trellis2ImageTo3DPipeline.from_pretrained('microsoft/TRELLIS.2-4B')
366
  pipeline.rembg_model = None
367
  pipeline.low_vram = False
368
  pipeline.cuda()
369
 
370
- envmap = EnvMap(torch.tensor(
371
- cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),
372
- dtype=torch.float32, device='cuda'
373
- ))
 
 
 
 
 
 
 
 
 
 
374
 
375
- demo.launch(css=css)
 
15
  import torch
16
  import numpy as np
17
  from PIL import Image
18
+ import base64
19
+ import io
20
  from trellis2.modules.sparse import SparseTensor
21
  from trellis2.pipelines import Trellis2ImageTo3DPipeline
22
  from trellis2.renderers import EnvMap
 
26
 
27
  MAX_SEED = np.iinfo(np.int32).max
28
  TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
29
+ MODES = [
30
+ {"name": "Normal", "icon": "assets/app/normal.png", "render_key": "normal"},
31
+ {"name": "Clay render", "icon": "assets/app/clay.png", "render_key": "clay"},
32
+ {"name": "Base color", "icon": "assets/app/basecolor.png", "render_key": "base_color"},
33
+ {"name": "HDRI forest", "icon": "assets/app/hdri_forest.png", "render_key": "shaded_forest"},
34
+ {"name": "HDRI sunset", "icon": "assets/app/hdri_sunset.png", "render_key": "shaded_sunset"},
35
+ {"name": "HDRI courtyard", "icon": "assets/app/hdri_courtyard.png", "render_key": "shaded_courtyard"},
36
+ ]
37
+ STEPS = 8
38
+ DEFAULT_MODE = 3
39
+ DEFAULT_STEP = 3
40
+
41
+
42
+ css = """
43
+ /* Overwrite Gradio Default Style */
44
+ .stepper-wrapper {
45
+ padding: 0;
46
+ }
47
+
48
+ .stepper-container {
49
+ padding: 0;
50
+ align-items: center;
51
+ }
52
+
53
+ .step-button {
54
+ flex-direction: row;
55
+ }
56
+
57
+ .step-connector {
58
+ transform: none;
59
+ }
60
+
61
+ .step-number {
62
+ width: 16px;
63
+ height: 16px;
64
+ }
65
+
66
+ .step-label {
67
+ position: relative;
68
+ bottom: 0;
69
+ }
70
+
71
+ .wrap.center.full {
72
+ inset: 0;
73
+ height: 100%;
74
+ }
75
+
76
+ .wrap.center.full.translucent {
77
+ background: var(--block-background-fill);
78
+ }
79
+
80
+ .meta-text-center {
81
+ display: block !important;
82
+ position: absolute !important;
83
+ top: unset !important;
84
+ bottom: 0 !important;
85
+ right: 0 !important;
86
+ transform: unset !important;
87
+ }
88
+
89
+
90
+ /* Previewer */
91
+ .previewer-container {
92
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
93
+ width: 100%;
94
+ height: 722px;
95
+ margin: 0 auto;
96
+ padding: 20px;
97
+ display: flex;
98
+ flex-direction: column;
99
+ align-items: center;
100
+ justify-content: center;
101
+ }
102
+
103
+ /* Row 1: Display Modes */
104
+ .previewer-container .mode-row {
105
+ width: 100%;
106
+ display: flex;
107
+ gap: 8px;
108
+ justify-content: center;
109
+ margin-bottom: 20px;
110
+ flex-wrap: wrap;
111
+ }
112
+ .previewer-container .mode-btn {
113
+ width: 24px;
114
+ height: 24px;
115
+ border-radius: 50%;
116
+ cursor: pointer;
117
+ opacity: 0.5;
118
+ transition: all 0.2s;
119
+ border: 2px solid #ddd;
120
+ object-fit: cover;
121
+ }
122
+ .previewer-container .mode-btn:hover { opacity: 0.9; transform: scale(1.1); }
123
+ .previewer-container .mode-btn.active {
124
+ opacity: 1;
125
+ border-color: var(--color-accent);
126
+ transform: scale(1.1);
127
+ }
128
+
129
+ /* Row 2: Display Image */
130
+ .previewer-container .display-row {
131
+ margin-bottom: 20px;
132
+ min-height: 400px;
133
+ width: 100%;
134
+ flex-grow: 1;
135
+ display: flex;
136
+ justify-content: center;
137
+ align-items: center;
138
+ }
139
+ .previewer-container .previewer-main-image {
140
+ max-width: 100%;
141
+ max-height: 100%;
142
+ flex-grow: 1;
143
+ object-fit: contain;
144
+ display: none;
145
+ }
146
+ .previewer-container .previewer-main-image.visible {
147
+ display: block;
148
+ }
149
+
150
+ /* Row 3: Custom HTML Slider */
151
+ .previewer-container .slider-row {
152
+ width: 100%;
153
+ display: flex;
154
+ flex-direction: column;
155
+ align-items: center;
156
+ gap: 10px;
157
+ padding: 0 10px;
158
+ }
159
+
160
+ .previewer-container input[type=range] {
161
+ -webkit-appearance: none;
162
+ width: 100%;
163
+ max-width: 400px;
164
+ background: transparent;
165
+ }
166
+ .previewer-container input[type=range]::-webkit-slider-runnable-track {
167
+ width: 100%;
168
+ height: 8px;
169
+ cursor: pointer;
170
+ background: #ddd;
171
+ border-radius: 5px;
172
+ }
173
+ .previewer-container input[type=range]::-webkit-slider-thumb {
174
+ height: 20px;
175
+ width: 20px;
176
+ border-radius: 50%;
177
+ background: var(--color-accent);
178
+ cursor: pointer;
179
+ -webkit-appearance: none;
180
+ margin-top: -6px;
181
+ box-shadow: 0 2px 5px rgba(0,0,0,0.2);
182
+ transition: transform 0.1s;
183
+ }
184
+ .previewer-container input[type=range]::-webkit-slider-thumb:hover {
185
+ transform: scale(1.2);
186
+ }
187
+ """
188
+
189
+
190
+ head = """
191
+ <script>
192
+ function refreshView(mode, step) {
193
+ // 1. Find current mode and step
194
+ const allImgs = document.querySelectorAll('.previewer-main-image');
195
+ for (let i = 0; i < allImgs.length; i++) {
196
+ const img = allImgs[i];
197
+ if (img.classList.contains('visible')) {
198
+ const id = img.id;
199
+ const [_, m, s] = id.split('-');
200
+ if (mode === -1) mode = parseInt(m.slice(1));
201
+ if (step === -1) step = parseInt(s.slice(1));
202
+ break;
203
+ }
204
+ }
205
+
206
+ // 2. Hide ALL images
207
+ // We select all elements with class 'previewer-main-image'
208
+ allImgs.forEach(img => img.classList.remove('visible'));
209
+
210
+ // 3. Construct the specific ID for the current state
211
+ // Format: view-m{mode}-s{step}
212
+ const targetId = 'view-m' + mode + '-s' + step;
213
+ const targetImg = document.getElementById(targetId);
214
+
215
+ // 4. Show ONLY the target
216
+ if (targetImg) {
217
+ targetImg.classList.add('visible');
218
+ }
219
+
220
+ // 5. Update Button Highlights
221
+ const allBtns = document.querySelectorAll('.mode-btn');
222
+ allBtns.forEach((btn, idx) => {
223
+ if (idx === mode) btn.classList.add('active');
224
+ else btn.classList.remove('active');
225
+ });
226
+ }
227
+
228
+ // --- Action: Switch Mode ---
229
+ function selectMode(mode) {
230
+ refreshView(mode, -1);
231
+ }
232
+
233
+ // --- Action: Slider Change ---
234
+ function onSliderChange(val) {
235
+ refreshView(-1, parseInt(val));
236
+ }
237
+
238
+ function modify_html_container() {
239
+ const container = document.querySelector('.previewer-container');
240
+ const html_container = container.parentNode.parentNode.parentNode;
241
+
242
+ // Remove class padded
243
+ html_container.classList.remove('padded');
244
+
245
+ // Search for data-testid="block-label" in html_container's children
246
+ const status_tracker = html_container.querySelector('[data-testid="block-label"]');
247
+ if (status_tracker) {
248
+ // Add class float
249
+ status_tracker.classList.add('float');
250
+ }
251
+ }
252
+ </script>
253
+ """
254
+
255
+
256
+ empty_html = f"""
257
+ <div class="previewer-container">
258
+ <svg style=" opacity: .5; height: var(--size-5); color: var(--body-text-color);"
259
+ xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-image"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
260
+ </div>
261
+ """
262
+
263
+
264
+ def image_to_base64(image):
265
+ buffered = io.BytesIO()
266
+ image = image.convert("RGB")
267
+ image.save(buffered, format="jpeg", quality=85)
268
+ img_str = base64.b64encode(buffered.getvalue()).decode()
269
+ return f"data:image/jpeg;base64,{img_str}"
270
 
271
 
272
  def start_session(req: gr.Request):
 
279
  shutil.rmtree(user_dir)
280
 
281
 
282
+ def remove_background(input: Image.Image, user_dir: str) -> Image.Image:
283
+ input = input.convert('RGB')
284
+ os.makedirs(user_dir, exist_ok=True)
285
+ input.save(os.path.join(user_dir, 'input.png'))
286
+ output = rmbg_client.predict(handle_file(os.path.join(user_dir, 'input.png')), api_name="/image")[0][0]
287
+ output = Image.open(output)
288
+ return output
289
 
290
 
291
+ def preprocess_image(input: Image.Image, req: gr.Request,) -> Image.Image:
292
  """
293
  Preprocess the input image.
294
  """
295
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
296
  # if has alpha channel, use it directly; otherwise, remove background
297
  has_alpha = False
298
  if input.mode == 'RGBA':
 
306
  if has_alpha:
307
  output = input
308
  else:
309
+ output = remove_background(input, user_dir)
310
  output_np = np.array(output)
311
  alpha = output_np[:, :, 3]
312
  bbox = np.argwhere(alpha > 0.8 * 255)
 
368
  req: gr.Request,
369
  progress=gr.Progress(track_tqdm=True),
370
  ) -> str:
371
+ # --- Sampling ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  outputs, latents = pipeline.run(
373
  image,
374
  seed=seed,
 
400
  )
401
  mesh = outputs[0]
402
  mesh.simplify(16777216) # nvdiffrast limit
403
+ images = render_utils.render_snapshot(mesh, resolution=1024, r=2, fov=36, nviews=STEPS, envmap=envmap)
 
 
 
404
  state = pack_state(latents)
405
  torch.cuda.empty_cache()
406
+
407
+ # --- HTML Construction ---
408
+ # The Stack of 48 Images
409
+ images_html = ""
410
+ for m_idx, mode in enumerate(MODES):
411
+ for s_idx in range(STEPS):
412
+ # ID Naming Convention: view-m{mode}-s{step}
413
+ unique_id = f"view-m{m_idx}-s{s_idx}"
414
+
415
+ # Logic: Only Mode 0, Step 0 is visible initially
416
+ is_visible = (m_idx == DEFAULT_MODE and s_idx == DEFAULT_STEP)
417
+ vis_class = "visible" if is_visible else ""
418
+
419
+ # Image Source
420
+ img_base64 = image_to_base64(Image.fromarray(images[mode['render_key']][s_idx]))
421
+
422
+ # Render the Tag
423
+ images_html += f"""
424
+ <img id="{unique_id}"
425
+ class="previewer-main-image {vis_class}"
426
+ src="{img_base64}"
427
+ loading="eager">
428
+ """
429
+
430
+ # Button Row HTML
431
+ btns_html = ""
432
+ for idx, mode in enumerate(MODES):
433
+ active_class = "active" if idx == DEFAULT_MODE else ""
434
+ # Note: onclick calls the JS function defined in Head
435
+ btns_html += f"""
436
+ <img src="{mode['icon_base64']}"
437
+ class="mode-btn {active_class}"
438
+ onclick="selectMode({idx})"
439
+ title="{mode['name']}">
440
+ """
441
+
442
+ # Assemble the full component
443
+ full_html = f"""
444
+ <div class="previewer-container">
445
+ <!-- Row 1: Viewport containing 48 static <img> tags -->
446
+ <div class="display-row">
447
+ {images_html}
448
+ </div>
449
+
450
+ <!-- Row 2 -->
451
+ <div class="mode-row" id="btn-group">
452
+ {btns_html}
453
+ </div>
454
+
455
+ <!-- Row 3: Slider -->
456
+ <div class="slider-row">
457
+ <input type="range" id="custom-slider" min="0" max="{STEPS - 1}" value="{DEFAULT_STEP}" step="1" oninput="onSliderChange(this.value)">
458
+ </div>
459
+ </div>
460
+ """
461
+
462
+ return state, full_html
463
 
464
 
465
  @spaces.GPU(duration=60)
 
484
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
485
  shape_slat, tex_slat, res = unpack_state(state)
486
  mesh = pipeline.decode_latent(shape_slat, tex_slat, res)[0]
487
+ mesh.simplify(16777216)
488
  glb = o_voxel.postprocess.to_glb(
489
  vertices=mesh.vertices,
490
  faces=mesh.faces,
 
508
  return glb_path, glb_path
509
 
510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  with gr.Blocks(delete_cache=(600, 600)) as demo:
512
  gr.Markdown("""
513
  ## Image to 3D Asset with [TRELLIS.2](https://microsoft.github.io/trellis.2)
 
519
  with gr.Column(scale=1, min_width=360):
520
  image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=400)
521
 
522
+ resolution = gr.Radio(["512", "1024", "1536"], label="Resolution", value="1024")
523
  seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)
524
  randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
525
+ decimation_target = gr.Slider(100000, 1000000, label="Decimation Target", value=500000, step=10000)
526
  texture_size = gr.Slider(1024, 4096, label="Texture Size", value=2048, step=1024)
527
+
528
+ generate_btn = gr.Button("Generate")
529
 
530
  with gr.Accordion(label="Advanced Settings", open=False):
531
  gr.Markdown("Stage 1: Sparse Structure Generation")
 
547
  tex_slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
548
  tex_slat_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=3.0, step=0.1)
549
 
 
 
550
  with gr.Column(scale=10):
551
  with gr.Walkthrough(selected=0) as walkthrough:
552
  with gr.Step("Preview", id=0):
553
+ preview_output = gr.HTML(empty_html, label="3D Asset Preview", show_label=True, container=True, js_on_load="modify_html_container()")
554
  extract_btn = gr.Button("Extract GLB")
555
  with gr.Step("Extract", id=1):
556
+ glb_output = gr.Model3D(label="Extracted GLB", height=724, show_label=True, display_mode="solid", clear_color=(0.25, 0.25, 0.25, 1.0))
557
  download_btn = gr.DownloadButton(label="Download GLB")
558
 
559
  with gr.Column(scale=1, min_width=172):
560
  examples = gr.Examples(
561
  examples=[
562
+ f'assets/example_image/{image}'
563
+ for image in os.listdir("assets/example_image")
564
  ],
565
  inputs=[image_prompt],
566
  fn=preprocess_image,
 
610
 
611
  # Launch the Gradio app
612
  if __name__ == "__main__":
613
+ os.makedirs(TMP_DIR, exist_ok=True)
614
+
615
+ # Construct ui components
616
+ btn_img_base64_strs = {}
617
+ for i in range(len(MODES)):
618
+ icon = Image.open(MODES[i]['icon'])
619
+ MODES[i]['icon_base64'] = image_to_base64(icon)
620
+
621
  rmbg_client = Client("briaai/BRIA-RMBG-2.0")
622
  pipeline = Trellis2ImageTo3DPipeline.from_pretrained('microsoft/TRELLIS.2-4B')
623
  pipeline.rembg_model = None
624
  pipeline.low_vram = False
625
  pipeline.cuda()
626
 
627
+ envmap = {
628
+ 'forest': EnvMap(torch.tensor(
629
+ cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),
630
+ dtype=torch.float32, device='cuda'
631
+ )),
632
+ 'sunset': EnvMap(torch.tensor(
633
+ cv2.cvtColor(cv2.imread('assets/hdri/sunset.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),
634
+ dtype=torch.float32, device='cuda'
635
+ )),
636
+ 'courtyard': EnvMap(torch.tensor(
637
+ cv2.cvtColor(cv2.imread('assets/hdri/courtyard.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),
638
+ dtype=torch.float32, device='cuda'
639
+ )),
640
+ }
641
 
642
+ demo.launch(css=css, head=head)
assets/app/basecolor.png ADDED
assets/app/clay.png ADDED
assets/app/hdri_city.png ADDED
assets/app/hdri_courtyard.png ADDED
assets/app/hdri_forest.png ADDED
assets/app/hdri_interior.png ADDED
assets/app/hdri_night.png ADDED
assets/app/hdri_studio.png ADDED
assets/app/hdri_sunrise.png ADDED
assets/app/hdri_sunset.png ADDED
assets/app/normal.png ADDED
assets/example_images/0a34fae7ba57cb8870df5325b9c30ea474def1b0913c19c596655b85a79fdee4.webp DELETED

Git LFS Details

  • SHA256: 83d3765ff57511f11054d62e6beaf52648d277006b6dcb3c1d5f9e03ef502c49
  • Pointer size: 131 Bytes
  • Size of remote file: 108 kB
assets/example_images/2bb0932314bae71eec94d0d01a20d3f761ade9664e013b9a9a43c00a2f44163a.webp DELETED

Git LFS Details

  • SHA256: c4e26e3e2f3de96cf396c64f1cef39ac82c13f231e2567fe0fe902dc103bf949
  • Pointer size: 131 Bytes
  • Size of remote file: 170 kB
assets/example_images/3723615e3766742ae35b09517152a58c36d62b707bc60d7f76f8a6c922add2c0.webp DELETED

Git LFS Details

  • SHA256: 88c65db47f93beed7d6b184c32f9fa27c5f64ced2e3d4f535ad628179763cff8
  • Pointer size: 131 Bytes
  • Size of remote file: 116 kB
assets/example_images/454e7d8a30486c0635369936e7bec5677b78ae5f436d0e46af0d533738be859f.webp DELETED

Git LFS Details

  • SHA256: 47be8271d2d1d27fc334cc470d63534807ad44c6f50cee18a204125a1c6b66a4
  • Pointer size: 131 Bytes
  • Size of remote file: 140 kB
assets/example_images/50b70c5f88a5961d2c786158655d2fce5c3b214b2717956500a66a4e5b5fbe37.webp DELETED

Git LFS Details

  • SHA256: 933c10aeebb2920b08cb34a08ab1878817b64eb9e30efdcc3d76731069fc0849
  • Pointer size: 131 Bytes
  • Size of remote file: 131 kB
assets/example_images/51b1b31d40476b123db70a51ae0b5f8b8d0db695b616bc2ec4e6324eb178fc14.webp DELETED

Git LFS Details

  • SHA256: 2d5224235eeadadfdb93ab37664055ef55ffd930b085d268cd62c5faf9d101de
  • Pointer size: 131 Bytes
  • Size of remote file: 137 kB
assets/example_images/52284bf45134c59a94be150a5b18b9cc3619ada4b30ded8d8d0288383b8c016f.webp DELETED

Git LFS Details

  • SHA256: 86b909e6847118f2cec6e9c0945e6a78154ce5918f4ba14c0b0afa0be2e8647f
  • Pointer size: 131 Bytes
  • Size of remote file: 150 kB
assets/example_images/5c80e5e03a3b60b6f03eaf555ba1dafc0e4230c472d7e8c8e2c5ca0a0dfcef10.webp DELETED

Git LFS Details

  • SHA256: fbd98cf5da79c56f8efc6cf86804391e71bdad2e935d21a7262472653a0674dc
  • Pointer size: 131 Bytes
  • Size of remote file: 127 kB
assets/example_images/61fea9d08e0bd9a067c9f696621dc89165afb5aab318d0701bc025d7863dabf0.webp DELETED

Git LFS Details

  • SHA256: dfad86b88eb81da36a5acf77891822c042e991436bb004c7d75d8b19e89c45bd
  • Pointer size: 131 Bytes
  • Size of remote file: 111 kB
assets/example_images/6b6d89d46d7f53e6409dbe695a9ef8f97c5257e641da35015a78579e903acdad.webp DELETED
Binary file (95.7 kB)
 
assets/example_images/7b540da337f576ffce2adc36c7459b9bbbfd845ab2160a6abbe986f1f906f6cd.webp DELETED
Binary file (99.6 kB)
 
assets/example_images/7d7659d5943e85a73a4ffe33c6dd48f5d79601e9bf11b103516f419ce9fbf713.webp DELETED

Git LFS Details

  • SHA256: 6707893380d3c791a9a2d33bc0caa5f10719f7168d25f8d447fa26f4420919db
  • Pointer size: 131 Bytes
  • Size of remote file: 109 kB
assets/example_images/8aa698c59aab48d4ce69a558d9159107890e3d64e522af404d9635ad0be21f88.webp DELETED

Git LFS Details

  • SHA256: a319ace2549835da92a6ffa5db73eebd7fce29079e5865cb32dfbdac21d9b900
  • Pointer size: 131 Bytes
  • Size of remote file: 100 kB
assets/example_images/9c306c7bd0e857285f536fb500c0828e5fad4e23c3ceeab92c888c568fa19101.webp DELETED

Git LFS Details

  • SHA256: 0d42562b49df17554583f2acbe18f8a26c9075cdab278caefab27aa7587df4ac
  • Pointer size: 131 Bytes
  • Size of remote file: 115 kB
assets/example_images/a13d176cd7a7d457b42d1b32223bcff1a45dafbbb42c6a272b97d65ac2f2eb52.webp DELETED
Binary file (82.9 kB)
 
assets/example_images/be7deb26f4fdd2080d4288668af4c39e526564282c579559ff8a4126ca4ed6c1.webp DELETED

Git LFS Details

  • SHA256: 0928c46a44b8adcaa04cf6c3720b7ee4f6f5013717031cd3373a8ec1b92aef9d
  • Pointer size: 131 Bytes
  • Size of remote file: 151 kB
assets/example_images/c3d714bc125f06ce1187799d5ca10736b4064a24c141e627089aad2bdedf7aa5.webp DELETED

Git LFS Details

  • SHA256: e211aff13d1e7dcdf592d68ea34e03794c4464c5b159224d7c508d9ecae5eb59
  • Pointer size: 131 Bytes
  • Size of remote file: 152 kB
assets/example_images/c9340e744541f310bf89838f652602961d3e5950b31cd349bcbfc7e59e15cd2e.webp DELETED

Git LFS Details

  • SHA256: 4533ce41604e7aff386c71f37f0b2727242a4615ef0e37c3cd62273678ad1809
  • Pointer size: 131 Bytes
  • Size of remote file: 143 kB
assets/example_images/cd3c309f17eee5ad6afe4e001765893ade20b653f611365c93d158286b4cee96.webp DELETED

Git LFS Details

  • SHA256: 6b7c45936606c2f24af55c9e32426c25b819abb8cabf255ff9592f10bf0e3e60
  • Pointer size: 131 Bytes
  • Size of remote file: 246 kB
assets/example_images/cdf996a6cc218918eeb90209891ce306a230e6d9cca2a3d9bbb37c6d7b6bd318.webp DELETED

Git LFS Details

  • SHA256: eaf705e6205f5101af261fac1a3477121cf377f92ff93feaf506eada70de98d7
  • Pointer size: 131 Bytes
  • Size of remote file: 218 kB
assets/example_images/e10465728ebea1e055524f97ac5d47cebf82a672f07a05409aa07d826c9d9f37.webp DELETED
Binary file (86.1 kB)
 
assets/example_images/ee8ecf658fde9c58830c021b2e30d0d5e7e492ef52febe7192a6c74fbf1b0472.webp DELETED

Git LFS Details

  • SHA256: d3636477a76b626de8749d245f916261b17736f8fd7aa4fe097cd4bbac874d61
  • Pointer size: 131 Bytes
  • Size of remote file: 228 kB
assets/example_images/f5332118a0cda9cd13fe13d4be2b00437e702d1f9af51ebb6b75219a572a6ce9.webp DELETED

Git LFS Details

  • SHA256: 0f49599c52ec02ea0b19e5e333dbd48d072c56f4a6300a35756ce50832d59ca6
  • Pointer size: 131 Bytes
  • Size of remote file: 158 kB
assets/example_images/f8a7eafe26a4f3ebd26a9e7d0289e4a40b5a93e9234e94ec3e1071c352acc65a.webp DELETED

Git LFS Details

  • SHA256: 3cb85a0afac1465b9033327f3ba8d00f4d8e6a36fef7d39bb4fd4eb22a610385
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
assets/example_images/f94e2b76494ce2cf1874611273e5fb3d76b395793bb5647492fa85c2ce0a248b.webp DELETED
Binary file (99.6 kB)
 
requirements.txt CHANGED
@@ -15,7 +15,6 @@ zstandard==0.25.0
15
  kornia==0.8.2
16
  timm==1.0.22
17
  git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8
18
- https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.3/flash_attn-2.7.3+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
19
  https://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
20
  https://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/cumesh-0.0.1-cp310-cp310-linux_x86_64.whl
21
  https://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/flex_gemm-0.0.1-cp310-cp310-linux_x86_64.whl
 
15
  kornia==0.8.2
16
  timm==1.0.22
17
  git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8
 
18
  https://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
19
  https://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/cumesh-0.0.1-cp310-cp310-linux_x86_64.whl
20
  https://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/flex_gemm-0.0.1-cp310-cp310-linux_x86_64.whl
trellis2/models/__init__.py CHANGED
File without changes
trellis2/models/sc_vaes/fdg_vae.py CHANGED
File without changes
trellis2/models/sc_vaes/sparse_unet_vae.py CHANGED
File without changes
trellis2/models/sparse_elastic_mixin.py CHANGED
File without changes
trellis2/models/sparse_structure_flow.py CHANGED
File without changes
trellis2/models/sparse_structure_vae.py CHANGED
File without changes
trellis2/models/structured_latent_flow.py CHANGED
File without changes
trellis2/modules/attention/__init__.py CHANGED
File without changes
trellis2/modules/attention/config.py CHANGED
File without changes
trellis2/modules/attention/full_attn.py CHANGED
File without changes
trellis2/modules/attention/modules.py CHANGED
File without changes
trellis2/modules/attention/rope.py CHANGED
File without changes