chahui commited on
Commit
5de4ad5
·
verified ·
1 Parent(s): d6ef6a3

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +7 -66
  2. requirements.txt +3 -1
app.py CHANGED
@@ -4,53 +4,19 @@ import tempfile
4
  import threading
5
  from pathlib import Path
6
 
7
- # === Runtime environment tweaks (must be set before importing heavy libs) ===
8
  os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") # force CPU
9
- os.environ.setdefault("WORLDGEN_DISABLE_EVAL", "1") # avoid KNN/eval paths if supported
10
- os.environ.setdefault("GRADIO_TEMP_DIR", "/tmp/gradio") # centralize gradio cache
11
-
12
- import nunchaku.utils
13
-
14
- def safe_get_precision(*args, **kwargs):
15
- # Always return fp32 on CPU to avoid any torch.cuda references
16
- return "fp32"
17
-
18
- # Patch module attribute
19
- nunchaku.utils.get_precision = safe_get_precision
20
-
21
- # ALSO patch the module that imported the symbol name directly
22
- try:
23
- import nunchaku.models.transformers.transformer_flux as tf
24
- tf.get_precision = safe_get_precision
25
- except Exception:
26
- # If the module isn't imported yet, it will still use our utils patch when it imports later.
27
- pass
28
 
29
  import gradio as gr
30
- import torch
31
  from worldgen import WorldGen
32
 
33
- from huggingface_hub import hf_hub_download
34
-
35
  _wg = None
36
-
37
  def get_worldgen():
38
  global _wg
39
  if _wg is None:
40
- # 確保使用公開模型且不帶 token
41
- model_path = hf_hub_download(
42
- repo_id="nunchaku-tech/nunchaku-flux.1-dev",
43
- filename="unquantized_layers.safetensors",
44
- token=None # 強制匿名模式
45
- )
46
-
47
- # 初始化 WorldGen,並指定模型路徑(如果需要)
48
- _wg = WorldGen(
49
- mode="t2s",
50
- device="cpu",
51
- low_vram=True,
52
- lora_path=None # 如果你有 LoRA 模型可以指定路徑
53
- )
54
  return _wg
55
 
56
  def _zip_directory(dir_path: Path) -> str:
@@ -62,21 +28,15 @@ def _zip_directory(dir_path: Path) -> str:
62
 
63
  def _save_scene(generated, out_dir: Path) -> Path:
64
  out_dir.mkdir(parents=True, exist_ok=True)
65
-
66
- # 1) try common object methods
67
  for meth in ("save", "export", "write", "to_disk"):
68
  if hasattr(generated, meth):
69
  getattr(generated, meth)(str(out_dir))
70
  return out_dir
71
-
72
- # 2) single-file export fallbacks
73
  for meth in ("save_as_glb", "to_glb", "save_as_ply", "to_ply"):
74
  if hasattr(generated, meth):
75
  fp = out_dir / ("scene.glb" if "glb" in meth else "scene.ply")
76
  getattr(generated, meth)(str(fp))
77
  return out_dir
78
-
79
- # 3) last resort: leave a note
80
  (out_dir / "README.txt").write_text(
81
  "No known save/export method detected. Please adjust _save_scene according to your WorldGen version."
82
  )
@@ -85,50 +45,31 @@ def _save_scene(generated, out_dir: Path) -> Path:
85
  def generate_from_text(prompt: str):
86
  if not prompt or not prompt.strip():
87
  return None, "Please enter a scene description (English works best)."
88
-
89
  wg = get_worldgen()
90
-
91
  try:
92
  result = wg.generate_world(prompt.strip())
93
  except Exception as e:
94
  return None, f"Generation failed: {e}"
95
-
96
  tmpdir = Path(tempfile.mkdtemp())
97
  out_dir = tmpdir / "worldgen_output"
98
  out_dir = _save_scene(result, out_dir)
99
  zip_path = _zip_directory(out_dir)
100
-
101
- # delayed cleanup to avoid filling the 50GB ephemeral disk
102
  def _cleanup(p: Path):
103
  try:
104
  shutil.rmtree(p, ignore_errors=True)
105
  except Exception:
106
  pass
107
-
108
- threading.Timer(300, _cleanup, args=(tmpdir,)).start() # 5 minutes later
109
-
110
  return zip_path, "Done. Download the ZIP (contains 3D assets)."
111
 
112
  with gr.Blocks(title="WorldGen • Text -> 3D Scene") as demo:
113
- gr.Markdown(
114
- """# WorldGen - Text -> 3D
115
- - CPU-only fallback is enabled. For real runs, switch the Space to a GPU (T4/A10G).
116
- - Outputs are zipped for download; temp files are cleaned shortly after each run.
117
-
118
- """
119
- )
120
  with gr.Row():
121
  with gr.Column():
122
- prompt = gr.Textbox(
123
- label="Scene prompt (English)",
124
- placeholder="a neon-lit cyberpunk street with rain reflections, highly detailed",
125
- lines=3,
126
- )
127
  btn = gr.Button("Generate 3D Scene")
128
  with gr.Column():
129
  out_zip = gr.File(label="Download output (ZIP)")
130
  status = gr.Markdown()
131
-
132
  btn.click(generate_from_text, inputs=[prompt], outputs=[out_zip, status])
133
-
134
  demo.launch()
 
4
  import threading
5
  from pathlib import Path
6
 
7
+ # === Runtime environment tweaks ===
8
  os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") # force CPU
9
+ os.environ.setdefault("WORLDGEN_DISABLE_EVAL", "1")
10
+ os.environ.setdefault("GRADIO_TEMP_DIR", "/tmp/gradio")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  import gradio as gr
 
13
  from worldgen import WorldGen
14
 
 
 
15
  _wg = None
 
16
  def get_worldgen():
17
  global _wg
18
  if _wg is None:
19
+ _wg = WorldGen(mode="t2s", device="cpu", low_vram=True, lora_path=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  return _wg
21
 
22
  def _zip_directory(dir_path: Path) -> str:
 
28
 
29
  def _save_scene(generated, out_dir: Path) -> Path:
30
  out_dir.mkdir(parents=True, exist_ok=True)
 
 
31
  for meth in ("save", "export", "write", "to_disk"):
32
  if hasattr(generated, meth):
33
  getattr(generated, meth)(str(out_dir))
34
  return out_dir
 
 
35
  for meth in ("save_as_glb", "to_glb", "save_as_ply", "to_ply"):
36
  if hasattr(generated, meth):
37
  fp = out_dir / ("scene.glb" if "glb" in meth else "scene.ply")
38
  getattr(generated, meth)(str(fp))
39
  return out_dir
 
 
40
  (out_dir / "README.txt").write_text(
41
  "No known save/export method detected. Please adjust _save_scene according to your WorldGen version."
42
  )
 
45
  def generate_from_text(prompt: str):
46
  if not prompt or not prompt.strip():
47
  return None, "Please enter a scene description (English works best)."
 
48
  wg = get_worldgen()
 
49
  try:
50
  result = wg.generate_world(prompt.strip())
51
  except Exception as e:
52
  return None, f"Generation failed: {e}"
 
53
  tmpdir = Path(tempfile.mkdtemp())
54
  out_dir = tmpdir / "worldgen_output"
55
  out_dir = _save_scene(result, out_dir)
56
  zip_path = _zip_directory(out_dir)
 
 
57
  def _cleanup(p: Path):
58
  try:
59
  shutil.rmtree(p, ignore_errors=True)
60
  except Exception:
61
  pass
62
+ threading.Timer(300, _cleanup, args=(tmpdir,)).start()
 
 
63
  return zip_path, "Done. Download the ZIP (contains 3D assets)."
64
 
65
  with gr.Blocks(title="WorldGen • Text -> 3D Scene") as demo:
66
+ gr.Markdown("# WorldGen - Text -> 3D\n- CPU-only fallback is enabled.\n- Outputs are zipped for download.")
 
 
 
 
 
 
67
  with gr.Row():
68
  with gr.Column():
69
+ prompt = gr.Textbox(label="Scene prompt (English)", placeholder="a neon-lit cyberpunk street", lines=3)
 
 
 
 
70
  btn = gr.Button("Generate 3D Scene")
71
  with gr.Column():
72
  out_zip = gr.File(label="Download output (ZIP)")
73
  status = gr.Markdown()
 
74
  btn.click(generate_from_text, inputs=[prompt], outputs=[out_zip, status])
 
75
  demo.launch()
requirements.txt CHANGED
@@ -1,4 +1,6 @@
1
  torch>=2.7
2
- # torchvision>=0.22 # uncomment if needed by your WorldGen setup
3
  websockets>=13.1
 
 
 
4
  git+https://github.com/ZiYang-xie/WorldGen.git
 
1
  torch>=2.7
 
2
  websockets>=13.1
3
+ gradio
4
+ huggingface_hub
5
+ nunchaku
6
  git+https://github.com/ZiYang-xie/WorldGen.git