Huiwenshi commited on
Commit
243b12d
·
verified ·
1 Parent(s): 978c889

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. hg_app.py +1 -1
  2. hg_app_bak.py +404 -0
hg_app.py CHANGED
@@ -413,4 +413,4 @@ if __name__ == '__main__':
413
 
414
  demo = build_app()
415
  app = gr.mount_gradio_app(app, demo, path="/")
416
- uvicorn.run(app)
 
413
 
414
  demo = build_app()
415
  app = gr.mount_gradio_app(app, demo, path="/")
416
+ uvicorn.run(app, host="0.0.0.0", port=7860)
hg_app_bak.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pip install gradio==3.39.0
2
+ import os
3
+ import subprocess
4
+ def install_cuda_toolkit():
5
+ # CUDA_TOOLKIT_URL = "https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda_11.8.0_520.61.05_linux.run"
6
+ CUDA_TOOLKIT_URL = "https://developer.download.nvidia.com/compute/cuda/12.2.0/local_installers/cuda_12.2.0_535.54.03_linux.run"
7
+ CUDA_TOOLKIT_FILE = "/tmp/%s" % os.path.basename(CUDA_TOOLKIT_URL)
8
+ subprocess.call(["wget", "-q", CUDA_TOOLKIT_URL, "-O", CUDA_TOOLKIT_FILE])
9
+ subprocess.call(["chmod", "+x", CUDA_TOOLKIT_FILE])
10
+ subprocess.call([CUDA_TOOLKIT_FILE, "--silent", "--toolkit"])
11
+
12
+ os.environ["CUDA_HOME"] = "/usr/local/cuda"
13
+ os.environ["PATH"] = "%s/bin:%s" % (os.environ["CUDA_HOME"], os.environ["PATH"])
14
+ os.environ["LD_LIBRARY_PATH"] = "%s/lib:%s" % (
15
+ os.environ["CUDA_HOME"],
16
+ "" if "LD_LIBRARY_PATH" not in os.environ else os.environ["LD_LIBRARY_PATH"],
17
+ )
18
+ # Fix: arch_list[-1] += '+PTX'; IndexError: list index out of range
19
+ os.environ["TORCH_CUDA_ARCH_LIST"] = "8.0;8.6"
20
+
21
+ install_cuda_toolkit()
22
+ os.system("cd /home/user/app/hy3dgen/texgen/differentiable_renderer/ && bash compile_mesh_painter.sh")
23
+ os.system("cd /home/user/app/hy3dgen/texgen/custom_rasterizer && pip install .")
24
+ # os.system("cd /home/user/app/hy3dgen/texgen/custom_rasterizer && CUDA_HOME=/usr/local/cuda FORCE_CUDA=1 TORCH_CUDA_ARCH_LIST='8.0;8.6;8.9;9.0' python setup.py install")
25
+
26
+ import shutil
27
+ import time
28
+ from glob import glob
29
+ import gradio as gr
30
+ import torch
31
+ from gradio_litmodel3d import LitModel3D
32
+
33
+ import spaces
34
+
35
+ def get_example_img_list():
36
+ print('Loading example img list ...')
37
+ return sorted(glob('./assets/example_images/*.png'))
38
+
39
+
40
+ def get_example_txt_list():
41
+ print('Loading example txt list ...')
42
+ txt_list = list()
43
+ for line in open('./assets/example_prompts.txt'):
44
+ txt_list.append(line.strip())
45
+ return txt_list
46
+
47
+
48
+ def gen_save_folder(max_size=60):
49
+ os.makedirs(SAVE_DIR, exist_ok=True)
50
+ exists = set(int(_) for _ in os.listdir(SAVE_DIR) if not _.startswith("."))
51
+ cur_id = min(set(range(max_size)) - exists) if len(exists) < max_size else -1
52
+ if os.path.exists(f"{SAVE_DIR}/{(cur_id + 1) % max_size}"):
53
+ shutil.rmtree(f"{SAVE_DIR}/{(cur_id + 1) % max_size}")
54
+ print(f"remove {SAVE_DIR}/{(cur_id + 1) % max_size} success !!!")
55
+ save_folder = f"{SAVE_DIR}/{max(0, cur_id)}"
56
+ os.makedirs(save_folder, exist_ok=True)
57
+ print(f"mkdir {save_folder} suceess !!!")
58
+ return save_folder
59
+
60
+
61
+ def export_mesh(mesh, save_folder, textured=False):
62
+ if textured:
63
+ path = os.path.join(save_folder, f'textured_mesh.glb')
64
+ else:
65
+ path = os.path.join(save_folder, f'white_mesh.glb')
66
+ mesh.export(path, include_normals=textured)
67
+ return path
68
+
69
+
70
+ def build_model_viewer_html(save_folder, height=660, width=790, textured=False):
71
+ if textured:
72
+ related_path = f"./textured_mesh.glb"
73
+ template_name = './assets/modelviewer-textured-template.html'
74
+ output_html_path = os.path.join(save_folder, f'textured_mesh.html')
75
+ else:
76
+ related_path = f"./white_mesh.glb"
77
+ template_name = './assets/modelviewer-template.html'
78
+ output_html_path = os.path.join(save_folder, f'white_mesh.html')
79
+
80
+ with open(os.path.join(CURRENT_DIR, template_name), 'r') as f:
81
+ template_html = f.read()
82
+ obj_html = f"""
83
+ <div class="column is-mobile is-centered">
84
+ <model-viewer style="height: {height - 10}px; width: {width}px;" rotation-per-second="10deg" id="modelViewer"
85
+ src="{related_path}/" disable-tap
86
+ environment-image="neutral" auto-rotate camera-target="0m 0m 0m" orientation="0deg 0deg 170deg" shadow-intensity=".9"
87
+ ar auto-rotate camera-controls>
88
+ </model-viewer>
89
+ </div>
90
+ """
91
+
92
+ with open(output_html_path, 'w') as f:
93
+ f.write(template_html.replace('<model-viewer>', obj_html))
94
+
95
+ iframe_tag = f'<iframe src="file/{output_html_path}" height="{height}" width="100%" frameborder="0"></iframe>'
96
+ print(f'Find html {output_html_path}, {os.path.exists(output_html_path)}')
97
+
98
+ return f"""
99
+ <div style='height: {height}; width: 100%;'>
100
+ {iframe_tag}
101
+ </div>
102
+ """
103
+
104
+ @spaces.GPU(duration=60)
105
+ def _gen_shape(
106
+ caption,
107
+ image,
108
+ steps=50,
109
+ guidance_scale=7.5,
110
+ seed=1234,
111
+ octree_resolution=256,
112
+ check_box_rembg=False,
113
+ ):
114
+ if caption: print('prompt is', caption)
115
+ save_folder = gen_save_folder()
116
+ stats = {}
117
+ time_meta = {}
118
+ start_time_0 = time.time()
119
+
120
+ image_path = ''
121
+ if image is None:
122
+ start_time = time.time()
123
+ image = t2i_worker(caption)
124
+ time_meta['text2image'] = time.time() - start_time
125
+
126
+ image.save(os.path.join(save_folder, 'input.png'))
127
+
128
+ print(image.mode)
129
+ if check_box_rembg or image.mode == "RGB":
130
+ start_time = time.time()
131
+ image = rmbg_worker(image.convert('RGB'))
132
+ time_meta['rembg'] = time.time() - start_time
133
+
134
+ image.save(os.path.join(save_folder, 'rembg.png'))
135
+
136
+ # image to white model
137
+ start_time = time.time()
138
+
139
+ generator = torch.Generator()
140
+ generator = generator.manual_seed(int(seed))
141
+ mesh = i23d_worker(
142
+ image=image,
143
+ num_inference_steps=steps,
144
+ guidance_scale=guidance_scale,
145
+ generator=generator,
146
+ octree_resolution=octree_resolution
147
+ )[0]
148
+
149
+ mesh = FloaterRemover()(mesh)
150
+ mesh = DegenerateFaceRemover()(mesh)
151
+ mesh = FaceReducer()(mesh)
152
+
153
+ stats['number_of_faces'] = mesh.faces.shape[0]
154
+ stats['number_of_vertices'] = mesh.vertices.shape[0]
155
+
156
+ time_meta['image_to_textured_3d'] = {'total': time.time() - start_time}
157
+ time_meta['total'] = time.time() - start_time_0
158
+ stats['time'] = time_meta
159
+ return mesh, save_folder
160
+
161
+ @spaces.GPU(duration=80)
162
+ def generation_all(
163
+ caption,
164
+ image,
165
+ steps=50,
166
+ guidance_scale=7.5,
167
+ seed=1234,
168
+ octree_resolution=256,
169
+ check_box_rembg=False
170
+ ):
171
+ mesh, save_folder = _gen_shape(
172
+ caption,
173
+ image,
174
+ steps=steps,
175
+ guidance_scale=guidance_scale,
176
+ seed=seed,
177
+ octree_resolution=octree_resolution,
178
+ check_box_rembg=check_box_rembg
179
+ )
180
+ path = export_mesh(mesh, save_folder, textured=False)
181
+ model_viewer_html = build_model_viewer_html(save_folder, height=596, width=700)
182
+
183
+ textured_mesh = texgen_worker(mesh, image)
184
+ path_textured = export_mesh(textured_mesh, save_folder, textured=True)
185
+ model_viewer_html_textured = build_model_viewer_html(save_folder, height=596, width=700, textured=True)
186
+
187
+ return (
188
+ gr.update(value=path, visible=True),
189
+ gr.update(value=path_textured, visible=True),
190
+ gr.update(value=path, visible=True),
191
+ gr.update(value=path_textured, visible=True),
192
+ # model_viewer_html,
193
+ # model_viewer_html_textured,
194
+ )
195
+
196
+ @spaces.GPU(duration=30)
197
+ def shape_generation(
198
+ caption,
199
+ image,
200
+ steps=50,
201
+ guidance_scale=7.5,
202
+ seed=1234,
203
+ octree_resolution=256,
204
+ check_box_rembg=False,
205
+ ):
206
+ mesh, save_folder = _gen_shape(
207
+ caption,
208
+ image,
209
+ steps=steps,
210
+ guidance_scale=guidance_scale,
211
+ seed=seed,
212
+ octree_resolution=octree_resolution,
213
+ check_box_rembg=check_box_rembg
214
+ )
215
+
216
+ path = export_mesh(mesh, save_folder, textured=False)
217
+ model_viewer_html = build_model_viewer_html(save_folder, height=596, width=700)
218
+
219
+ return (
220
+ gr.update(value=path, visible=True),
221
+ gr.update(value=path, visible=True),
222
+ # model_viewer_html,
223
+ )
224
+
225
+
226
+ def build_app():
227
+ title_html = """
228
+ <div style="font-size: 2em; font-weight: bold; text-align: center; margin-bottom: 20px">
229
+
230
+ Hunyuan3D-2: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation
231
+ </div>
232
+ <div align="center">
233
+ Tencent Hunyuan3D Team
234
+ </div>
235
+ <div align="center">
236
+ <a href="https://github.com/tencent/Hunyuan3D-1">Github Page</a> &ensp;
237
+ <a href="http://3d-models.hunyuan.tencent.com">Homepage</a> &ensp;
238
+ <a href="https://arxiv.org/pdf/2411.02293">Technical Report</a> &ensp;
239
+ <a href="https://huggingface.co/Tencent/Hunyuan3D-2"> Models</a> &ensp;
240
+ </div>
241
+ """
242
+ css = """
243
+ .json-output {
244
+ height: 578px;
245
+ }
246
+ .json-output .json-holder {
247
+ height: 538px;
248
+ overflow-y: scroll;
249
+ }
250
+ """
251
+
252
+ with gr.Blocks(theme=gr.themes.Base(), css=css, title='Hunyuan-3D-2.0') as demo:
253
+ # if not gr.__version__.startswith('4'): gr.HTML(title_html)
254
+ gr.HTML(title_html)
255
+
256
+ with gr.Row():
257
+ with gr.Column(scale=2):
258
+ with gr.Tabs() as tabs_prompt:
259
+ with gr.Tab('Image Prompt', id='tab_img_prompt') as tab_ip:
260
+ image = gr.Image(label='Image', type='pil', image_mode='RGBA', height=290)
261
+ with gr.Row():
262
+ check_box_rembg = gr.Checkbox(value=True, label='Remove Background')
263
+
264
+ with gr.Tab('Text Prompt', id='tab_txt_prompt') as tab_tp:
265
+ caption = gr.Textbox(label='Text Prompt',
266
+ placeholder='HunyuanDiT will be used to generate image.',
267
+ info='Example: A 3D model of a cute cat, white background')
268
+
269
+ with gr.Accordion('Advanced Options', open=False):
270
+ num_steps = gr.Slider(maximum=50, minimum=20, value=30, step=1, label='Inference Steps')
271
+ octree_resolution = gr.Dropdown([256, 384, 512], value=256, label='Octree Resolution')
272
+ cfg_scale = gr.Number(value=5.5, label='Guidance Scale')
273
+ seed = gr.Slider(maximum=1e7, minimum=0, value=1234, label='Seed')
274
+
275
+ with gr.Group():
276
+ btn = gr.Button(value='Generate Shape Only', variant='primary')
277
+ btn_all = gr.Button(value='Generate Shape and Texture', variant='primary')
278
+
279
+ with gr.Group():
280
+ file_out = gr.File(label="File", visible=False)
281
+ file_out2 = gr.File(label="File", visible=False)
282
+
283
+ with gr.Column(scale=5):
284
+ with gr.Tabs():
285
+ with gr.Tab('Generated Mesh') as mesh1:
286
+ mesh_output1 = LitModel3D(
287
+ label="3D Model1",
288
+ exposure=10.0,
289
+ height=600,
290
+ visible=True,
291
+ clear_color=[0.0, 0.0, 0.0, 0.0],
292
+ tonemapping="aces",
293
+ contrast=1.0,
294
+ scale=1.0,
295
+ )
296
+ # html_output1 = gr.HTML(HTML_OUTPUT_PLACEHOLDER, label='Output')
297
+ with gr.Tab('Generated Textured Mesh') as mesh2:
298
+ # html_output2 = gr.HTML(HTML_OUTPUT_PLACEHOLDER, label='Output')
299
+ mesh_output2 = LitModel3D(
300
+ label="3D Model2",
301
+ exposure=10.0,
302
+ height=600,
303
+ visible=True,
304
+ clear_color=[0.0, 0.0, 0.0, 0.0],
305
+ tonemapping="aces",
306
+ contrast=1.0,
307
+ scale=1.0,
308
+ )
309
+
310
+ with gr.Column(scale=2):
311
+ with gr.Tabs() as gallery:
312
+ with gr.Tab('Image to 3D Gallery', id='tab_img_gallery') as tab_gi:
313
+ with gr.Row():
314
+ gr.Examples(examples=example_is, inputs=[image],
315
+ label="Image Prompts", examples_per_page=18)
316
+
317
+ with gr.Tab('Text to 3D Gallery', id='tab_txt_gallery') as tab_gt:
318
+ with gr.Row():
319
+ gr.Examples(examples=example_ts, inputs=[caption],
320
+ label="Text Prompts", examples_per_page=18)
321
+
322
+ tab_gi.select(fn=lambda: gr.update(selected='tab_img_prompt'), outputs=tabs_prompt)
323
+ tab_gt.select(fn=lambda: gr.update(selected='tab_txt_prompt'), outputs=tabs_prompt)
324
+
325
+ btn.click(
326
+ shape_generation,
327
+ inputs=[
328
+ caption,
329
+ image,
330
+ num_steps,
331
+ cfg_scale,
332
+ seed,
333
+ octree_resolution,
334
+ check_box_rembg,
335
+ ],
336
+ # outputs=[file_out, html_output1]
337
+ outputs=[file_out, mesh_output1]
338
+ ).then(
339
+ lambda: gr.update(visible=True),
340
+ outputs=[file_out],
341
+ )
342
+
343
+ btn_all.click(
344
+ generation_all,
345
+ inputs=[
346
+ caption,
347
+ image,
348
+ num_steps,
349
+ cfg_scale,
350
+ seed,
351
+ octree_resolution,
352
+ check_box_rembg,
353
+ ],
354
+ # outputs=[file_out, file_out2, html_output1, html_output2]
355
+ outputs=[file_out, file_out2, mesh_output1, mesh_output2]
356
+ ).then(
357
+ lambda: (gr.update(visible=True), gr.update(visible=True)),
358
+ outputs=[file_out, file_out2],
359
+ )
360
+
361
+ return demo
362
+
363
+
364
+ if __name__ == '__main__':
365
+ import argparse
366
+
367
+ parser = argparse.ArgumentParser()
368
+ parser.add_argument('--port', type=int, default=8080)
369
+ parser.add_argument('--cache-path', type=str, default='./gradio_cache')
370
+ args = parser.parse_args()
371
+
372
+ SAVE_DIR = args.cache_path
373
+ os.makedirs(SAVE_DIR, exist_ok=True)
374
+
375
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
376
+
377
+ HTML_OUTPUT_PLACEHOLDER = """
378
+ <div style='height: 596px; width: 100%; border-radius: 8px; border-color: #e5e7eb; order-style: solid; border-width: 1px;'></div>
379
+ """
380
+
381
+ INPUT_MESH_HTML = """
382
+ <div style='height: 490px; width: 100%; border-radius: 8px;
383
+ border-color: #e5e7eb; order-style: solid; border-width: 1px;'>
384
+ </div>
385
+ """
386
+ example_is = get_example_img_list()
387
+ example_ts = get_example_txt_list()
388
+
389
+ from hy3dgen.text2image import HunyuanDiTPipeline
390
+ from hy3dgen.shapegen import FaceReducer, FloaterRemover, DegenerateFaceRemover, \
391
+ Hunyuan3DDiTFlowMatchingPipeline
392
+ from hy3dgen.texgen import Hunyuan3DPaintPipeline
393
+ from hy3dgen.rembg import BackgroundRemover
394
+
395
+ rmbg_worker = BackgroundRemover()
396
+ t2i_worker = HunyuanDiTPipeline()
397
+ i23d_worker = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
398
+ texgen_worker = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
399
+ floater_remove_worker = FloaterRemover()
400
+ degenerate_face_remove_worker = DegenerateFaceRemover()
401
+ face_reduce_worker = FaceReducer()
402
+
403
+ demo = build_app()
404
+ demo.queue().launch()