Spaces:
Running
on
Zero
Running
on
Zero
File size: 8,355 Bytes
f89a9bf 81d04f7 f89a9bf 81d04f7 f89a9bf |
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 |
import spaces
import os
import gradio as gr
import numpy as np
import torch
from PIL import Image
import trimesh
import random
from transformers import AutoModelForImageSegmentation
from torchvision import transforms
from huggingface_hub import hf_hub_download, snapshot_download, login
import subprocess
import shutil
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE = torch.float16
print("DEVICE: ", DEVICE)
DEFAULT_PART_FACE_NUMBER = 10000
MAX_SEED = np.iinfo(np.int32).max
HOLOPART_REPO_URL = "https://github.com/VAST-AI-Research/HoloPart"
HOLOPART_PRETRAINED_MODEL = "checkpoints/HoloPart"
TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
os.makedirs(TMP_DIR, exist_ok=True)
HOLOPART_CODE_DIR = "./holopart"
if not os.path.exists(HOLOPART_REPO_URL):
os.system(f"git clone {HOLOPART_REPO_URL} {HOLOPART_CODE_DIR}")
import sys
sys.path.append(HOLOPART_CODE_DIR)
sys.path.append(os.path.join(HOLOPART_CODE_DIR, "scripts"))
EXAMPLES = [
["./holopart/assets/example_data/000.glb", "./holopart/assets/example_data/000.png"],
["./holopart/assets/example_data/001.glb", "./holopart/assets/example_data/001.png"],
["./holopart/assets/example_data/002.glb", "./holopart/assets/example_data/002.png"],
["./holopart/assets/example_data/003.glb", "./holopart/assets/example_data/003.png"],
]
HEADER = """
# 🔮 Decompose a 3D shape into complete parts with [HoloPart](https://github.com/VAST-AI-Research/HoloPart).
### Step 1: Prepare Your Segmented Mesh
Upload a mesh with part segmentation. We recommend using these segmentation tools:
- [SAMPart3D](https://github.com/Pointcept/SAMPart3D)
- [SAMesh](https://github.com/gtangg12/samesh)
For a mesh file `mesh.glb` and corresponding face mask `mask.npy`, prepare your input using this Python code:
```python
import trimesh
import numpy as np
mesh = trimesh.load("mesh.glb", force="mesh")
mask_npy = np.load("mask.npy")
mesh_parts = []
for part_id in np.unique(mask_npy):
mesh_part = mesh.submesh([mask_npy == part_id], append=True)
mesh_parts.append(mesh_part)
mesh_parts = trimesh.Scene(mesh_parts).export("input_mesh.glb")
```
The resulting **input_mesh.glb** is your prepared input for HoloPart.
### Step 2: Click the Decompose Parts button to begin the decomposition process.
"""
from inference_holopart import prepare_data, run_holopart
from holopart.pipelines.pipeline_holopart import HoloPartPipeline
snapshot_download("VAST-AI/HoloPart", local_dir=HOLOPART_PRETRAINED_MODEL)
holopart_pipe = HoloPartPipeline.from_pretrained(HOLOPART_PRETRAINED_MODEL).to(DEVICE, DTYPE)
def start_session(req: gr.Request):
save_dir = os.path.join(TMP_DIR, str(req.session_hash))
os.makedirs(save_dir, exist_ok=True)
print("start session, mkdir", save_dir)
def end_session(req: gr.Request):
save_dir = os.path.join(TMP_DIR, str(req.session_hash))
shutil.rmtree(save_dir)
def get_random_hex():
random_bytes = os.urandom(8)
random_hex = random_bytes.hex()
return random_hex
def get_random_seed(randomize_seed, seed):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
return seed
def explode_mesh(mesh: trimesh.Scene, explode_factor: float = 0.5):
center = mesh.centroid
exploded_mesh = trimesh.Scene()
for geometry_name, geometry in mesh.geometry.items():
transform = mesh.graph[geometry_name][0]
vertices_global = trimesh.transformations.transform_points(
geometry.vertices, transform)
part_center = np.mean(vertices_global, axis=0)
direction = part_center - center
direction_length = np.linalg.norm(direction)
if direction_length > 0:
direction = direction / direction_length
displacement = direction * explode_factor
new_transform = np.copy(transform)
new_transform[:3, 3] += displacement
exploded_mesh.add_geometry(geometry, transform=new_transform, geom_name=geometry_name)
return exploded_mesh
@spaces.GPU(duration=600)
def run_full(data_path, seed=42, num_inference_steps=25, guidance_scale=3.5):
batch_size = 30
parts_data = prepare_data(data_path)
part_scene = run_holopart(
holopart_pipe,
batch=parts_data,
batch_size=batch_size,
seed=seed,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
num_chunks=1000000,
)
print("mesh extraction done")
save_dir = os.path.join(TMP_DIR, "examples")
os.makedirs(save_dir, exist_ok=True)
mesh_path = os.path.join(save_dir, f"holorpart_{get_random_hex()}.glb")
part_scene.export(mesh_path)
print("save to ", mesh_path)
exploded_mesh = explode_mesh(part_scene, 0.7)
exploded_mesh_path = os.path.join(save_dir, f"holorpart_exploded_{get_random_hex()}.glb")
exploded_mesh.export(exploded_mesh_path)
torch.cuda.empty_cache()
return mesh_path, exploded_mesh_path
@spaces.GPU(duration=600)
def run_example(data_path: str, example_image_path, seed=42, num_inference_steps=25, guidance_scale=3.5):
batch_size = 30
parts_data = prepare_data(data_path)
part_scene = run_holopart(
holopart_pipe,
batch=parts_data,
batch_size=batch_size,
seed=seed,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
num_chunks=1000000,
)
print("mesh extraction done")
save_dir = os.path.join(TMP_DIR, "examples")
os.makedirs(save_dir, exist_ok=True)
mesh_path = os.path.join(save_dir, f"holorpart_{get_random_hex()}.glb")
part_scene.export(mesh_path)
print("save to ", mesh_path)
exploded_mesh = explode_mesh(part_scene, 0.5)
exploded_mesh_path = os.path.join(save_dir, f"holorpart_exploded_{get_random_hex()}.glb")
exploded_mesh.export(exploded_mesh_path)
torch.cuda.empty_cache()
return mesh_path, exploded_mesh_path
with gr.Blocks(title="HoloPart") as demo:
gr.Markdown(HEADER)
with gr.Row():
with gr.Column():
with gr.Row():
input_mesh = gr.Model3D(label="Input Mesh")
example_image = gr.Image(label="Example Image", type="filepath", interactive=False, visible=False)
# seg_image = gr.Image(
# label="Segmentation Result", type="pil", format="png", interactive=False
# )
with gr.Accordion("Generation Settings", open=True):
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=0,
value=0
)
# randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=8,
maximum=50,
step=1,
value=25,
)
guidance_scale = gr.Slider(
label="CFG scale",
minimum=0.0,
maximum=20.0,
step=0.1,
value=3.5,
)
with gr.Row():
reduce_face = gr.Checkbox(label="Simplify Mesh", value=True, interactive=False)
# target_face_num = gr.Slider(maximum=1000000, minimum=10000, value=DEFAULT_FACE_NUMBER, label="Target Face Number")
gen_button = gr.Button("Decompose Parts", variant="primary")
with gr.Column():
model_output = gr.Model3D(label="Decomposed GLB", interactive=False)
exploded_parts_output = gr.Model3D(label="Exploded Parts", interactive=False)
with gr.Row():
examples = gr.Examples(
examples=EXAMPLES,
fn=run_example,
inputs=[input_mesh, example_image],
outputs=[model_output, exploded_parts_output],
cache_examples=True,
)
gen_button.click(
run_full,
inputs=[
input_mesh,
seed,
num_inference_steps,
guidance_scale
],
outputs=[model_output, exploded_parts_output],
)
demo.load(start_session)
demo.unload(end_session)
demo.launch()
|