Huiwenshi commited on
Commit
fa1970f
·
verified ·
1 Parent(s): 66e6369

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +75 -109
app.py CHANGED
@@ -34,67 +34,7 @@ from PIL import Image
34
  from einops import rearrange
35
  import pandas as pd
36
 
37
- # import sys
38
  # import spaces
39
- # import subprocess
40
- # from huggingface_hub import snapshot_download
41
-
42
- # def install_cuda_toolkit():
43
- # # CUDA_TOOLKIT_URL = "https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda_11.8.0_520.61.05_linux.run"
44
- # CUDA_TOOLKIT_URL = "https://developer.download.nvidia.com/compute/cuda/12.2.0/local_installers/cuda_12.2.0_535.54.03_linux.run"
45
- # CUDA_TOOLKIT_FILE = "/tmp/%s" % os.path.basename(CUDA_TOOLKIT_URL)
46
- # subprocess.call(["wget", "-q", CUDA_TOOLKIT_URL, "-O", CUDA_TOOLKIT_FILE])
47
- # subprocess.call(["chmod", "+x", CUDA_TOOLKIT_FILE])
48
- # subprocess.call([CUDA_TOOLKIT_FILE, "--silent", "--toolkit"])
49
-
50
- # os.environ["CUDA_HOME"] = "/usr/local/cuda"
51
- # os.environ["PATH"] = "%s/bin:%s" % (os.environ["CUDA_HOME"], os.environ["PATH"])
52
- # os.environ["LD_LIBRARY_PATH"] = "%s/lib:%s" % (
53
- # os.environ["CUDA_HOME"],
54
- # "" if "LD_LIBRARY_PATH" not in os.environ else os.environ["LD_LIBRARY_PATH"],
55
- # )
56
- # # Fix: arch_list[-1] += '+PTX'; IndexError: list index out of range
57
- # os.environ["TORCH_CUDA_ARCH_LIST"] = "8.0;8.6"
58
-
59
- # def install_requirements():
60
- # subprocess.check_call([sys.executable, "-m", "pip", "install", "git+https://github.com/NVlabs/nvdiffrast"])
61
- # subprocess.check_call([sys.executable, "-m", "pip", "install", "git+https://github.com/facebookresearch/pytorch3d@stable"])
62
-
63
- # def download_models():
64
- # os.makedirs("weights", exist_ok=True)
65
- # os.makedirs("weights/hunyuanDiT", exist_ok=True)
66
- # os.makedirs("third_party/weights/DUSt3R_ViTLarge_BaseDecoder_512_dpt", exist_ok=True)
67
- # try:
68
- # snapshot_download(
69
- # repo_id="tencent/Hunyuan3D-1",
70
- # local_dir="./weights",
71
- # resume_download=True
72
- # )
73
- # print("Successfully downloaded Hunyuan3D-1 model")
74
- # except Exception as e:
75
- # print(f"Error downloading Hunyuan3D-1: {e}")
76
- # try:
77
- # snapshot_download(
78
- # repo_id="Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers-Distilled",
79
- # local_dir="./weights/hunyuanDiT",
80
- # resume_download=True
81
- # )
82
- # print("Successfully downloaded HunyuanDiT model")
83
- # except Exception as e:
84
- # print(f"Error downloading HunyuanDiT: {e}")
85
- # try:
86
- # snapshot_download(
87
- # repo_id="naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt",
88
- # local_dir="./third_party/weights/DUSt3R_ViTLarge_BaseDecoder_512_dpt",
89
- # resume_download=True
90
- # )
91
- # print("Successfully downloaded DUSt3R model")
92
- # except Exception as e:
93
- # print(f"Error downloading DUSt3R: {e}")
94
- # install_cuda_toolkit()
95
- # install_requirements()
96
- # download_models()
97
-
98
  from infer import seed_everything, save_gif
99
  from infer import Text2Image, Removebg, Image2Views, Views2Mesh, GifRenderer
100
  from third_party.check import check_bake_available
@@ -135,7 +75,7 @@ CONST_HEADER = '''
135
  CONST_NOTE = '''
136
  ❗️❗️❗️Usage❗️❗️❗️<br>
137
 
138
- Limited by format, the model can only export *.obj mesh with vertex colors. The "texture" mod can only work on *.glb.<br>
139
  Please click "Do Rendering" to export a GIF.<br>
140
  You can click "Do Baking" to bake multi-view imgaes onto the shape.<br>
141
 
@@ -206,7 +146,6 @@ def gen_save_folder(max_size=30):
206
  print(f"mkdir {save_folder} suceess !!!")
207
  return save_folder
208
 
209
- @space.GPU(duration=120)
210
  def stage_0_t2i(text, seed, step, save_folder):
211
  dst = save_folder + '/img.png'
212
  image = worker_t2i(text, seed, step)
@@ -224,7 +163,6 @@ def stage_1_xbg(image, save_folder, force_remove):
224
  rgba.save(dst)
225
  return dst
226
 
227
- # @space.GPU
228
  def stage_2_i2v(image, seed, step, save_folder):
229
  if isinstance(image, str):
230
  image = Image.open(image)
@@ -239,16 +177,15 @@ def stage_2_i2v(image, seed, step, save_folder):
239
  show_img = Image.fromarray(show_img)
240
  return views_img, cond_img, show_img
241
 
242
- # @space.GPU
243
  def stage_3_v23(
244
  views_pil,
245
  cond_pil,
246
  seed,
247
  save_folder,
248
  target_face_count = 30000,
249
- texture_color = 'texture'
250
  ):
251
- do_texture_mapping = texture_color == 'texture'
252
  worker_v23(
253
  views_pil,
254
  cond_pil,
@@ -262,16 +199,14 @@ def stage_3_v23(
262
  obj_dst = save_folder + '/mesh_vertex_colors.obj' # gradio just only can show vertex shading
263
  return obj_dst, glb_dst
264
 
265
- # @space.GPU
266
  def stage_3p_baking(save_folder, color, bake, force, front, others, align_times):
267
- if color == "texture" and bake:
268
  obj_dst = worker_baker(save_folder, force, front, others, align_times)
269
  glb_dst = obj_dst.replace(".obj", ".glb")
270
  return glb_dst
271
  else:
272
  return None
273
 
274
- # @space.GPU
275
  def stage_4_gif(save_folder, color, bake, render):
276
  if not render: return None
277
  baked_fld_list = sorted(glob(save_folder + '/view_*/bake/mesh.obj'))
@@ -306,24 +241,24 @@ def check_image_available(image):
306
 
307
  def update_mode(mode):
308
  color_change = {
309
- 'Quick': gr.update(value='vertex'),
310
- 'Moderate': gr.update(value='texture'),
311
- 'Appearance': gr.update(value='texture')
312
  }[mode]
313
  bake_change = {
314
- 'Quick': gr.update(value=False, interactive=False, visible=False),
315
- 'Moderate': gr.update(value=False),
316
- 'Appearance': gr.update(value=BAKE_AVAILEBLE)
317
  }[mode]
318
  face_change = {
319
- 'Quick': gr.update(value=120000, maximum=300000),
320
  'Moderate': gr.update(value=60000, maximum=300000),
321
- 'Appearance': gr.update(value=10000, maximum=60000)
322
  }[mode]
323
  render_change = {
324
- 'Quick': gr.update(value=False, interactive=False, visible=False),
325
- 'Moderate': gr.update(value=True),
326
- 'Appearance': gr.update(value=True)
327
  }[mode]
328
  return color_change, bake_change, face_change, render_change
329
 
@@ -344,17 +279,17 @@ with gr.Blocks() as demo:
344
  with gr.Tab("Text to 3D"):
345
  with gr.Column():
346
  text = gr.TextArea('一只黑白相间的熊猫在白色背景上居中坐着,呈现出卡通风格和可爱氛围。',
347
- lines=3, max_lines=20, label='Input text')
348
 
349
  textgen_mode = gr.Radio(
350
- choices=['Quick', 'Moderate', 'Appearance'],
351
- label="Simple settings",
352
- value='Appearance',
353
  interactive=True
354
  )
355
 
356
  with gr.Accordion("Custom settings", open=False):
357
- textgen_color = gr.Radio(choices=["vertex", "texture"], label="Color", value="texture")
358
 
359
  with gr.Row():
360
  textgen_render = gr.Checkbox(
@@ -412,12 +347,12 @@ with gr.Blocks() as demo:
412
  )
413
  textgen_other_views = gr.CheckboxGroup(
414
  choices=['60°', '120°', '180°', '240°', '300°'],
415
- label="Other views Baking",
416
  value=['180°'],
417
  interactive=True,
418
  visible=True
419
  )
420
- textgen_align_times =gr.Slider(
421
  value=3,
422
  minimum=1,
423
  maximum=5,
@@ -440,19 +375,33 @@ with gr.Blocks() as demo:
440
  )
441
  textgen_color.change(
442
  fn=lambda x:[
443
- gr.update(value=(x=='texture'), interactive=(x=='texture'), visible=(x=='texture')),
444
- gr.update(value=(x=='texture'), interactive=(x=='texture'), visible=(x=='texture')),
445
  ],
446
  inputs=textgen_color,
447
- outputs=[textgen_bake, textgen_render]
 
 
 
448
  )
449
  textgen_bake.change(
450
- fn= lambda x:[gr.update(visible=x)]*4+[gr.update(value=10000, minimum=2000, maximum=60000 if x else 300000)],
 
 
 
 
 
 
451
  inputs=textgen_bake,
452
- outputs=[textgen_front_baking, textgen_other_views, textgen_align_times, textgen_force_bake, textgen_max_faces]
 
 
 
 
 
 
453
  )
454
 
455
-
456
  ### Image iutput region
457
 
458
  with gr.Tab("Image to 3D"):
@@ -463,14 +412,14 @@ with gr.Blocks() as demo:
463
  alert_message = gr.Markdown("") # for warning
464
 
465
  imggen_mode = gr.Radio(
466
- choices=['Quick', 'Moderate', 'Appearance'],
467
- label="Simple settings",
468
- value='Appearance',
469
  interactive=True
470
  )
471
 
472
  with gr.Accordion("Custom settings", open=False):
473
- imggen_color = gr.Radio(choices=["vertex", "texture"], label="Color", value="texture")
474
 
475
  with gr.Row():
476
  imggen_removebg = gr.Checkbox(
@@ -498,7 +447,7 @@ with gr.Blocks() as demo:
498
  label="Gen steps",
499
  interactive=True
500
  )
501
- imggen_max_faces =gr.Slider(
502
  value=10000,
503
  minimum=2000,
504
  maximum=60000,
@@ -522,7 +471,7 @@ with gr.Blocks() as demo:
522
  )
523
  imggen_other_views = gr.CheckboxGroup(
524
  choices=['60°', '120°', '180°', '240°', '300°'],
525
- label="Other views Baking",
526
  value=['180°'],
527
  interactive=True,
528
  visible=True
@@ -549,15 +498,33 @@ with gr.Blocks() as demo:
549
  )
550
 
551
  imggen_color.change(
552
- fn=lambda x:[gr.update(value=(x=='texture'), interactive=(x=='texture'), visible=(x=='texture'))]*2,
 
 
 
553
  inputs=imggen_color,
554
- outputs=[imggen_bake, imggen_render]
 
 
 
555
  )
556
 
557
  imggen_bake.change(
558
- fn= lambda x:[gr.update(visible=x)]*4+[gr.update(value=120000, minimum=2000, maximum=60000 if x else 300000)],
 
 
 
 
 
 
559
  inputs=imggen_bake,
560
- outputs=[imggen_front_baking, imggen_other_views, imggen_align_times, imggen_force_bake, imggen_max_faces]
 
 
 
 
 
 
561
  )
562
 
563
  with gr.Row():
@@ -566,7 +533,6 @@ with gr.Blocks() as demo:
566
  with gr.Row():
567
  gr.Examples(examples=example_is, inputs=[input_image],
568
  label="Img examples", examples_per_page=10)
569
-
570
 
571
  gr.Markdown(CONST_NOTE)
572
 
@@ -599,7 +565,7 @@ with gr.Blocks() as demo:
599
 
600
  result_3dglb_texture = gr.Model3D(
601
  clear_color=[0.0, 0.0, 0.0, 0.0],
602
- label="GLB texture color",
603
  show_label=True,
604
  visible=True,
605
  camera_position=[90, 90, None],
@@ -607,7 +573,7 @@ with gr.Blocks() as demo:
607
 
608
  result_3dglb_baked = gr.Model3D(
609
  clear_color=[0.0, 0.0, 0.0, 0.0],
610
- label="GLB baked color",
611
  show_label=True,
612
  visible=True,
613
  camera_position=[90, 90, None],
@@ -618,7 +584,7 @@ with gr.Blocks() as demo:
618
  with gr.Row():
619
  gr.Markdown(
620
  "Due to Gradio limitations, OBJ files are displayed with vertex shading only, "
621
- "while GLB files can be viewed with texture shading. <br>For the best experience, "
622
  "we recommend downloading the GLB files and opening them with 3D software "
623
  "like Blender or MeshLab."
624
  )
@@ -661,7 +627,7 @@ with gr.Blocks() as demo:
661
  fn=stage_4_gif,
662
  inputs=[save_folder, textgen_color, textgen_bake, textgen_render],
663
  outputs=[result_gif],
664
- ).success(lambda: print('Text_to_3D Done ...'))
665
 
666
 
667
  imggen_submit.click(
@@ -689,7 +655,7 @@ with gr.Blocks() as demo:
689
  fn=stage_4_gif,
690
  inputs=[save_folder, imggen_color, imggen_bake, imggen_render],
691
  outputs=[result_gif],
692
- ).success(lambda: print('Image_to_3D Done ...'))
693
 
694
  #===============================================================
695
  # start gradio server
 
34
  from einops import rearrange
35
  import pandas as pd
36
 
 
37
  # import spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  from infer import seed_everything, save_gif
39
  from infer import Text2Image, Removebg, Image2Views, Views2Mesh, GifRenderer
40
  from third_party.check import check_bake_available
 
75
  CONST_NOTE = '''
76
  ❗️❗️❗️Usage❗️❗️❗️<br>
77
 
78
+ Limited by format, the model can only export *.obj mesh with vertex colors. The "face" mod can only work on *.glb.<br>
79
  Please click "Do Rendering" to export a GIF.<br>
80
  You can click "Do Baking" to bake multi-view imgaes onto the shape.<br>
81
 
 
146
  print(f"mkdir {save_folder} suceess !!!")
147
  return save_folder
148
 
 
149
  def stage_0_t2i(text, seed, step, save_folder):
150
  dst = save_folder + '/img.png'
151
  image = worker_t2i(text, seed, step)
 
163
  rgba.save(dst)
164
  return dst
165
 
 
166
  def stage_2_i2v(image, seed, step, save_folder):
167
  if isinstance(image, str):
168
  image = Image.open(image)
 
177
  show_img = Image.fromarray(show_img)
178
  return views_img, cond_img, show_img
179
 
 
180
  def stage_3_v23(
181
  views_pil,
182
  cond_pil,
183
  seed,
184
  save_folder,
185
  target_face_count = 30000,
186
+ texture_color = 'face'
187
  ):
188
+ do_texture_mapping = texture_color == 'face'
189
  worker_v23(
190
  views_pil,
191
  cond_pil,
 
199
  obj_dst = save_folder + '/mesh_vertex_colors.obj' # gradio just only can show vertex shading
200
  return obj_dst, glb_dst
201
 
 
202
  def stage_3p_baking(save_folder, color, bake, force, front, others, align_times):
203
+ if color == "face" and bake:
204
  obj_dst = worker_baker(save_folder, force, front, others, align_times)
205
  glb_dst = obj_dst.replace(".obj", ".glb")
206
  return glb_dst
207
  else:
208
  return None
209
 
 
210
  def stage_4_gif(save_folder, color, bake, render):
211
  if not render: return None
212
  baked_fld_list = sorted(glob(save_folder + '/view_*/bake/mesh.obj'))
 
241
 
242
  def update_mode(mode):
243
  color_change = {
244
+ 'Vertex color': gr.update(value='vertex'),
245
+ 'Face color': gr.update(value='face'),
246
+ 'Baking': gr.update(value='face')
247
  }[mode]
248
  bake_change = {
249
+ 'Vertex color': gr.update(value=False, interactive=False, visible=False),
250
+ 'Face color': gr.update(value=False),
251
+ 'Baking': gr.update(value=BAKE_AVAILEBLE)
252
  }[mode]
253
  face_change = {
254
+ 'Vertex color': gr.update(value=120000, maximum=300000),
255
  'Moderate': gr.update(value=60000, maximum=300000),
256
+ 'Baking': gr.update(value=10000, maximum=60000)
257
  }[mode]
258
  render_change = {
259
+ 'Vertex color': gr.update(value=False, interactive=False, visible=False),
260
+ 'Face color': gr.update(value=True),
261
+ 'Baking': gr.update(value=True)
262
  }[mode]
263
  return color_change, bake_change, face_change, render_change
264
 
 
279
  with gr.Tab("Text to 3D"):
280
  with gr.Column():
281
  text = gr.TextArea('一只黑白相间的熊猫在白色背景上居中坐着,呈现出卡通风格和可爱氛围。',
282
+ lines=3, max_lines=20, label='Input text (within 70 words)')
283
 
284
  textgen_mode = gr.Radio(
285
+ choices=['Vertex color', 'Face color', 'Baking'],
286
+ label="Texture mode",
287
+ value='Baking',
288
  interactive=True
289
  )
290
 
291
  with gr.Accordion("Custom settings", open=False):
292
+ textgen_color = gr.Radio(choices=["vertex", "face"], label="Color", value="face")
293
 
294
  with gr.Row():
295
  textgen_render = gr.Checkbox(
 
347
  )
348
  textgen_other_views = gr.CheckboxGroup(
349
  choices=['60°', '120°', '180°', '240°', '300°'],
350
+ label="Other views baking",
351
  value=['180°'],
352
  interactive=True,
353
  visible=True
354
  )
355
+ textgen_align_times = gr.Slider(
356
  value=3,
357
  minimum=1,
358
  maximum=5,
 
375
  )
376
  textgen_color.change(
377
  fn=lambda x:[
378
+ gr.update(value=(x=='face'), interactive=(x=='face'), visible=(x=='face')),
379
+ gr.update(value=(x=='face'), interactive=(x=='face'), visible=(x=='face')),
380
  ],
381
  inputs=textgen_color,
382
+ outputs=[
383
+ textgen_bake,
384
+ textgen_render
385
+ ]
386
  )
387
  textgen_bake.change(
388
+ fn= lambda x:[
389
+ gr.update(visible=x),
390
+ gr.update(visible=x),
391
+ gr.update(visible=x),
392
+ gr.update(visible=x),
393
+ gr.update(value=10000 if x else 120000, minimum=2000, maximum=60000 if x else 300000)
394
+ ],
395
  inputs=textgen_bake,
396
+ outputs=[
397
+ textgen_front_baking,
398
+ textgen_other_views,
399
+ textgen_align_times,
400
+ textgen_force_bake,
401
+ textgen_max_faces
402
+ ]
403
  )
404
 
 
405
  ### Image iutput region
406
 
407
  with gr.Tab("Image to 3D"):
 
412
  alert_message = gr.Markdown("") # for warning
413
 
414
  imggen_mode = gr.Radio(
415
+ choices=['Vertex color', 'Face color', 'Baking'],
416
+ label="Texture mode",
417
+ value='Baking',
418
  interactive=True
419
  )
420
 
421
  with gr.Accordion("Custom settings", open=False):
422
+ imggen_color = gr.Radio(choices=["vertex", "face"], label="Color", value="face")
423
 
424
  with gr.Row():
425
  imggen_removebg = gr.Checkbox(
 
447
  label="Gen steps",
448
  interactive=True
449
  )
450
+ imggen_max_faces = gr.Slider(
451
  value=10000,
452
  minimum=2000,
453
  maximum=60000,
 
471
  )
472
  imggen_other_views = gr.CheckboxGroup(
473
  choices=['60°', '120°', '180°', '240°', '300°'],
474
+ label="Other views baking",
475
  value=['180°'],
476
  interactive=True,
477
  visible=True
 
498
  )
499
 
500
  imggen_color.change(
501
+ fn=lambda x:[
502
+ gr.update(value=(x=='face'), interactive=(x=='face'), visible=(x=='face')),
503
+ gr.update(value=(x=='face'), interactive=(x=='face'), visible=(x=='face'))
504
+ ],
505
  inputs=imggen_color,
506
+ outputs=[
507
+ imggen_bake,
508
+ imggen_render
509
+ ]
510
  )
511
 
512
  imggen_bake.change(
513
+ fn= lambda x:[
514
+ gr.update(visible=x),
515
+ gr.update(visible=x),
516
+ gr.update(visible=x),
517
+ gr.update(visible=x),
518
+ gr.update( value=10000 if x else 120000, minimum=2000, maximum=60000 if x else 300000)
519
+ ],
520
  inputs=imggen_bake,
521
+ outputs=[
522
+ imggen_front_baking,
523
+ imggen_other_views,
524
+ imggen_align_times,
525
+ imggen_force_bake,
526
+ imggen_max_faces
527
+ ]
528
  )
529
 
530
  with gr.Row():
 
533
  with gr.Row():
534
  gr.Examples(examples=example_is, inputs=[input_image],
535
  label="Img examples", examples_per_page=10)
 
536
 
537
  gr.Markdown(CONST_NOTE)
538
 
 
565
 
566
  result_3dglb_texture = gr.Model3D(
567
  clear_color=[0.0, 0.0, 0.0, 0.0],
568
+ label="GLB face color",
569
  show_label=True,
570
  visible=True,
571
  camera_position=[90, 90, None],
 
573
 
574
  result_3dglb_baked = gr.Model3D(
575
  clear_color=[0.0, 0.0, 0.0, 0.0],
576
+ label="GLB baking",
577
  show_label=True,
578
  visible=True,
579
  camera_position=[90, 90, None],
 
584
  with gr.Row():
585
  gr.Markdown(
586
  "Due to Gradio limitations, OBJ files are displayed with vertex shading only, "
587
+ "while GLB files can be viewed with face color. <br>For the best experience, "
588
  "we recommend downloading the GLB files and opening them with 3D software "
589
  "like Blender or MeshLab."
590
  )
 
627
  fn=stage_4_gif,
628
  inputs=[save_folder, textgen_color, textgen_bake, textgen_render],
629
  outputs=[result_gif],
630
+ ).success(lambda: print('Text_to_3D Done ...\n'))
631
 
632
 
633
  imggen_submit.click(
 
655
  fn=stage_4_gif,
656
  inputs=[save_folder, imggen_color, imggen_bake, imggen_render],
657
  outputs=[result_gif],
658
+ ).success(lambda: print('Image_to_3D Done ...\n'))
659
 
660
  #===============================================================
661
  # start gradio server