crevelop/Trellis
62
1import gradio as gr2import spaces3from gradio_litmodel3d import LitModel3D4 5import os6os.environ['SPCONV_ALGO'] = 'native'7from typing import *8import torch9import numpy as np10import imageio11import uuid12from easydict import EasyDict as edict13from PIL import Image14from trellis.pipelines import TrellisImageTo3DPipeline15from trellis.representations import Gaussian, MeshExtractResult16from trellis.utils import render_utils, postprocessing_utils17 18import logging19 20# Configure logging21logging.basicConfig(22 level=logging.INFO,23 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",24 handlers=[25 logging.StreamHandler()26 ]27)28logger = logging.getLogger(__name__)29 30# Log environment variables31logger.info(f"ATTN_BACKEND: {os.environ.get('ATTN_BACKEND')}")32logger.info(f"ATTN_DEBUG: {os.environ.get('ATTN_DEBUG')}")33logger.info(f"SPARSE_BACKEND: {os.environ.get('SPARSE_BACKEND')}")34logger.info(f"SPARSE_DEBUG: {os.environ.get('SPARSE_DEBUG')}")35logger.info(f"SPARSE_ATTN_BACKEND: {os.environ.get('SPARSE_ATTN_BACKEND')}")36 37MAX_SEED = np.iinfo(np.int32).max38TMP_DIR = "/tmp/Trellis-demo"39 40os.makedirs(TMP_DIR, exist_ok=True)41 42 43def preprocess_image(image: Image.Image) -> Tuple[str, Image.Image]:44 """45 Preprocess the input image.46 47 Args:48 image (Image.Image): The input image.49 50 Returns:51 str: uuid of the trial.52 Image.Image: The preprocessed image.53 """54 trial_id = str(uuid.uuid4())55 processed_image = pipeline.preprocess_image(image)56 processed_image.save(f"{TMP_DIR}/{trial_id}.png")57 return trial_id, processed_image58 59 60def pack_state(gs: Gaussian, mesh: MeshExtractResult, trial_id: str) -> dict:61 return {62 'gaussian': {63 **gs.init_params,64 '_xyz': gs._xyz.cpu().numpy(),65 '_features_dc': gs._features_dc.cpu().numpy(),66 '_scaling': gs._scaling.cpu().numpy(),67 '_rotation': gs._rotation.cpu().numpy(),68 '_opacity': gs._opacity.cpu().numpy(),69 },70 'mesh': {71 'vertices': mesh.vertices.cpu().numpy(),72 'faces': mesh.faces.cpu().numpy(),73 },74 'trial_id': trial_id,75 }76 77 78def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:79 gs = Gaussian(80 aabb=state['gaussian']['aabb'],81 sh_degree=state['gaussian']['sh_degree'],82 mininum_kernel_size=state['gaussian']['mininum_kernel_size'],83 scaling_bias=state['gaussian']['scaling_bias'],84 opacity_bias=state['gaussian']['opacity_bias'],85 scaling_activation=state['gaussian']['scaling_activation'],86 )87 gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')88 gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')89 gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')90 gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')91 gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')92 93 mesh = edict(94 vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),95 faces=torch.tensor(state['mesh']['faces'], device='cuda'),96 )97 98 return gs, mesh, state['trial_id']99 100 101@spaces.GPU102def image_to_3d(trial_id: str, seed: int, randomize_seed: bool, ss_guidance_strength: float, ss_sampling_steps: int, slat_guidance_strength: float, slat_sampling_steps: int) -> Tuple[dict, str]:103 """104 Convert an image to a 3D model.105 106 Args:107 trial_id (str): The uuid of the trial.108 seed (int): The random seed.109 randomize_seed (bool): Whether to randomize the seed.110 ss_guidance_strength (float): The guidance strength for sparse structure generation.111 ss_sampling_steps (int): The number of sampling steps for sparse structure generation.112 slat_guidance_strength (float): The guidance strength for structured latent generation.113 slat_sampling_steps (int): The number of sampling steps for structured latent generation.114 115 Returns:116 dict: The information of the generated 3D model.117 str: The path to the video of the 3D model.118 """119 if randomize_seed:120 seed = np.random.randint(0, MAX_SEED)121 outputs = pipeline.run(122 Image.open(f"{TMP_DIR}/{trial_id}.png"),123 seed=seed,124 formats=["gaussian", "mesh"],125 preprocess_image=False,126 sparse_structure_sampler_params={127 "steps": ss_sampling_steps,128 "cfg_strength": ss_guidance_strength,129 },130 slat_sampler_params={131 "steps": slat_sampling_steps,132 "cfg_strength": slat_guidance_strength,133 },134 )135 video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']136 video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']137 video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]138 trial_id = uuid.uuid4()139 video_path = f"{TMP_DIR}/{trial_id}.mp4"140 os.makedirs(os.path.dirname(video_path), exist_ok=True)141 imageio.mimsave(video_path, video, fps=15)142 state = pack_state(outputs['gaussian'][0], outputs['mesh'][0], trial_id)143 return state, video_path144 145 146@spaces.GPU147def extract_glb(state: dict, mesh_simplify: float, texture_size: int) -> Tuple[str, str]:148 """149 Extract a GLB file from the 3D model.150 151 Args:152 state (dict): The state of the generated 3D model.153 mesh_simplify (float): The mesh simplification factor.154 texture_size (int): The texture resolution.155 156 Returns:157 str: The path to the extracted GLB file.158 """159 gs, mesh, trial_id = unpack_state(state)160 glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)161 glb_path = f"{TMP_DIR}/{trial_id}.glb"162 glb.export(glb_path)163 return glb_path, glb_path164 165 166def activate_button() -> gr.Button:167 return gr.Button(interactive=True)168 169 170def deactivate_button() -> gr.Button:171 return gr.Button(interactive=False)172 173 174with gr.Blocks() as demo:175 gr.Markdown("""176 ## Image to 3D Asset with [TRELLIS](https://trellis3d.github.io/)177 * Upload an image and click "Generate" to create a 3D asset. If the image has alpha channel, it be used as the mask. Otherwise, we use `rembg` to remove the background.178 * If you find the generated 3D asset satisfactory, click "Extract GLB" to extract the GLB file and download it.179 """)180 181 with gr.Row():182 with gr.Column():183 image_prompt = gr.Image(label="Image Prompt", image_mode="RGBA", type="pil", height=300)184 185 with gr.Accordion(label="Generation Settings", open=False):186 seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)187 randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)188 gr.Markdown("Stage 1: Sparse Structure Generation")189 with gr.Row():190 ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)191 ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)192 gr.Markdown("Stage 2: Structured Latent Generation")193 with gr.Row():194 slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)195 slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)196 197 generate_btn = gr.Button("Generate")198 199 with gr.Accordion(label="GLB Extraction Settings", open=False):200 mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)201 texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)202 203 extract_glb_btn = gr.Button("Extract GLB", interactive=False)204 205 with gr.Column():206 video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)207 model_output = LitModel3D(label="Extracted GLB", exposure=20.0, height=300)208 download_glb = gr.DownloadButton(label="Download GLB", interactive=False)209 210 trial_id = gr.Textbox(visible=False)211 output_buf = gr.State()212 213 # Example images at the bottom of the page214 with gr.Row():215 examples = gr.Examples(216 examples=[217 f'assets/example_image/{image}'218 for image in os.listdir("assets/example_image")219 ],220 inputs=[image_prompt],221 fn=preprocess_image,222 outputs=[trial_id, image_prompt],223 run_on_click=True,224 examples_per_page=64,225 )226 227 # Handlers228 image_prompt.upload(229 preprocess_image,230 inputs=[image_prompt],231 outputs=[trial_id, image_prompt],232 )233 image_prompt.clear(234 lambda: '',235 outputs=[trial_id],236 )237 238 generate_btn.click(239 image_to_3d,240 inputs=[trial_id, seed, randomize_seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps],241 outputs=[output_buf, video_output],242 ).then(243 activate_button,244 outputs=[extract_glb_btn],245 )246 247 video_output.clear(248 deactivate_button,249 outputs=[extract_glb_btn],250 )251 252 extract_glb_btn.click(253 extract_glb,254 inputs=[output_buf, mesh_simplify, texture_size],255 outputs=[model_output, download_glb],256 ).then(257 activate_button,258 outputs=[download_glb],259 )260 261 model_output.clear(262 deactivate_button,263 outputs=[download_glb],264 )265 266 267# Launch the Gradio app268if __name__ == "__main__":269 pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")270 if torch.cuda.is_available():271 pipeline.cuda()272 print("CUDA is available. Using GPU.")273 else:274 print("CUDA not available. Falling back to CPU.")275 try:276 pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8))) # Preload rembg277 except:278 pass279 print(f"CUDA Available: {torch.cuda.is_available()}")280 print(f"CUDA Version: {torch.version.cuda}")281 print(f"Number of GPUs: {torch.cuda.device_count()}")282 demo.launch(debug=True)283 