jiadisu Claude Opus 4.6 commited on
Commit
1b389ac
·
1 Parent(s): df7d56b

Switch to Gradio SDK + ZeroGPU for HF Spaces

Browse files

- README.md: sdk: gradio (required for ZeroGPU)
- app.py: add @spaces.GPU(duration=300) decorator
- packages.txt: system deps (ffmpeg, libsndfile1)
- requirements.txt: add spaces, gradio, flash-attn, magi_compiler

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Files changed (4) hide show
  1. README.md +2 -2
  2. app.py +13 -27
  3. packages.txt +2 -0
  4. requirements.txt +9 -0
README.md CHANGED
@@ -3,9 +3,9 @@ title: daVinci-MagiHuman
3
  emoji: 🎬
4
  colorFrom: blue
5
  colorTo: purple
6
- sdk: docker
 
7
  app_port: 7860
8
- suggested_hardware: a100-large
9
  ---
10
 
11
  <div align="center">
 
3
  emoji: 🎬
4
  colorFrom: blue
5
  colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.23.0
8
  app_port: 7860
 
9
  ---
10
 
11
  <div align="center">
app.py CHANGED
@@ -2,7 +2,7 @@
2
  """
3
  Gradio frontend for daVinci-MagiHuman distilled model.
4
 
5
- Designed for Hugging Face Spaces (A100-80GB GPU).
6
  Accepts an image + text prompt + duration, generates audio-video output.
7
  """
8
 
@@ -12,25 +12,19 @@ import sys
12
  import tempfile
13
  import uuid
14
 
 
 
15
  # ---------------------------------------------------------------------------
16
- # 1. Download all model weights from HF Hub (runs once, cached afterwards)
17
  # ---------------------------------------------------------------------------
18
- # HF Spaces persistent storage: /data (survives restarts if enabled)
19
- # Fallback to /tmp/models if /data is not available.
20
  MODEL_ROOT = os.environ.get("MODEL_ROOT", "/data/models")
21
  os.makedirs(MODEL_ROOT, exist_ok=True)
22
 
23
- # HF repo → local sub-directory mapping
24
  HF_REPOS = {
25
- # Project's own weights
26
  "GAIR-NLP/daVinci-MagiHuman": {
27
- "subdir": ".", # download to MODEL_ROOT root
28
- "allow_patterns": [
29
- "distill/**",
30
- "turbo_vae/**",
31
- ],
32
  },
33
- # Third-party open-source models
34
  "stabilityai/stable-audio-open-1.0": {
35
  "subdir": "audio",
36
  },
@@ -51,9 +45,8 @@ def download_models():
51
 
52
  for repo_id, spec in HF_REPOS.items():
53
  local_dir = os.path.join(MODEL_ROOT, spec["subdir"])
54
- # Simple check: if directory already has files, skip download
55
  if os.path.isdir(local_dir) and os.listdir(local_dir):
56
- print(f"[download] {repo_id} → {local_dir} (already cached, skipping)")
57
  continue
58
 
59
  print(f"[download] {repo_id} → {local_dir} (downloading …)")
@@ -77,10 +70,8 @@ print("[app] Checking / downloading model weights …")
77
  download_models()
78
 
79
  # ---------------------------------------------------------------------------
80
- # 2. Environment bootstrap – must happen BEFORE any inference imports
81
  # ---------------------------------------------------------------------------
82
- # HF Spaces launches a single process; we simulate the minimal distributed
83
- # environment that the pipeline expects (world_size=1, rank=0).
84
  os.environ.setdefault("MASTER_ADDR", "localhost")
85
  os.environ.setdefault("MASTER_PORT", "29500")
86
  os.environ.setdefault("RANK", "0")
@@ -88,12 +79,10 @@ os.environ.setdefault("WORLD_SIZE", "1")
88
  os.environ.setdefault("LOCAL_RANK", "0")
89
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
90
 
91
- # Project root must be on sys.path so `inference.*` imports resolve.
92
  PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
93
  if PROJECT_ROOT not in sys.path:
94
  sys.path.insert(0, PROJECT_ROOT)
95
 
96
- # Build the config JSON that maps to the downloaded paths.
97
  CONFIG_OVERRIDES = {
98
  "engine_config": {
99
  "load": os.path.join(MODEL_ROOT, "distill"),
@@ -112,19 +101,17 @@ CONFIG_OVERRIDES = {
112
  },
113
  }
114
 
115
- # Write a temporary config JSON that parse_config() can pick up via CLI args.
116
  _tmp_config = os.path.join(tempfile.gettempdir(), "magihuman_config.json")
117
  with open(_tmp_config, "w") as f:
118
  json.dump(CONFIG_OVERRIDES, f)
119
 
120
- # Inject the config path into sys.argv so that parse_config() finds it.
121
  sys.argv = [sys.argv[0], "--config-load-path", _tmp_config]
122
 
123
  # ---------------------------------------------------------------------------
124
- # 3. Initialize infrastructure & build pipeline (runs once at startup)
125
  # ---------------------------------------------------------------------------
126
  import gradio as gr
127
- import torch # noqa: E402
128
 
129
  from inference.infra import initialize_infra
130
  from inference.common import parse_config
@@ -142,8 +129,10 @@ print("[app] Pipeline ready.")
142
 
143
 
144
  # ---------------------------------------------------------------------------
145
- # 4. Inference wrapper
 
146
  # ---------------------------------------------------------------------------
 
147
  def generate_video(
148
  image,
149
  prompt: str,
@@ -156,9 +145,7 @@ def generate_video(
156
  if not prompt or not prompt.strip():
157
  raise gr.Error("Please enter a text prompt.")
158
 
159
- # Gradio passes a filepath (str) for gr.Image(type="filepath")
160
  image_path = image
161
-
162
  output_dir = tempfile.mkdtemp(prefix="magihuman_")
163
  save_prefix = os.path.join(output_dir, f"output_{uuid.uuid4().hex[:8]}")
164
 
@@ -228,7 +215,6 @@ with gr.Blocks(title=TITLE, theme=gr.themes.Soft()) as demo:
228
  outputs=[video_output],
229
  )
230
 
231
- # Pre-loaded example (uses bundled assets from the repo)
232
  example_prompt_path = os.path.join(PROJECT_ROOT, "example/assets/prompt.txt")
233
  example_prompt = "A person talking in a living room."
234
  if os.path.exists(example_prompt_path):
 
2
  """
3
  Gradio frontend for daVinci-MagiHuman distilled model.
4
 
5
+ Designed for Hugging Face Spaces with ZeroGPU (Gradio SDK).
6
  Accepts an image + text prompt + duration, generates audio-video output.
7
  """
8
 
 
12
  import tempfile
13
  import uuid
14
 
15
+ import spaces
16
+
17
  # ---------------------------------------------------------------------------
18
+ # 1. Download all model weights from HF Hub (runs on CPU, cached)
19
  # ---------------------------------------------------------------------------
 
 
20
  MODEL_ROOT = os.environ.get("MODEL_ROOT", "/data/models")
21
  os.makedirs(MODEL_ROOT, exist_ok=True)
22
 
 
23
  HF_REPOS = {
 
24
  "GAIR-NLP/daVinci-MagiHuman": {
25
+ "subdir": ".",
26
+ "allow_patterns": ["distill/**", "turbo_vae/**"],
 
 
 
27
  },
 
28
  "stabilityai/stable-audio-open-1.0": {
29
  "subdir": "audio",
30
  },
 
45
 
46
  for repo_id, spec in HF_REPOS.items():
47
  local_dir = os.path.join(MODEL_ROOT, spec["subdir"])
 
48
  if os.path.isdir(local_dir) and os.listdir(local_dir):
49
+ print(f"[download] {repo_id} → {local_dir} (cached, skipping)")
50
  continue
51
 
52
  print(f"[download] {repo_id} → {local_dir} (downloading …)")
 
70
  download_models()
71
 
72
  # ---------------------------------------------------------------------------
73
+ # 2. Environment bootstrap
74
  # ---------------------------------------------------------------------------
 
 
75
  os.environ.setdefault("MASTER_ADDR", "localhost")
76
  os.environ.setdefault("MASTER_PORT", "29500")
77
  os.environ.setdefault("RANK", "0")
 
79
  os.environ.setdefault("LOCAL_RANK", "0")
80
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
81
 
 
82
  PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
83
  if PROJECT_ROOT not in sys.path:
84
  sys.path.insert(0, PROJECT_ROOT)
85
 
 
86
  CONFIG_OVERRIDES = {
87
  "engine_config": {
88
  "load": os.path.join(MODEL_ROOT, "distill"),
 
101
  },
102
  }
103
 
 
104
  _tmp_config = os.path.join(tempfile.gettempdir(), "magihuman_config.json")
105
  with open(_tmp_config, "w") as f:
106
  json.dump(CONFIG_OVERRIDES, f)
107
 
 
108
  sys.argv = [sys.argv[0], "--config-load-path", _tmp_config]
109
 
110
  # ---------------------------------------------------------------------------
111
+ # 3. Initialize infrastructure & build pipeline (on CPU at startup)
112
  # ---------------------------------------------------------------------------
113
  import gradio as gr
114
+ import torch
115
 
116
  from inference.infra import initialize_infra
117
  from inference.common import parse_config
 
129
 
130
 
131
  # ---------------------------------------------------------------------------
132
+ # 4. Inference wrapper — @spaces.GPU requests a ZeroGPU allocation
133
+ # duration= sets the max GPU time in seconds (default 60, max 300)
134
  # ---------------------------------------------------------------------------
135
+ @spaces.GPU(duration=300)
136
  def generate_video(
137
  image,
138
  prompt: str,
 
145
  if not prompt or not prompt.strip():
146
  raise gr.Error("Please enter a text prompt.")
147
 
 
148
  image_path = image
 
149
  output_dir = tempfile.mkdtemp(prefix="magihuman_")
150
  save_prefix = os.path.join(output_dir, f"output_{uuid.uuid4().hex[:8]}")
151
 
 
215
  outputs=[video_output],
216
  )
217
 
 
218
  example_prompt_path = os.path.join(PROJECT_ROOT, "example/assets/prompt.txt")
219
  example_prompt = "A person talking in a living room."
220
  if os.path.exists(example_prompt_path):
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+ libsndfile1-dev
requirements.txt CHANGED
@@ -1,3 +1,12 @@
 
 
 
 
 
 
 
 
 
1
  accelerate==1.10.1
2
  av==15.1.0
3
  beautifulsoup4
 
1
+ # -- HF Spaces / Gradio SDK additions --
2
+ spaces
3
+ gradio
4
+ huggingface_hub
5
+ soundfile
6
+ flash-attn
7
+ magi_compiler @ git+https://github.com/sandai/MagiCompiler.git
8
+
9
+ # -- Original project deps --
10
  accelerate==1.10.1
11
  av==15.1.0
12
  beautifulsoup4