jayman commited on
Commit
9a7d141
·
verified ·
1 Parent(s): 3fdcc43

Update gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +72 -40
gradio_app.py CHANGED
@@ -1,12 +1,15 @@
1
  # Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
2
  # except for the third-party components listed below.
3
 
 
4
  import os
5
  import random
6
  import shutil
 
7
  import subprocess
8
  import sys
9
  import time
 
10
  import uuid
11
  from glob import glob
12
  from pathlib import Path
@@ -23,22 +26,36 @@ from hy3dgen.shapegen.utils import logger
23
 
24
  MAX_SEED = 1e7
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  # Rebuild texture native extensions against the currently installed PyTorch.
28
  # This avoids ABI mismatch from the bundled prebuilt wheel.
29
  if True:
30
- import importlib
31
- import os
32
- import site
33
- import spaces
34
- import subprocess
35
- import sys
36
- import urllib.request
37
- from pathlib import Path
38
-
39
  os.environ.setdefault("MAX_JOBS", "1")
40
  os.environ.setdefault("TORCH_CUDA_ARCH_LIST", "8.9")
41
  os.environ.setdefault("CUDAARCHS", "89")
 
 
 
42
 
43
  rasterizer_root = Path("/home/user/app/hy3dgen/texgen/custom_rasterizer")
44
  kernel_dir = rasterizer_root / "lib" / "custom_rasterizer_kernel"
@@ -89,7 +106,6 @@ if True:
89
  check=True,
90
  )
91
 
92
- # Refresh current Python process so imports installed during startup are visible.
93
  for site_dir in site.getsitepackages():
94
  if site_dir not in sys.path:
95
  sys.path.append(site_dir)
@@ -167,10 +183,6 @@ if True:
167
  importlib.invalidate_caches()
168
 
169
 
170
-
171
-
172
-
173
-
174
  def get_example_img_list():
175
  print("Loading example img list ...")
176
  return sorted(glob("./assets/example_images/**/*.png", recursive=True))
@@ -268,6 +280,47 @@ def build_model_viewer_html(save_folder, height=660, width=790, textured=False):
268
  """
269
 
270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
  def _gen_shape(
273
  caption=None,
@@ -375,7 +428,6 @@ def _gen_shape(
375
  return mesh, main_image, save_folder, stats, seed
376
 
377
 
378
-
379
  def generation_all(
380
  caption=None,
381
  image=None,
@@ -417,7 +469,8 @@ def generation_all(
417
  stats["time"]["face reduction"] = time.time() - tmp_time
418
 
419
  tmp_time = time.time()
420
- textured_mesh = texgen_worker(mesh, image)
 
421
  logger.info("---Texture Generation takes %s seconds ---" % (time.time() - tmp_time))
422
  stats["time"]["texture generation"] = time.time() - tmp_time
423
  stats["time"]["total"] = time.time() - start_time_0
@@ -444,7 +497,6 @@ def generation_all(
444
  )
445
 
446
 
447
-
448
  def shape_generation(
449
  caption=None,
450
  image=None,
@@ -714,7 +766,7 @@ def build_app():
714
  gr.HTML(f"""
715
  <div align="center">
716
  Activated Model - Shape Generation ({args.model_path}/{args.subfolder}) ;
717
- Texture Generation ({'Hunyuan3D-2' if HAS_TEXTUREGEN else 'Unavailable'})
718
  </div>
719
  """)
720
 
@@ -722,8 +774,7 @@ def build_app():
722
  gr.HTML("""
723
  <div style="margin-top: 5px;" align="center">
724
  <b>Warning: </b>
725
- Texture synthesis is disabled due to missing requirements.
726
- Check the Space logs for the exact Python traceback.
727
  </div>
728
  """)
729
 
@@ -920,25 +971,7 @@ if __name__ == "__main__":
920
 
921
  SUPPORTED_FORMATS = ["glb", "obj", "ply", "stl"]
922
 
923
- HAS_TEXTUREGEN = False
924
- if not args.disable_tex:
925
- try:
926
- from hy3dgen.texgen import Hunyuan3DPaintPipeline
927
-
928
- texgen_worker = Hunyuan3DPaintPipeline.from_pretrained(args.texgen_model_path)
929
-
930
- if args.low_vram_mode:
931
- texgen_worker.enable_model_cpu_offload()
932
-
933
- HAS_TEXTUREGEN = True
934
- except Exception as e:
935
- import traceback
936
-
937
- traceback.print_exc()
938
- print(e)
939
- print("Failed to load texture generator.")
940
- print("Please try to install requirements by following README.md")
941
- HAS_TEXTUREGEN = False
942
 
943
  HAS_T2I = True
944
  if args.enable_t23d:
@@ -986,4 +1019,3 @@ if __name__ == "__main__":
986
  app = gr.mount_gradio_app(app, demo, path="/")
987
 
988
  uvicorn.run(app, host=args.host, port=args.port)
989
-
 
1
  # Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
2
  # except for the third-party components listed below.
3
 
4
+ import importlib
5
  import os
6
  import random
7
  import shutil
8
+ import site
9
  import subprocess
10
  import sys
11
  import time
12
+ import urllib.request
13
  import uuid
14
  from glob import glob
15
  from pathlib import Path
 
26
 
27
  MAX_SEED = 1e7
28
 
29
+ texgen_worker = None
30
+ texgen_load_error = None
31
+
32
+
33
+ def reset_diffusers_module_cache():
34
+ candidates = [
35
+ Path(os.environ.get("HF_MODULES_CACHE", "/tmp/hf_modules")) / "diffusers_modules" / "local",
36
+ Path.home() / ".cache" / "huggingface" / "modules" / "diffusers_modules" / "local",
37
+ ]
38
+
39
+ for cache_path in candidates:
40
+ try:
41
+ if cache_path.exists():
42
+ print(f"Removing stale Diffusers dynamic module cache: {cache_path}")
43
+ shutil.rmtree(cache_path, ignore_errors=True)
44
+ except Exception as exc:
45
+ print(f"Could not remove Diffusers module cache {cache_path}: {exc}")
46
+
47
+ importlib.invalidate_caches()
48
+
49
 
50
  # Rebuild texture native extensions against the currently installed PyTorch.
51
  # This avoids ABI mismatch from the bundled prebuilt wheel.
52
  if True:
 
 
 
 
 
 
 
 
 
53
  os.environ.setdefault("MAX_JOBS", "1")
54
  os.environ.setdefault("TORCH_CUDA_ARCH_LIST", "8.9")
55
  os.environ.setdefault("CUDAARCHS", "89")
56
+ os.environ.setdefault("HF_MODULES_CACHE", "/tmp/hf_modules")
57
+
58
+ reset_diffusers_module_cache()
59
 
60
  rasterizer_root = Path("/home/user/app/hy3dgen/texgen/custom_rasterizer")
61
  kernel_dir = rasterizer_root / "lib" / "custom_rasterizer_kernel"
 
106
  check=True,
107
  )
108
 
 
109
  for site_dir in site.getsitepackages():
110
  if site_dir not in sys.path:
111
  sys.path.append(site_dir)
 
183
  importlib.invalidate_caches()
184
 
185
 
 
 
 
 
186
  def get_example_img_list():
187
  print("Loading example img list ...")
188
  return sorted(glob("./assets/example_images/**/*.png", recursive=True))
 
280
  """
281
 
282
 
283
+ def get_texgen_worker():
284
+ global texgen_worker, texgen_load_error
285
+
286
+ if texgen_worker is not None:
287
+ return texgen_worker
288
+
289
+ if args.disable_tex:
290
+ raise gr.Error("Texture generation is disabled with --disable_tex.")
291
+
292
+ last_error = None
293
+
294
+ for attempt in range(2):
295
+ try:
296
+ if attempt > 0:
297
+ print("Retrying texture generator after cleaning Diffusers module cache...")
298
+ reset_diffusers_module_cache()
299
+
300
+ from hy3dgen.texgen import Hunyuan3DPaintPipeline
301
+
302
+ print("Loading texture generator on demand...")
303
+ texgen_worker = Hunyuan3DPaintPipeline.from_pretrained(args.texgen_model_path)
304
+
305
+ if args.low_vram_mode:
306
+ texgen_worker.enable_model_cpu_offload()
307
+
308
+ texgen_load_error = None
309
+ print("Texture generator loaded successfully.")
310
+ return texgen_worker
311
+
312
+ except Exception as exc:
313
+ import traceback
314
+
315
+ last_error = exc
316
+ texgen_load_error = traceback.format_exc()
317
+ print(texgen_load_error)
318
+
319
+ if "diffusers_modules.local.modules" not in texgen_load_error and attempt == 0:
320
+ break
321
+
322
+ raise gr.Error(f"Texture generator failed to load: {last_error}")
323
+
324
 
325
  def _gen_shape(
326
  caption=None,
 
428
  return mesh, main_image, save_folder, stats, seed
429
 
430
 
 
431
  def generation_all(
432
  caption=None,
433
  image=None,
 
469
  stats["time"]["face reduction"] = time.time() - tmp_time
470
 
471
  tmp_time = time.time()
472
+ texgen = get_texgen_worker()
473
+ textured_mesh = texgen(mesh, image)
474
  logger.info("---Texture Generation takes %s seconds ---" % (time.time() - tmp_time))
475
  stats["time"]["texture generation"] = time.time() - tmp_time
476
  stats["time"]["total"] = time.time() - start_time_0
 
497
  )
498
 
499
 
 
500
  def shape_generation(
501
  caption=None,
502
  image=None,
 
766
  gr.HTML(f"""
767
  <div align="center">
768
  Activated Model - Shape Generation ({args.model_path}/{args.subfolder}) ;
769
+ Texture Generation ({'Hunyuan3D-2 loads on demand' if HAS_TEXTUREGEN else 'Unavailable'})
770
  </div>
771
  """)
772
 
 
774
  gr.HTML("""
775
  <div style="margin-top: 5px;" align="center">
776
  <b>Warning: </b>
777
+ Texture synthesis is disabled with --disable_tex.
 
778
  </div>
779
  """)
780
 
 
971
 
972
  SUPPORTED_FORMATS = ["glb", "obj", "ply", "stl"]
973
 
974
+ HAS_TEXTUREGEN = not args.disable_tex
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
975
 
976
  HAS_T2I = True
977
  if args.enable_t23d:
 
1019
  app = gr.mount_gradio_app(app, demo, path="/")
1020
 
1021
  uvicorn.run(app, host=args.host, port=args.port)