davidvgilmore commited on
Commit
435c3c4
·
verified ·
1 Parent(s): 674de53

Upload gradio_app.py with huggingface_hub

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