-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1849 lines (1543 loc) · 78.5 KB
/
app.py
File metadata and controls
1849 lines (1543 loc) · 78.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import time
import os
import warnings
from webui.loading_screen import show_loading_screen, finalize_loading
from webui.initialize_pipeline import load_pipeline, reduce_memory_usage
from webui.ui_components import show_video_preview, show_3d_model_viewer, show_example_gallery
from webui.image_preview import image_preview
# Suppress common warnings for cleaner output
warnings.filterwarnings("ignore", message=".*TRANSFORMERS_CACHE.*deprecated.*")
warnings.filterwarnings("ignore", message=".*xFormers is available.*")
warnings.filterwarnings("ignore", message=".*torch.library.impl_abstract.*renamed.*")
warnings.filterwarnings("ignore", message=".*torch.library.register_fake.*")
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
os.environ['SPCONV_ALGO'] = 'native'
# Memory optimizations for Trellis workloads
# Use backend_alloc:cudaMallocAsync for better memory management with PyTorch 2.0+
# Avoid expandable_segments due to compatibility issues with certain operations
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:512,garbage_collection_threshold:0.8,roundup_power2_divisions:16'
# CUDA optimizations
os.environ['CUDA_LAUNCH_BLOCKING'] = '0' # Non-blocking launches
# Suppress common library warnings
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
# Suppress transformers cache warnings
os.environ['TRANSFORMERS_NO_ADVISORY_WARNINGS'] = '1'
from typing import Optional, List, Tuple, Dict, Any
import torch
import numpy as np
import imageio
import uuid
import gc
from dataclasses import dataclass
from easydict import EasyDict as edict
from PIL import Image
from trellis.pipelines import TrellisImageTo3DPipeline
from trellis.pipelines.image_refiner import ImageRefiner
from trellis.representations import Gaussian, MeshExtractResult
from trellis.utils import render_utils, postprocessing_utils
MAX_SEED = np.iinfo(np.int32).max
TMP_DIR = os.environ.get("TRELLIS_OUTPUT_DIR", "/tmp/Trellis-demo")
os.makedirs(TMP_DIR, exist_ok=True)
# ============================================================================
# Data Classes for Type Safety
# ============================================================================
@dataclass
class GenerationParams:
"""Parameters for 3D model generation."""
seed: int
randomize_seed: bool
ss_guidance_strength: float
ss_sampling_steps: int
slat_guidance_strength: float
slat_sampling_steps: int
@dataclass
class ExportParams:
"""Parameters for GLB export."""
mesh_simplify: float
texture_size: int
fill_holes_resolution: int = 1024
fill_holes_num_views: int = 1000
@dataclass
class ModelState:
"""State of a generated 3D model."""
gaussian_data: Dict[str, Any]
mesh_data: Dict[str, Any]
trial_id: str
class StateManager:
"""Manages Streamlit session state with type safety."""
# State keys
PIPELINE = 'pipeline'
REFINER = 'refiner'
UPLOADED_IMAGE = 'uploaded_image'
PROCESSED_PREVIEW = 'processed_preview'
GENERATED_VIDEO = 'generated_video'
GENERATED_GLB = 'generated_glb'
GENERATED_STATE = 'generated_state'
CLEANUP_COUNTER = 'cleanup_counter'
IS_GENERATING = 'is_generating'
@staticmethod
def initialize() -> None:
"""Initialize all required session state variables."""
defaults = {
StateManager.PIPELINE: None,
StateManager.REFINER: None,
StateManager.UPLOADED_IMAGE: None,
StateManager.PROCESSED_PREVIEW: None,
StateManager.GENERATED_VIDEO: None,
StateManager.GENERATED_GLB: None,
StateManager.GENERATED_STATE: None,
StateManager.CLEANUP_COUNTER: 0,
StateManager.IS_GENERATING: False,
}
for key, default_value in defaults.items():
if key not in st.session_state:
st.session_state[key] = default_value
@staticmethod
def get_pipeline() -> Optional[TrellisImageTo3DPipeline]:
"""Get the pipeline from session state."""
return st.session_state.get(StateManager.PIPELINE)
@staticmethod
def set_pipeline(pipeline: TrellisImageTo3DPipeline) -> None:
"""Set the pipeline in session state."""
st.session_state[StateManager.PIPELINE] = pipeline
@staticmethod
def get_refiner() -> Optional[ImageRefiner]:
"""Get the refiner from session state."""
return st.session_state.get(StateManager.REFINER)
@staticmethod
def set_refiner(refiner: Optional[ImageRefiner]) -> None:
"""Set the refiner in session state."""
st.session_state[StateManager.REFINER] = refiner
@staticmethod
def get_uploaded_image() -> Optional[Image.Image]:
"""Get the uploaded image."""
return st.session_state.get(StateManager.UPLOADED_IMAGE)
@staticmethod
def set_uploaded_image(image: Optional[Image.Image]) -> None:
"""Set the uploaded image."""
st.session_state[StateManager.UPLOADED_IMAGE] = image
@staticmethod
def get_generated_video() -> Optional[str]:
"""Get the generated video path."""
return st.session_state.get(StateManager.GENERATED_VIDEO)
@staticmethod
def set_generated_video(video_path: Optional[str]) -> None:
"""Set the generated video path."""
st.session_state[StateManager.GENERATED_VIDEO] = video_path
@staticmethod
def get_generated_glb() -> Optional[str]:
"""Get the generated GLB path."""
return st.session_state.get(StateManager.GENERATED_GLB)
@staticmethod
def set_generated_glb(glb_path: Optional[str]) -> None:
"""Set the generated GLB path."""
st.session_state[StateManager.GENERATED_GLB] = glb_path
@staticmethod
def get_generated_state() -> Optional[Dict[str, Any]]:
"""Get the generated model state."""
return st.session_state.get(StateManager.GENERATED_STATE)
@staticmethod
def set_generated_state(state: Optional[Dict[str, Any]]) -> None:
"""Set the generated model state."""
st.session_state[StateManager.GENERATED_STATE] = state
@staticmethod
def clear_generated_content() -> None:
"""Clear all generated content from session state."""
keys_to_clear = [
StateManager.GENERATED_VIDEO,
StateManager.GENERATED_GLB,
StateManager.GENERATED_STATE,
StateManager.UPLOADED_IMAGE,
StateManager.PROCESSED_PREVIEW,
]
for key in keys_to_clear:
st.session_state[key] = None
@staticmethod
def increment_cleanup_counter() -> int:
"""Increment and return the cleanup counter."""
counter = st.session_state.get(StateManager.CLEANUP_COUNTER, 0)
counter += 1
if counter > 1000:
counter = 0
st.session_state[StateManager.CLEANUP_COUNTER] = counter
return counter
@staticmethod
def is_generating() -> bool:
"""Check if a generation is currently in progress."""
return st.session_state.get(StateManager.IS_GENERATING, False)
@staticmethod
def set_generating(generating: bool) -> None:
"""Set the generation state."""
st.session_state[StateManager.IS_GENERATING] = generating
class MemoryManager:
"""Manages memory cleanup and optimization."""
@staticmethod
def cleanup_session_state(clear_all: bool = False) -> None:
"""
Clean up large objects from session state to prevent memory leaks.
Args:
clear_all: If True, clear all generated content. If False, only clear old cached data.
"""
if clear_all:
StateManager.clear_generated_content()
# Always clean up image preview states that can accumulate
preview_keys = [k for k in st.session_state.keys() if k.startswith('_image_preview_')]
for key in preview_keys:
if isinstance(st.session_state[key], dict):
state = st.session_state[key]
# Reset render count periodically to prevent integer overflow
if state.get('render_count', 0) > 1000:
state['render_count'] = 0
# Cleanup pipeline resources
pipeline = StateManager.get_pipeline()
if pipeline is not None:
pipeline.cleanup()
# Cleanup refiner if loaded
refiner = StateManager.get_refiner()
if refiner is not None:
refiner.unload()
# Force garbage collection and CUDA cleanup
reduce_memory_usage()
@staticmethod
def periodic_cleanup() -> None:
"""
Perform periodic cleanup to prevent memory accumulation.
Should be called regularly (e.g., every few generations).
"""
counter = StateManager.increment_cleanup_counter()
# Perform lightweight cleanup every 5 interactions
if counter % 5 == 0:
MemoryManager.cleanup_session_state(clear_all=False)
# Perform more aggressive cleanup every 20 interactions
if counter % 20 == 0:
print(f"Performing periodic cleanup (interaction #{counter})")
# Clear old temp files
from webui.initialize_pipeline import cleanup_temp_files
cleanup_temp_files(max_age_hours=1)
@staticmethod
def reduce_memory() -> None:
"""Force garbage collection and CUDA cache cleanup."""
reduce_memory_usage()
# ============================================================================
# TODO 3: Image Processor - Handles image preprocessing and refinement
# ============================================================================
class ImageProcessor:
"""Handles image preprocessing and refinement operations."""
def __init__(self):
"""Initialize the image processor."""
pass
@staticmethod
def apply_refinement(image: Image.Image) -> Image.Image:
"""
Apply SSD-1B (Segmind Stable Diffusion) refinement to improve input image quality.
Loads refiner lazily and unloads after use to conserve VRAM.
Args:
image: Input PIL Image
Returns:
Refined PIL Image
"""
refiner = StateManager.get_refiner()
if refiner is None:
print("Loading SSD-1B Refiner (Segmind Stable Diffusion)...")
refiner = ImageRefiner(device="cpu", use_fp16=False)
StateManager.set_refiner(refiner)
# Apply refinement
refined_image = refiner.refine(
image,
strength=0.3, # Subtle refinement to preserve original
guidance_scale=7.5,
num_inference_steps=20,
prompt="high quality, detailed, sharp, clean",
negative_prompt="blurry, low quality, distorted, artifacts"
)
return refined_image
@staticmethod
def preprocess_single_image(image: Image.Image, use_refinement: bool = False) -> Tuple[str, Image.Image]:
"""
Preprocess a single input image with memory-efficient operations.
Background removal happens first, then refinement if requested.
Args:
image: The input image
use_refinement: Whether to apply SSD-1B refinement after background removal
Returns:
Tuple of (trial_id, processed_image)
"""
trial_id = str(uuid.uuid4())
# Memory-efficient preprocessing with no gradients (background removal first)
pipeline = StateManager.get_pipeline()
with torch.no_grad():
with torch.cuda.amp.autocast(enabled=torch.cuda.is_available()):
processed_image = pipeline.preprocess_image(image)
# Apply refinement after background removal if requested
if use_refinement:
print("Applying image refinement after background removal...")
processed_image = ImageProcessor.apply_refinement(processed_image)
# Clean up refiner VRAM before TRELLIS processing
refiner = StateManager.get_refiner()
if refiner is not None:
refiner.unload()
torch.cuda.empty_cache()
# High-quality image saving - no compression artifacts
processed_image.save(f"{TMP_DIR}/{trial_id}.png", quality=100, subsampling=0)
return trial_id, processed_image
@staticmethod
def preprocess_multiple_images(images: List[Image.Image], use_refinement: bool = False) -> Tuple[str, List[Image.Image]]:
"""
Preprocess multiple input images for multi-view 3D reconstruction.
Background removal happens first, then refinement if requested.
Memory optimization: Process and save images one by one to reduce peak memory usage.
Args:
images: List of input images
use_refinement: Whether to apply SSD-1B refinement after background removal
Returns:
Tuple of (trial_id, processed_images)
"""
trial_id = str(uuid.uuid4())
processed_images = []
# Process images one by one to minimize memory usage
pipeline = StateManager.get_pipeline()
for i, img in enumerate(images):
# Background removal first
processed_img = pipeline.preprocess_image(img)
# Apply refinement after background removal if requested
if use_refinement:
print(f"Refining image {i+1}/{len(images)} after background removal...")
processed_img = ImageProcessor.apply_refinement(processed_img)
# High-quality image saving for multi-view - no compression artifacts
processed_img.save(f"{TMP_DIR}/{trial_id}_{i}.png", quality=100, subsampling=0)
processed_images.append(processed_img)
# Force cleanup of intermediate objects
del img
torch.cuda.empty_cache()
# Clean up refiner after processing all images
if use_refinement:
refiner = StateManager.get_refiner()
if refiner is not None:
refiner.unload()
torch.cuda.empty_cache()
return trial_id, processed_images
# ============================================================================
# TODO 4: Video Renderer - Handles video creation
# ============================================================================
class VideoRenderer:
"""Handles video rendering operations."""
@staticmethod
def _convert_frame_to_uint8(frame: Any) -> np.ndarray:
"""
Convert frame to uint8 numpy array, handling both tensors and arrays.
Args:
frame: Frame as tensor or numpy array
Returns:
uint8 numpy array
"""
if hasattr(frame, 'cpu'):
# Tensor: (C, H, W) -> (H, W, C), scale to [0, 255]
frame = frame.detach().cpu().numpy().transpose(1, 2, 0) * 255
return np.clip(frame, 0, 255).astype(np.uint8)
else:
# Already numpy: handle NaN/Inf and ensure uint8
frame = np.nan_to_num(frame, nan=0, posinf=255, neginf=0)
return np.asarray(frame, dtype=np.uint8)
@staticmethod
def create_side_by_side_video(
color_frames: List[Any],
normal_frames: List[Any],
output_path: str,
fps: int = 15,
quality: int = 8
) -> None:
"""
Create side-by-side video of color and normal renderings.
Args:
color_frames: List of color rendered frames
normal_frames: List of normal map frames
output_path: Output video file path
fps: Frames per second
quality: Video quality (1-10, higher is better)
"""
# Process and combine all frames
combined_frames = [
np.concatenate([
VideoRenderer._convert_frame_to_uint8(color),
VideoRenderer._convert_frame_to_uint8(normal)
], axis=1)
for color, normal in zip(color_frames, normal_frames)
]
imageio.mimsave(output_path, combined_frames, fps=fps, quality=quality)
del combined_frames
class ModelGenerator:
"""Handles 3D model generation from images."""
@staticmethod
def pack_model_state(gs: Gaussian, mesh: MeshExtractResult, trial_id: str) -> Dict[str, Any]:
"""
Pack model state while keeping tensors on GPU to avoid unnecessary CPU transfers.
Memory optimization: Only move to CPU when actually needed for serialization.
Args:
gs: Gaussian splat representation
mesh: Mesh extraction result
trial_id: Trial identifier
Returns:
Dictionary containing packed model state
"""
return {
'gaussian': {
**gs.init_params,
'_xyz': gs._xyz, # Keep on GPU
'_features_dc': gs._features_dc, # Keep on GPU
'_scaling': gs._scaling, # Keep on GPU
'_rotation': gs._rotation, # Keep on GPU
'_opacity': gs._opacity, # Keep on GPU
},
'mesh': {
'vertices': mesh.vertices, # Keep on GPU
'faces': mesh.faces, # Keep on GPU
},
'trial_id': trial_id,
}
@staticmethod
def unpack_model_state(state: Dict[str, Any]) -> Tuple[Gaussian, edict, str]:
"""
Unpack model state efficiently - tensors are already on GPU from pack_state.
Memory optimization: Avoid redundant tensor creation and device transfers.
Args:
state: Packed model state dictionary
Returns:
Tuple of (Gaussian, mesh, trial_id)
"""
gs = Gaussian(
aabb=state['gaussian']['aabb'],
sh_degree=state['gaussian']['sh_degree'],
mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
scaling_bias=state['gaussian']['scaling_bias'],
opacity_bias=state['gaussian']['opacity_bias'],
scaling_activation=state['gaussian']['scaling_activation'],
)
# Tensors are already on GPU from pack_state - direct assignment
gs._xyz = state['gaussian']['_xyz']
gs._features_dc = state['gaussian']['_features_dc']
gs._scaling = state['gaussian']['_scaling']
gs._rotation = state['gaussian']['_rotation']
gs._opacity = state['gaussian']['_opacity']
mesh = edict(
vertices=state['mesh']['vertices'], # Already on GPU
faces=state['mesh']['faces'], # Already on GPU
)
return gs, mesh, state['trial_id']
@staticmethod
def generate_from_single_image(
trial_id: str,
params: GenerationParams
) -> Tuple[Dict[str, Any], str]:
"""
Convert a single image to a 3D model.
Args:
trial_id: The uuid of the trial
params: Generation parameters
Returns:
Tuple of (model_state, video_path)
"""
MemoryManager.reduce_memory()
seed = params.seed
if params.randomize_seed:
seed = np.random.randint(0, MAX_SEED)
pipeline = StateManager.get_pipeline()
with Image.open(f"{TMP_DIR}/{trial_id}.png") as image:
# Memory optimization: Ensure clean state before inference
MemoryManager.reduce_memory()
with torch.inference_mode():
# Critical memory optimization before heavy computation
MemoryManager.reduce_memory()
# Get resize dimensions, ensuring they're valid
resize_width = st.session_state.get("resize_width", 518)
resize_height = st.session_state.get("resize_height", 518)
outputs = pipeline.run(
image,
seed=seed,
formats=["gaussian", "mesh"],
preprocess_image=False,
target_size=(int(resize_width), int(resize_height)),
sparse_structure_sampler_params={
"steps": params.ss_sampling_steps,
"cfg_strength": params.ss_guidance_strength,
},
slat_sampler_params={
"steps": params.slat_sampling_steps,
"cfg_strength": params.slat_guidance_strength,
},
)
# Clean up immediately after inference
del image
MemoryManager.reduce_memory()
# Extract gaussian and mesh for video rendering
gaussian = outputs['gaussian'][0]
mesh = outputs['mesh'][0]
# Clean up outputs immediately after extraction
del outputs
MemoryManager.reduce_memory()
# Render videos with reduced frames for memory efficiency
video_color = render_utils.render_video(gaussian, num_frames=60)['color']
video_normal = render_utils.render_video(mesh, num_frames=60)['normal']
# Generate new trial ID for video output
video_trial_id = str(uuid.uuid4())
video_path = f"{TMP_DIR}/{video_trial_id}.mp4"
os.makedirs(os.path.dirname(video_path), exist_ok=True)
# Create video using streaming approach to minimize memory usage
VideoRenderer.create_side_by_side_video(video_color, video_normal, video_path, fps=15, quality=8)
# Clean up video arrays immediately after streaming creation
del video_color, video_normal
torch.cuda.empty_cache()
gc.collect()
# Pack state for GLB extraction - keeps tensors on GPU
state = ModelGenerator.pack_model_state(gaussian, mesh, video_trial_id)
# Early cleanup - gaussian and mesh are now in state
del gaussian, mesh
MemoryManager.reduce_memory()
return state, video_path
@staticmethod
def generate_from_multiple_images(
trial_id: str,
num_images: int,
batch_size: int,
params: GenerationParams
) -> Tuple[Dict[str, Any], str]:
"""
Convert multiple images to a 3D model using multi-view conditioning.
Args:
trial_id: The uuid of the trial
num_images: Number of images in this batch
batch_size: Number of images to process simultaneously
params: Generation parameters
Returns:
Tuple of (model_state, video_path)
"""
MemoryManager.reduce_memory()
seed = params.seed
if params.randomize_seed:
seed = np.random.randint(0, MAX_SEED)
# Adaptive batch sizing based on available memory
original_batch_size = batch_size
if torch.cuda.is_available():
free_memory = torch.cuda.get_device_properties(0).total_memory - torch.cuda.memory_allocated()
free_memory_gb = free_memory / (1024**3)
# Adaptive batch sizing for memory efficiency
if free_memory_gb < 8.0:
batch_size = min(batch_size, 1) # Very limited memory
if batch_size != original_batch_size:
print(f"Low memory detected ({free_memory_gb:.1f}GB free). Reducing batch size to {batch_size}.")
elif free_memory_gb < 12.0:
batch_size = min(batch_size, 2) # Limited memory
if batch_size != original_batch_size:
print(f"Moderate memory detected ({free_memory_gb:.1f}GB free). Adjusting batch size to {batch_size}.")
# Ensure batch size doesn't exceed number of images
batch_size = min(batch_size, num_images)
# Load all images for multi-view conditioning
print(f"Loading {num_images} images for multi-view conditioning...")
images = []
for j in range(num_images):
image = Image.open(f"{TMP_DIR}/{trial_id}_{j}.png")
images.append(image)
# Get multi-view conditioning by passing all images at once
pipeline = StateManager.get_pipeline()
with torch.inference_mode():
cond = pipeline.get_cond(images, target_size=(st.session_state.get("resize_width", 518), st.session_state.get("resize_height", 518)))
# Analyze contradiction for multi-view inputs
contradiction = pipeline.analyze_contradiction(cond)
# Store analysis results in session state for use in generation
st.session_state['generation_cond'] = cond
st.session_state['generation_contradiction'] = contradiction
# Check if auto-adjust guidance is enabled
auto_adjust_enabled = st.session_state.get(f"auto_adjust_{'multi' if cond.get('multi_view', False) else 'single'}", False)
# Display guidance information
if auto_adjust_enabled and cond.get('multi_view', False):
# Show contradiction analysis for multi-view auto-adjust
if contradiction < 1.0:
st.success(f"Multi-view consistency: Good ({contradiction:.2f}) | Guidance auto-optimized")
elif contradiction < 3.0:
st.warning(f"Multi-view consistency: Moderate ({contradiction:.2f}) | Guidance auto-optimized")
else:
st.error(f"Multi-view consistency: Poor ({contradiction:.2f}) | Guidance auto-optimized")
elif auto_adjust_enabled:
# Single view with auto-adjust
st.info("Single-view generation | Guidance auto-optimized")
else:
# Manual guidance mode
guidance_display = "Manual guidance mode"
if cond.get('multi_view', False):
guidance_display += f" (contradiction: {contradiction:.2f})"
st.info(guidance_display)
# Clean up images immediately
del images
MemoryManager.reduce_memory()
torch.manual_seed(seed)
with torch.inference_mode():
coords = pipeline.sample_sparse_structure(cond, 1, {
"steps": params.ss_sampling_steps,
"cfg_strength": params.ss_guidance_strength,
})
slat = pipeline.sample_slat(cond, coords, {
"steps": params.slat_sampling_steps,
"cfg_strength": params.slat_guidance_strength,
})
# Clean up conditioning data immediately after sampling
del cond, coords
MemoryManager.reduce_memory()
# Critical memory cleanup before mesh decoding
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Decode SLAT without inference mode (rendering needs autograd compatibility)
outputs = pipeline.decode_slat(slat, ["gaussian", "mesh"])
del slat
# Extract gaussian and mesh for video rendering
gaussian = outputs['gaussian'][0]
mesh = outputs['mesh'][0]
# Clean up outputs immediately after extraction
del outputs
MemoryManager.reduce_memory()
# Render videos with reduced frames for memory efficiency
video_color = render_utils.render_video(gaussian, num_frames=60)['color']
video_normal = render_utils.render_video(mesh, num_frames=60)['normal']
# Generate new trial ID for video output
video_trial_id = str(uuid.uuid4())
video_path = f"{TMP_DIR}/{video_trial_id}.mp4"
os.makedirs(os.path.dirname(video_path), exist_ok=True)
# Create video using streaming approach to minimize memory usage
VideoRenderer.create_side_by_side_video(video_color, video_normal, video_path, fps=15, quality=8)
# Clean up video arrays immediately after streaming creation
del video_color, video_normal
torch.cuda.empty_cache()
gc.collect()
# Pack state for GLB extraction - keeps tensors on GPU
state = ModelGenerator.pack_model_state(gaussian, mesh, video_trial_id)
# Early cleanup - gaussian and mesh are now in state
del gaussian, mesh
MemoryManager.reduce_memory()
return state, video_path
class GLBExporter:
"""Handles GLB file export operations."""
@staticmethod
def extract(state: Dict[str, Any], params: ExportParams) -> Tuple[str, str]:
"""
Extract a GLB file from the 3D model.
Args:
state: The state of the generated 3D model
params: Export parameters
Returns:
Tuple of (glb_path, glb_path) for consistency
"""
# Aggressive memory cleanup before GLB extraction
MemoryManager.reduce_memory()
# Unpack state into gaussian splats and mesh
gs, mesh, trial_id = ModelGenerator.unpack_model_state(state)
# Clear state dict immediately as we've unpacked it
del state
MemoryManager.reduce_memory()
# Generate GLB (postprocessing may need autograd compatibility)
glb = postprocessing_utils.to_glb(
gs, mesh,
simplify=params.mesh_simplify,
texture_size=params.texture_size,
fill_holes_resolution=params.fill_holes_resolution,
fill_holes_num_views=params.fill_holes_num_views,
verbose=False
)
# Save GLB file
glb_path = f"{TMP_DIR}/{trial_id}.glb"
glb.export(glb_path)
# Clean up large objects immediately
del gs, mesh, glb
torch.cuda.empty_cache()
gc.collect()
return glb_path, glb_path
# ============================================================================
# TODO 7: Single Image UI - Handles single image interface
# ============================================================================
class SingleImageUI:
"""Handles the single image generation UI."""
@staticmethod
def render() -> None:
"""Render the single image generation interface."""
st.header("Single Image Generation")
col1, col2 = st.columns(2)
with col1:
SingleImageUI._render_input_column()
with col2:
SingleImageUI._render_output_column()
# Examples section
SingleImageUI._render_examples()
@staticmethod
def _render_input_column() -> None:
"""Render the input column."""
st.subheader("Input")
# File uploader - Streamlit manages its state automatically
uploaded_file = st.file_uploader(
"Upload Image",
type=["png", "jpg", "jpeg"],
key="single_image",
label_visibility="visible"
)
# If uploader is empty but we have preserved data, restore the StateManager image
if not uploaded_file and st.session_state.get("_preserved_single_image"):
StateManager.set_uploaded_image(st.session_state["_preserved_single_image"])
# Handle uploaded image
if uploaded_file is not None:
new_image = Image.open(uploaded_file)
current_image = StateManager.get_uploaded_image()
if current_image is None or current_image != new_image:
StateManager.set_uploaded_image(new_image)
# Reset all generated content when new image is uploaded
st.session_state.processed_preview = None
StateManager.set_generated_video(None)
StateManager.set_generated_glb(None)
StateManager.set_generated_state(None)
# Force cleanup when switching images
MemoryManager.cleanup_session_state(clear_all=False)
st.rerun()
# Show uploaded image
uploaded_image = StateManager.get_uploaded_image()
if uploaded_image is not None:
# Image preprocessing options above the uploaded image
with st.expander("Image Preprocessing Options", expanded=True):
col1, col2 = st.columns(2)
with col1:
# Image refinement checkbox
use_refinement = st.checkbox(
"Apply Image Refinement (SSD-1B)",
value=False, # Default to False to avoid confusion
help="Enhance input quality with SSD-1B after background removal. Adds ~5-7s processing time.",
key="refinement_single_input"
)
with col2:
# Resize dimensions moved here from advanced settings
# Valid resize options (multiples of 14)
valid_sizes = [i * 14 for i in range(19, 74)] # 266 to 1022
resize_width = st.selectbox(
"Resize Width",
options=valid_sizes,
index=valid_sizes.index(518) if 518 in valid_sizes else 0,
key="resize_width_single",
help="Width to resize images to for conditioning model (must be multiple of 14)",
format_func=lambda x: f"{x}px"
)
# Store in session state for use in generation
st.session_state["resize_width"] = resize_width
resize_height = st.selectbox(
"Resize Height",
options=valid_sizes,
index=valid_sizes.index(518) if 518 in valid_sizes else 0,
key="resize_height_single",
help="Height to resize images to for conditioning model (must be multiple of 14)",
format_func=lambda x: f"{x}px"
)
# Store in session state for use in generation
st.session_state["resize_height"] = resize_height
st.markdown("**Uploaded Image:**")
st.image(uploaded_image, use_container_width=True)
# Auto-process and show final processed preview
pipeline = StateManager.get_pipeline()
if pipeline is not None:
# Use current resize dimensions if set, otherwise use default
current_width = st.session_state.get("resize_width", 518)
current_height = st.session_state.get("resize_height", 518)
target_size = (current_width, current_height)
# Check if we need to regenerate preview due to size change or refinement setting change
current_preview_size = st.session_state.get("processed_preview_size")
current_refinement_setting = st.session_state.get("current_refinement_setting", False)
needs_regeneration = (current_preview_size != target_size or
current_refinement_setting != use_refinement or
'processed_preview' not in st.session_state or
st.session_state.processed_preview is None)
if needs_regeneration:
with torch.no_grad(), torch.cuda.amp.autocast(enabled=torch.cuda.is_available()):
processed_image = pipeline.preprocess_image(uploaded_image, target_size)
# Apply refinement if enabled
if use_refinement:
processed_image = ImageProcessor.apply_refinement(processed_image)
# Clean up refiner VRAM
refiner = StateManager.get_refiner()
if refiner is not None:
refiner.unload()
torch.cuda.empty_cache()
# Store preview and track settings used
if 'processed_preview' in st.session_state and st.session_state.processed_preview is not None:
old_preview = st.session_state.processed_preview
del old_preview
st.session_state.processed_preview = processed_image
st.session_state.processed_preview_size = target_size
st.session_state.current_refinement_setting = use_refinement
else:
processed_image = st.session_state.processed_preview
preview_label = f"**Processed Preview - {target_size[0]}×{target_size[1]}**"
if use_refinement:
preview_label += " *(with refinement)*"
else:
preview_label += " *(background removed)*"
st.markdown(preview_label)
st.image(processed_image, use_container_width=True)
else:
st.info("Processed preview will be shown after pipeline loads")
st.session_state.processed_preview = None
@staticmethod
def _render_generation_panel(
uploaded_data: Any,
is_multi_image: bool,
video_key: str,
glb_key: str,
download_key: str,
generate_key: str,
seed_key: str,
randomize_key: str,
ss_strength_key: str,
ss_steps_key: str,
slat_strength_key: str,
slat_steps_key: str,
simplify_key: str,
texture_key: str,
batch_size_key: str = None,
trial_id: str = None
) -> None:
"""
Render complete generation panel with settings, button, and output preview.
This is a fully reusable component for both single and multi-image tabs.
Args:
uploaded_data: Uploaded image or list of images
is_multi_image: True for multi-image, False for single-image
trial_id: Unique identifier for this trial (used for UI keys)
video_key: Unique key for video clear button
glb_key: Unique key for GLB clear button
download_key: Unique key for download button
generate_key: Unique key for generate button
seed_key: Unique key for seed slider
randomize_key: Unique key for randomize checkbox
ss_strength_key: Unique key for sparse structure guidance strength
ss_steps_key: Unique key for sparse structure sampling steps
slat_strength_key: Unique key for slat guidance strength
slat_steps_key: Unique key for slat sampling steps
simplify_key: Unique key for mesh simplify slider
texture_key: Unique key for texture size slider
batch_size_key: Unique key for batch size slider (multi-image only)
"""
# Generate trial_id if not provided