Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
import os, sys, json, tempfile, subprocess, shutil, uuid, glob
|
2 |
from pathlib import Path
|
3 |
-
from typing import
|
4 |
|
5 |
import gradio as gr
|
6 |
import spaces
|
@@ -20,13 +20,13 @@ ASSETS.mkdir(exist_ok=True)
|
|
20 |
|
21 |
APP_TITLE = os.environ.get("APP_TITLE", "Foley Studio · ZeroGPU")
|
22 |
APP_TAGLINE = os.environ.get("APP_TAGLINE", "Generate scene-true foley for short clips (ZeroGPU-ready).")
|
23 |
-
PRIMARY_COLOR = os.environ.get("PRIMARY_COLOR", "#6B5BFF")
|
24 |
|
25 |
# ZeroGPU-safe defaults (tweak in Space Secrets if needed)
|
26 |
-
MAX_SECS = int(os.environ.get("MAX_SECS", "15"))
|
27 |
-
TARGET_H = int(os.environ.get("TARGET_H", "480"))
|
28 |
-
SR = int(os.environ.get("TARGET_SR", "48000"))
|
29 |
-
ZEROGPU_DURATION = int(os.environ.get("ZEROGPU_DURATION", "110"))
|
30 |
|
31 |
def sh(cmd: str):
|
32 |
print(">>", cmd)
|
@@ -44,13 +44,11 @@ def ffprobe_duration(path: str) -> float:
|
|
44 |
|
45 |
def _clone_without_lfs():
|
46 |
"""
|
47 |
-
Clone repo while skipping LFS smudge to avoid demo
|
48 |
Falls back to sparse checkout with only essential paths.
|
49 |
"""
|
50 |
if REPO_DIR.exists():
|
51 |
return
|
52 |
-
|
53 |
-
# Attempt 1: shallow clone with LFS disabled
|
54 |
try:
|
55 |
sh(
|
56 |
"GIT_LFS_SKIP_SMUDGE=1 "
|
@@ -64,7 +62,6 @@ def _clone_without_lfs():
|
|
64 |
except subprocess.CalledProcessError as e:
|
65 |
print("Shallow clone with LFS skipped failed, trying sparse checkout…", e)
|
66 |
|
67 |
-
# Attempt 2: sparse checkout minimal files
|
68 |
REPO_DIR.mkdir(parents=True, exist_ok=True)
|
69 |
sh(f"git -C {REPO_DIR} init")
|
70 |
sh(
|
@@ -82,7 +79,6 @@ def _clone_without_lfs():
|
|
82 |
"LICENSE",
|
83 |
"README.md",
|
84 |
]) + "\n")
|
85 |
-
# Try main, fallback to master
|
86 |
try:
|
87 |
sh(f"git -C {REPO_DIR} fetch --depth 1 origin main")
|
88 |
sh(f"git -C {REPO_DIR} checkout main")
|
@@ -94,7 +90,6 @@ def prepare_once():
|
|
94 |
"""Clone code (skip LFS), download weights, set env, prepare dirs."""
|
95 |
_clone_without_lfs()
|
96 |
|
97 |
-
# Ensure we can import their package later
|
98 |
if str(REPO_DIR) not in sys.path:
|
99 |
sys.path.insert(0, str(REPO_DIR))
|
100 |
|
@@ -113,21 +108,33 @@ def prepare_once():
|
|
113 |
|
114 |
prepare_once()
|
115 |
|
116 |
-
# Prefer safetensors
|
117 |
os.environ["TRANSFORMERS_PREFER_SAFETENSORS"] = "1"
|
|
|
118 |
|
119 |
-
def
|
120 |
"""
|
121 |
-
|
122 |
-
Transformers
|
123 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
cache_root = Path.home() / ".cache" / "huggingface" / "hub"
|
125 |
-
|
126 |
-
cache_root / "models--laion--larger_clap_general" / "snapshots" / "*" / "pytorch_model.bin",
|
127 |
-
cache_root / "models--laion--larger_clap_general" / "snapshots" / "*" / "model.bin",
|
128 |
cache_root / "models--laion--larger_clap_general" / "snapshots" / "*" / "*.bin",
|
129 |
-
]
|
130 |
-
for pat in patterns:
|
131 |
for f in glob.glob(str(pat)):
|
132 |
try:
|
133 |
Path(f).unlink()
|
@@ -135,14 +142,13 @@ def _purge_clap_pt_bins():
|
|
135 |
except Exception:
|
136 |
pass
|
137 |
|
138 |
-
# ----
|
139 |
try:
|
140 |
-
import audiotools # provided by
|
141 |
except Exception as e:
|
142 |
raise RuntimeError(
|
143 |
-
"Missing module 'audiotools'. Install
|
144 |
-
"'descript-audiotools' (
|
145 |
-
"to requirements.txt) and restart the Space."
|
146 |
) from e
|
147 |
|
148 |
try:
|
@@ -151,11 +157,11 @@ try:
|
|
151 |
import easydict # noqa: F401
|
152 |
except Exception as e:
|
153 |
raise RuntimeError(
|
154 |
-
"Missing config deps.
|
155 |
-
"'omegaconf>=2.3.0', 'pyyaml',
|
156 |
) from e
|
157 |
|
158 |
-
#
|
159 |
from hunyuanvideo_foley.utils.model_utils import load_model, denoise_process
|
160 |
from hunyuanvideo_foley.utils.feature_utils import feature_process
|
161 |
from hunyuanvideo_foley.utils.media_utils import merge_audio_video
|
@@ -190,7 +196,6 @@ def auto_load_models() -> str:
|
|
190 |
|
191 |
if not os.path.exists(MODEL_PATH):
|
192 |
os.makedirs(MODEL_PATH, exist_ok=True)
|
193 |
-
|
194 |
if not os.path.exists(CONFIG_PATH):
|
195 |
return f"❌ Config file not found: {CONFIG_PATH}"
|
196 |
|
@@ -199,7 +204,8 @@ def auto_load_models() -> str:
|
|
199 |
logger.info(f"MODEL_PATH: {MODEL_PATH}")
|
200 |
logger.info(f"CONFIG_PATH: {CONFIG_PATH}")
|
201 |
|
202 |
-
#
|
|
|
203 |
_purge_clap_pt_bins()
|
204 |
|
205 |
_model_dict, _cfg = load_model(MODEL_PATH, CONFIG_PATH, _device)
|
@@ -214,9 +220,9 @@ logger.info(auto_load_models())
|
|
214 |
# ========= Preprocessing =========
|
215 |
def preprocess_video(in_path: str) -> Tuple[str, float]:
|
216 |
"""
|
217 |
-
-
|
218 |
-
- Downscale to TARGET_H (keep AR), strip
|
219 |
-
- Return processed mp4 path and final duration
|
220 |
"""
|
221 |
dur = ffprobe_duration(in_path)
|
222 |
if dur == 0:
|
@@ -227,7 +233,7 @@ def preprocess_video(in_path: str) -> Tuple[str, float]:
|
|
227 |
processed = temp_dir / "proc.mp4"
|
228 |
trim_args = ["-t", str(MAX_SECS)] if dur > MAX_SECS else []
|
229 |
|
230 |
-
# Normalize
|
231 |
sh(" ".join([
|
232 |
"ffmpeg", "-y", "-i", f"\"{in_path}\"",
|
233 |
*trim_args,
|
@@ -237,7 +243,7 @@ def preprocess_video(in_path: str) -> Tuple[str, float]:
|
|
237 |
f"\"{trimmed}\""
|
238 |
]))
|
239 |
|
240 |
-
# Downscale to TARGET_H; ensure mod2 width
|
241 |
vf = f"scale=-2:{TARGET_H}:flags=bicubic"
|
242 |
sh(" ".join([
|
243 |
"ffmpeg", "-y", "-i", f"\"{trimmed}\"",
|
@@ -254,7 +260,7 @@ def preprocess_video(in_path: str) -> Tuple[str, float]:
|
|
254 |
return str(processed), final_dur
|
255 |
|
256 |
# ========= Inference (ZeroGPU) =========
|
257 |
-
@spaces.GPU(duration=ZEROGPU_DURATION)
|
258 |
@torch.inference_mode()
|
259 |
def run_model(video_path: str, prompt_text: str,
|
260 |
guidance_scale: float = 4.5,
|
|
|
1 |
import os, sys, json, tempfile, subprocess, shutil, uuid, glob
|
2 |
from pathlib import Path
|
3 |
+
from typing import Tuple, List
|
4 |
|
5 |
import gradio as gr
|
6 |
import spaces
|
|
|
20 |
|
21 |
APP_TITLE = os.environ.get("APP_TITLE", "Foley Studio · ZeroGPU")
|
22 |
APP_TAGLINE = os.environ.get("APP_TAGLINE", "Generate scene-true foley for short clips (ZeroGPU-ready).")
|
23 |
+
PRIMARY_COLOR = os.environ.get("PRIMARY_COLOR", "#6B5BFF")
|
24 |
|
25 |
# ZeroGPU-safe defaults (tweak in Space Secrets if needed)
|
26 |
+
MAX_SECS = int(os.environ.get("MAX_SECS", "15"))
|
27 |
+
TARGET_H = int(os.environ.get("TARGET_H", "480"))
|
28 |
+
SR = int(os.environ.get("TARGET_SR", "48000"))
|
29 |
+
ZEROGPU_DURATION = int(os.environ.get("ZEROGPU_DURATION", "110"))
|
30 |
|
31 |
def sh(cmd: str):
|
32 |
print(">>", cmd)
|
|
|
44 |
|
45 |
def _clone_without_lfs():
|
46 |
"""
|
47 |
+
Clone repo while skipping LFS smudge to avoid huge demo assets.
|
48 |
Falls back to sparse checkout with only essential paths.
|
49 |
"""
|
50 |
if REPO_DIR.exists():
|
51 |
return
|
|
|
|
|
52 |
try:
|
53 |
sh(
|
54 |
"GIT_LFS_SKIP_SMUDGE=1 "
|
|
|
62 |
except subprocess.CalledProcessError as e:
|
63 |
print("Shallow clone with LFS skipped failed, trying sparse checkout…", e)
|
64 |
|
|
|
65 |
REPO_DIR.mkdir(parents=True, exist_ok=True)
|
66 |
sh(f"git -C {REPO_DIR} init")
|
67 |
sh(
|
|
|
79 |
"LICENSE",
|
80 |
"README.md",
|
81 |
]) + "\n")
|
|
|
82 |
try:
|
83 |
sh(f"git -C {REPO_DIR} fetch --depth 1 origin main")
|
84 |
sh(f"git -C {REPO_DIR} checkout main")
|
|
|
90 |
"""Clone code (skip LFS), download weights, set env, prepare dirs."""
|
91 |
_clone_without_lfs()
|
92 |
|
|
|
93 |
if str(REPO_DIR) not in sys.path:
|
94 |
sys.path.insert(0, str(REPO_DIR))
|
95 |
|
|
|
108 |
|
109 |
prepare_once()
|
110 |
|
111 |
+
# Prefer safetensors & fast transfer
|
112 |
os.environ["TRANSFORMERS_PREFER_SAFETENSORS"] = "1"
|
113 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
114 |
|
115 |
+
def ensure_clap_safetensors():
|
116 |
"""
|
117 |
+
Proactively cache ONLY safetensors for laion/larger_clap_general so
|
118 |
+
Transformers never selects a stale/corrupt *.bin.
|
119 |
"""
|
120 |
+
snapshot_download(
|
121 |
+
repo_id="laion/larger_clap_general",
|
122 |
+
allow_patterns=[
|
123 |
+
"*.safetensors", "config.json", "*.json", "*.txt",
|
124 |
+
"tokenizer*", "*merges*", "*vocab*"
|
125 |
+
],
|
126 |
+
ignore_patterns=["*.bin"],
|
127 |
+
resume_download=True,
|
128 |
+
local_dir=None,
|
129 |
+
local_dir_use_symlinks=False,
|
130 |
+
)
|
131 |
+
|
132 |
+
def _purge_clap_pt_bins():
|
133 |
+
"""Remove any cached .bin for laion/larger_clap_general."""
|
134 |
cache_root = Path.home() / ".cache" / "huggingface" / "hub"
|
135 |
+
for pat in [
|
|
|
|
|
136 |
cache_root / "models--laion--larger_clap_general" / "snapshots" / "*" / "*.bin",
|
137 |
+
]:
|
|
|
138 |
for f in glob.glob(str(pat)):
|
139 |
try:
|
140 |
Path(f).unlink()
|
|
|
142 |
except Exception:
|
143 |
pass
|
144 |
|
145 |
+
# ---- Dependency guards (clear errors during boot) ---------------------------
|
146 |
try:
|
147 |
+
import audiotools # provided by PyPI package 'descript-audiotools'
|
148 |
except Exception as e:
|
149 |
raise RuntimeError(
|
150 |
+
"Missing module 'audiotools'. Install via PyPI package "
|
151 |
+
"'descript-audiotools' (add 'descript-audiotools>=0.7.2' to requirements.txt)."
|
|
|
152 |
) from e
|
153 |
|
154 |
try:
|
|
|
157 |
import easydict # noqa: F401
|
158 |
except Exception as e:
|
159 |
raise RuntimeError(
|
160 |
+
"Missing config deps. Add to requirements.txt: "
|
161 |
+
"'omegaconf>=2.3.0', 'pyyaml', 'easydict'."
|
162 |
) from e
|
163 |
|
164 |
+
# Import Tencent internals after guards
|
165 |
from hunyuanvideo_foley.utils.model_utils import load_model, denoise_process
|
166 |
from hunyuanvideo_foley.utils.feature_utils import feature_process
|
167 |
from hunyuanvideo_foley.utils.media_utils import merge_audio_video
|
|
|
196 |
|
197 |
if not os.path.exists(MODEL_PATH):
|
198 |
os.makedirs(MODEL_PATH, exist_ok=True)
|
|
|
199 |
if not os.path.exists(CONFIG_PATH):
|
200 |
return f"❌ Config file not found: {CONFIG_PATH}"
|
201 |
|
|
|
204 |
logger.info(f"MODEL_PATH: {MODEL_PATH}")
|
205 |
logger.info(f"CONFIG_PATH: {CONFIG_PATH}")
|
206 |
|
207 |
+
# Ensure CLAP uses safetensors; nuke any .bin first
|
208 |
+
ensure_clap_safetensors()
|
209 |
_purge_clap_pt_bins()
|
210 |
|
211 |
_model_dict, _cfg = load_model(MODEL_PATH, CONFIG_PATH, _device)
|
|
|
220 |
# ========= Preprocessing =========
|
221 |
def preprocess_video(in_path: str) -> Tuple[str, float]:
|
222 |
"""
|
223 |
+
- Trim to <= MAX_SECS
|
224 |
+
- Downscale to TARGET_H (keep AR), strip audio
|
225 |
+
- Return processed mp4 path and final duration
|
226 |
"""
|
227 |
dur = ffprobe_duration(in_path)
|
228 |
if dur == 0:
|
|
|
233 |
processed = temp_dir / "proc.mp4"
|
234 |
trim_args = ["-t", str(MAX_SECS)] if dur > MAX_SECS else []
|
235 |
|
236 |
+
# Normalize & remove audio
|
237 |
sh(" ".join([
|
238 |
"ffmpeg", "-y", "-i", f"\"{in_path}\"",
|
239 |
*trim_args,
|
|
|
243 |
f"\"{trimmed}\""
|
244 |
]))
|
245 |
|
246 |
+
# Downscale to TARGET_H; ensure mod2 width
|
247 |
vf = f"scale=-2:{TARGET_H}:flags=bicubic"
|
248 |
sh(" ".join([
|
249 |
"ffmpeg", "-y", "-i", f"\"{trimmed}\"",
|
|
|
260 |
return str(processed), final_dur
|
261 |
|
262 |
# ========= Inference (ZeroGPU) =========
|
263 |
+
@spaces.GPU(duration=ZEROGPU_DURATION)
|
264 |
@torch.inference_mode()
|
265 |
def run_model(video_path: str, prompt_text: str,
|
266 |
guidance_scale: float = 4.5,
|