Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,276 +1,284 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
import
|
11 |
-
import
|
12 |
-
from
|
13 |
-
from
|
14 |
-
import
|
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 |
-
ax.
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
#
|
56 |
-
ax.
|
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 |
-
vertices = vertices
|
111 |
-
|
112 |
-
pc_coor =
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
mesh
|
117 |
-
|
118 |
-
|
119 |
-
mesh.
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
mesh.
|
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 |
-
artist_mesh.
|
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 |
-
If
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
label="
|
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 |
-
with gr.Row():
|
264 |
-
gr.
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
)
|
275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
276 |
demo.launch(share=True)
|
|
|
1 |
+
import spaces
|
2 |
+
import subprocess
|
3 |
+
# Install flash attention, skipping CUDA build if necessary
|
4 |
+
subprocess.run(
|
5 |
+
"pip install flash-attn --no-build-isolation",
|
6 |
+
env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
|
7 |
+
shell=True,
|
8 |
+
)
|
9 |
+
import os
|
10 |
+
import torch
|
11 |
+
import trimesh
|
12 |
+
from accelerate.utils import set_seed
|
13 |
+
from accelerate import Accelerator
|
14 |
+
import numpy as np
|
15 |
+
import gradio as gr
|
16 |
+
from main import load_v2
|
17 |
+
from mesh_to_pc import process_mesh_to_pc
|
18 |
+
import time
|
19 |
+
import matplotlib.pyplot as plt
|
20 |
+
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
|
21 |
+
from PIL import Image
|
22 |
+
import io
|
23 |
+
|
24 |
+
model = load_v2()
|
25 |
+
|
26 |
+
device = torch.device('cuda')
|
27 |
+
accelerator = Accelerator(
|
28 |
+
mixed_precision="fp16",
|
29 |
+
)
|
30 |
+
model = accelerator.prepare(model)
|
31 |
+
model.eval()
|
32 |
+
print("Model loaded to device")
|
33 |
+
|
34 |
+
def wireframe_render(mesh):
|
35 |
+
views = [
|
36 |
+
(90, 20), (270, 20)
|
37 |
+
]
|
38 |
+
mesh.vertices = mesh.vertices[:, [0, 2, 1]]
|
39 |
+
|
40 |
+
bounding_box = mesh.bounds
|
41 |
+
center = mesh.centroid
|
42 |
+
scale = np.ptp(bounding_box, axis=0).max()
|
43 |
+
|
44 |
+
fig = plt.figure(figsize=(10, 10))
|
45 |
+
|
46 |
+
# Function to render and return each view as an image
|
47 |
+
def render_view(mesh, azimuth, elevation):
|
48 |
+
ax = fig.add_subplot(111, projection='3d')
|
49 |
+
ax.set_axis_off()
|
50 |
+
|
51 |
+
# Extract vertices and faces for plotting
|
52 |
+
vertices = mesh.vertices
|
53 |
+
faces = mesh.faces
|
54 |
+
|
55 |
+
# Plot faces
|
56 |
+
ax.add_collection3d(Poly3DCollection(
|
57 |
+
vertices[faces],
|
58 |
+
facecolors=(0.8, 0.5, 0.2, 1.0), # Brownish yellow
|
59 |
+
edgecolors='k',
|
60 |
+
linewidths=0.5,
|
61 |
+
))
|
62 |
+
|
63 |
+
# Set limits and center the view on the object
|
64 |
+
ax.set_xlim(center[0] - scale / 2, center[0] + scale / 2)
|
65 |
+
ax.set_ylim(center[1] - scale / 2, center[1] + scale / 2)
|
66 |
+
ax.set_zlim(center[2] - scale / 2, center[2] + scale / 2)
|
67 |
+
|
68 |
+
# Set view angle
|
69 |
+
ax.view_init(elev=elevation, azim=azimuth)
|
70 |
+
|
71 |
+
# Save the figure to a buffer
|
72 |
+
buf = io.BytesIO()
|
73 |
+
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0, dpi=300)
|
74 |
+
plt.clf()
|
75 |
+
buf.seek(0)
|
76 |
+
|
77 |
+
return Image.open(buf)
|
78 |
+
|
79 |
+
# Render each view and store in a list
|
80 |
+
images = [render_view(mesh, az, el) for az, el in views]
|
81 |
+
|
82 |
+
# Combine images horizontally
|
83 |
+
widths, heights = zip(*(i.size for i in images))
|
84 |
+
total_width = sum(widths)
|
85 |
+
max_height = max(heights)
|
86 |
+
|
87 |
+
combined_image = Image.new('RGBA', (total_width, max_height))
|
88 |
+
|
89 |
+
x_offset = 0
|
90 |
+
for img in images:
|
91 |
+
combined_image.paste(img, (x_offset, 0))
|
92 |
+
x_offset += img.width
|
93 |
+
|
94 |
+
# Save the combined image
|
95 |
+
save_path = f"combined_mesh_view_{int(time.time())}.png"
|
96 |
+
combined_image.save(save_path)
|
97 |
+
|
98 |
+
plt.close(fig)
|
99 |
+
return save_path
|
100 |
+
|
101 |
+
@torch.no_grad()
|
102 |
+
def do_inference(input_3d, sample_seed=0, do_sampling=False, do_marching_cubes=False):
|
103 |
+
set_seed(sample_seed)
|
104 |
+
print("Seed value:", sample_seed)
|
105 |
+
|
106 |
+
input_mesh = trimesh.load(input_3d)
|
107 |
+
pc_list, mesh_list = process_mesh_to_pc([input_mesh], marching_cubes = do_marching_cubes)
|
108 |
+
pc_normal = pc_list[0] # 4096, 6
|
109 |
+
mesh = mesh_list[0]
|
110 |
+
vertices = mesh.vertices
|
111 |
+
|
112 |
+
pc_coor = pc_normal[:, :3]
|
113 |
+
normals = pc_normal[:, 3:]
|
114 |
+
|
115 |
+
bounds = np.array([vertices.min(axis=0), vertices.max(axis=0)])
|
116 |
+
# scale mesh and pc
|
117 |
+
vertices = vertices - (bounds[0] + bounds[1])[None, :] / 2
|
118 |
+
vertices = vertices / (bounds[1] - bounds[0]).max()
|
119 |
+
mesh.vertices = vertices
|
120 |
+
pc_coor = pc_coor - (bounds[0] + bounds[1])[None, :] / 2
|
121 |
+
pc_coor = pc_coor / (bounds[1] - bounds[0]).max()
|
122 |
+
|
123 |
+
mesh.merge_vertices()
|
124 |
+
mesh.update_faces(mesh.nondegenerate_faces())
|
125 |
+
mesh.update_faces(mesh.unique_faces())
|
126 |
+
mesh.remove_unreferenced_vertices()
|
127 |
+
mesh.fix_normals()
|
128 |
+
if mesh.visual.vertex_colors is not None:
|
129 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
130 |
+
|
131 |
+
mesh.visual.vertex_colors = np.tile(orange_color, (mesh.vertices.shape[0], 1))
|
132 |
+
else:
|
133 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
134 |
+
mesh.visual.vertex_colors = np.tile(orange_color, (mesh.vertices.shape[0], 1))
|
135 |
+
input_save_name = f"processed_input_{int(time.time())}.obj"
|
136 |
+
mesh.export(input_save_name)
|
137 |
+
input_render_res = wireframe_render(mesh)
|
138 |
+
|
139 |
+
pc_coor = pc_coor / np.abs(pc_coor).max() * 0.99 # input should be from -1 to 1
|
140 |
+
|
141 |
+
assert (np.linalg.norm(normals, axis=-1) > 0.99).all(), "normals should be unit vectors, something wrong"
|
142 |
+
normalized_pc_normal = np.concatenate([pc_coor, normals], axis=-1, dtype=np.float16)
|
143 |
+
|
144 |
+
input = torch.tensor(normalized_pc_normal, dtype=torch.float16, device=device)[None]
|
145 |
+
print("Data loaded")
|
146 |
+
|
147 |
+
# with accelerator.autocast():
|
148 |
+
with accelerator.autocast():
|
149 |
+
outputs = model(input, do_sampling)
|
150 |
+
print("Model inference done")
|
151 |
+
recon_mesh = outputs[0]
|
152 |
+
|
153 |
+
valid_mask = torch.all(~torch.isnan(recon_mesh.reshape((-1, 9))), dim=1)
|
154 |
+
recon_mesh = recon_mesh[valid_mask] # nvalid_face x 3 x 3
|
155 |
+
vertices = recon_mesh.reshape(-1, 3).cpu()
|
156 |
+
vertices_index = np.arange(len(vertices)) # 0, 1, ..., 3 x face
|
157 |
+
triangles = vertices_index.reshape(-1, 3)
|
158 |
+
|
159 |
+
artist_mesh = trimesh.Trimesh(vertices=vertices, faces=triangles, force="mesh",
|
160 |
+
merge_primitives=True)
|
161 |
+
|
162 |
+
artist_mesh.merge_vertices()
|
163 |
+
artist_mesh.update_faces(artist_mesh.nondegenerate_faces())
|
164 |
+
artist_mesh.update_faces(artist_mesh.unique_faces())
|
165 |
+
artist_mesh.remove_unreferenced_vertices()
|
166 |
+
artist_mesh.fix_normals()
|
167 |
+
|
168 |
+
if artist_mesh.visual.vertex_colors is not None:
|
169 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
170 |
+
|
171 |
+
artist_mesh.visual.vertex_colors = np.tile(orange_color, (artist_mesh.vertices.shape[0], 1))
|
172 |
+
else:
|
173 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
174 |
+
artist_mesh.visual.vertex_colors = np.tile(orange_color, (artist_mesh.vertices.shape[0], 1))
|
175 |
+
|
176 |
+
num_faces = len(artist_mesh.faces)
|
177 |
+
|
178 |
+
brown_color = np.array([165, 42, 42, 255], dtype=np.uint8)
|
179 |
+
face_colors = np.tile(brown_color, (num_faces, 1))
|
180 |
+
|
181 |
+
artist_mesh.visual.face_colors = face_colors
|
182 |
+
# add time stamp to avoid cache
|
183 |
+
save_name = f"output_{int(time.time())}.obj"
|
184 |
+
artist_mesh.export(save_name)
|
185 |
+
output_render = wireframe_render(artist_mesh)
|
186 |
+
return input_save_name, input_render_res, save_name, output_render
|
187 |
+
|
188 |
+
|
189 |
+
_HEADER_ = '''
|
190 |
+
<h2><b>Official ? Gradio Demo</b></h2><h2><a href='https://github.com/buaacyw/MeshAnything' target='_blank'><b>MeshAnything V2: Artist-Created Mesh Generation With Adjacent Mesh Tokenization</b></a></h2>
|
191 |
+
|
192 |
+
**MeshAnything** converts any 3D representation into meshes created by human artists, i.e., Artist-Created Meshes (AMs).
|
193 |
+
|
194 |
+
Code: <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>GitHub</a>. Arxiv Paper: <a href='https://arxiv.org/abs/2406.10163' target='_blank'>ArXiv</a>.
|
195 |
+
|
196 |
+
??????**Important Notes:**
|
197 |
+
- Gradio doesn't support interactive wireframe rendering currently. For interactive mesh visualization, please use download the obj file and open it with MeshLab or https://3dviewer.net/.
|
198 |
+
- The input mesh will be normalized to a unit bounding box. The up vector of the input mesh should be +Y for better results. Click **Preprocess with Marching Cubes** if the input mesh is a manually created mesh.
|
199 |
+
- Limited by computational resources, MeshAnything is trained on meshes with fewer than 800 faces and cannot generate meshes with more than 800 faces. The shape of the input mesh should be sharp enough; otherwise, it will be challenging to represent it with only 800 faces. Thus, feed-forward image-to-3D methods may often produce bad results due to insufficient shape quality.
|
200 |
+
- For point cloud input, please refer to our github repo <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>GitHub</a>.
|
201 |
+
'''
|
202 |
+
|
203 |
+
|
204 |
+
_CITE_ = r"""
|
205 |
+
If MeshAnything is helpful, please help to ? the <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>Github Repo</a>. Thanks!
|
206 |
+
---
|
207 |
+
? **License**
|
208 |
+
|
209 |
+
S-Lab-1.0 LICENSE. Please refer to the [LICENSE file](https://github.com/buaacyw/GaussianEditor/blob/master/LICENSE.txt) for details.
|
210 |
+
|
211 |
+
? **Contact**
|
212 |
+
|
213 |
+
If you have any questions, feel free to open a discussion or contact us at <b>yiwen002@e.ntu.edu.sg</b>.
|
214 |
+
|
215 |
+
"""
|
216 |
+
output_model_obj = gr.Model3D(
|
217 |
+
label="Generated Mesh (OBJ Format)",
|
218 |
+
clear_color=[1, 1, 1, 1],
|
219 |
+
)
|
220 |
+
preprocess_model_obj = gr.Model3D(
|
221 |
+
label="Processed Input Mesh (OBJ Format)",
|
222 |
+
clear_color=[1, 1, 1, 1],
|
223 |
+
)
|
224 |
+
input_image_render = gr.Image(
|
225 |
+
label="Wireframe Render of Processed Input Mesh",
|
226 |
+
)
|
227 |
+
output_image_render = gr.Image(
|
228 |
+
label="Wireframe Render of Generated Mesh",
|
229 |
+
)
|
230 |
+
with (gr.Blocks() as demo):
|
231 |
+
gr.Markdown(_HEADER_)
|
232 |
+
with gr.Row(variant="panel"):
|
233 |
+
with gr.Column():
|
234 |
+
with gr.Row():
|
235 |
+
input_3d = gr.Model3D(
|
236 |
+
label="Input Mesh",
|
237 |
+
clear_color=[1,1,1,1],
|
238 |
+
)
|
239 |
+
|
240 |
+
with gr.Row():
|
241 |
+
with gr.Group():
|
242 |
+
do_marching_cubes = gr.Checkbox(label="Preprocess with Marching Cubes", value=False)
|
243 |
+
do_sampling = gr.Checkbox(label="Random Sampling", value=False)
|
244 |
+
sample_seed = gr.Number(value=0, label="Seed Value", precision=0)
|
245 |
+
|
246 |
+
with gr.Row():
|
247 |
+
submit = gr.Button("Generate", elem_id="generate", variant="primary")
|
248 |
+
|
249 |
+
with gr.Row(variant="panel"):
|
250 |
+
mesh_examples = gr.Examples(
|
251 |
+
examples=[
|
252 |
+
os.path.join("examples", img_name) for img_name in sorted(os.listdir("examples"))
|
253 |
+
],
|
254 |
+
inputs=input_3d,
|
255 |
+
outputs=[preprocess_model_obj, input_image_render, output_model_obj, output_image_render],
|
256 |
+
fn=do_inference,
|
257 |
+
cache_examples = False,
|
258 |
+
examples_per_page=10
|
259 |
+
)
|
260 |
+
with gr.Column():
|
261 |
+
with gr.Row():
|
262 |
+
input_image_render.render()
|
263 |
+
with gr.Row():
|
264 |
+
with gr.Tab("OBJ"):
|
265 |
+
preprocess_model_obj.render()
|
266 |
+
with gr.Row():
|
267 |
+
output_image_render.render()
|
268 |
+
with gr.Row():
|
269 |
+
with gr.Tab("OBJ"):
|
270 |
+
output_model_obj.render()
|
271 |
+
with gr.Row():
|
272 |
+
gr.Markdown('''Try click random sampling and different <b>Seed Value</b> if the result is unsatisfying''')
|
273 |
+
|
274 |
+
gr.Markdown(_CITE_)
|
275 |
+
|
276 |
+
mv_images = gr.State()
|
277 |
+
|
278 |
+
submit.click(
|
279 |
+
fn=do_inference,
|
280 |
+
inputs=[input_3d, sample_seed, do_sampling, do_marching_cubes],
|
281 |
+
outputs=[preprocess_model_obj, input_image_render, output_model_obj, output_image_render],
|
282 |
+
)
|
283 |
+
|
284 |
demo.launch(share=True)
|