Spaces:
Running on Zero
Running on Zero
Fix: monkey-patch without staticmethod wrapper, spaces before torch, ssr_mode=False
Browse files
app.py
CHANGED
|
@@ -5,8 +5,8 @@ import time
|
|
| 5 |
import shutil
|
| 6 |
import tempfile
|
| 7 |
import threading
|
| 8 |
-
import torch
|
| 9 |
import spaces
|
|
|
|
| 10 |
import torchaudio
|
| 11 |
import gradio as gr
|
| 12 |
from fastapi.responses import JSONResponse
|
|
@@ -53,7 +53,6 @@ def _read_cgroup_file(path):
|
|
| 53 |
|
| 54 |
|
| 55 |
def _parse_cpu_count():
|
| 56 |
-
"""Read actual CPU allocation from cgroup limits."""
|
| 57 |
cpu_max = _read_cgroup_file("/sys/fs/cgroup/cpu.max")
|
| 58 |
if cpu_max:
|
| 59 |
parts = cpu_max.split()
|
|
@@ -64,7 +63,6 @@ def _parse_cpu_count():
|
|
| 64 |
return quota // period
|
| 65 |
except ValueError:
|
| 66 |
pass
|
| 67 |
-
|
| 68 |
quota = _read_cgroup_file("/sys/fs/cgroup/cpu/cpu.cfs_quota_us")
|
| 69 |
period = _read_cgroup_file("/sys/fs/cgroup/cpu/cpu.cfs_period_us")
|
| 70 |
if quota and period:
|
|
@@ -74,7 +72,6 @@ def _parse_cpu_count():
|
|
| 74 |
return q // p
|
| 75 |
except ValueError:
|
| 76 |
pass
|
| 77 |
-
|
| 78 |
cpuset = _read_cgroup_file("/sys/fs/cgroup/cpuset.cpus")
|
| 79 |
if cpuset:
|
| 80 |
count = 0
|
|
@@ -86,12 +83,10 @@ def _parse_cpu_count():
|
|
| 86 |
count += 1
|
| 87 |
if count > 0:
|
| 88 |
return count
|
| 89 |
-
|
| 90 |
return os.cpu_count()
|
| 91 |
|
| 92 |
|
| 93 |
def _parse_ram_bytes():
|
| 94 |
-
"""Read actual memory limit from cgroup limits."""
|
| 95 |
mem_max = _read_cgroup_file("/sys/fs/cgroup/memory.max")
|
| 96 |
if mem_max and mem_max != "max":
|
| 97 |
try:
|
|
@@ -100,7 +95,6 @@ def _parse_ram_bytes():
|
|
| 100 |
return val
|
| 101 |
except ValueError:
|
| 102 |
pass
|
| 103 |
-
|
| 104 |
mem_limit = _read_cgroup_file("/sys/fs/cgroup/memory/memory.limit_in_bytes")
|
| 105 |
if mem_limit:
|
| 106 |
try:
|
|
@@ -109,7 +103,6 @@ def _parse_ram_bytes():
|
|
| 109 |
return val
|
| 110 |
except ValueError:
|
| 111 |
pass
|
| 112 |
-
|
| 113 |
try:
|
| 114 |
with open("/proc/meminfo", "r", encoding="utf-8") as meminfo:
|
| 115 |
for line in meminfo:
|
|
@@ -177,11 +170,9 @@ def _get_runtime_specs():
|
|
| 177 |
storage = shutil.disk_usage(os.getcwd())
|
| 178 |
hardware = os.environ.get("SPACE_HARDWARE", "zero-a10g")
|
| 179 |
is_zerogpu = "zero" in hardware.lower()
|
| 180 |
-
|
| 181 |
allocated_cores = _parse_cpu_count()
|
| 182 |
allocated_ram = _parse_ram_bytes()
|
| 183 |
host_cores = os.cpu_count()
|
| 184 |
-
|
| 185 |
return {
|
| 186 |
"platform": platform.platform(),
|
| 187 |
"python_version": platform.python_version(),
|
|
@@ -201,7 +192,7 @@ def _get_runtime_specs():
|
|
| 201 |
|
| 202 |
|
| 203 |
# ---------------------------------------------------------------------------
|
| 204 |
-
# Web search (DuckDuckGo
|
| 205 |
# ---------------------------------------------------------------------------
|
| 206 |
|
| 207 |
try:
|
|
@@ -210,7 +201,6 @@ try:
|
|
| 210 |
def _search_web(query, backend="text", max_results=10, extract_top=0, region="wt-wt"):
|
| 211 |
extract_top = max(0, min(5, extract_top))
|
| 212 |
max_results = max(1, min(50, max_results))
|
| 213 |
-
|
| 214 |
with DDGS() as ddgs:
|
| 215 |
if backend == "news":
|
| 216 |
hits = list(ddgs.news(query, max_results=max_results, region=region))
|
|
@@ -226,7 +216,6 @@ try:
|
|
| 226 |
if r.get("image"):
|
| 227 |
entry["image"] = r["image"]
|
| 228 |
results.append(entry)
|
| 229 |
-
|
| 230 |
elif backend == "images":
|
| 231 |
hits = list(ddgs.images(query, max_results=max_results, region=region))
|
| 232 |
results = []
|
|
@@ -239,17 +228,9 @@ try:
|
|
| 239 |
"width": r.get("width"),
|
| 240 |
"height": r.get("height"),
|
| 241 |
})
|
| 242 |
-
|
| 243 |
-
else: # text
|
| 244 |
hits = list(ddgs.text(query, max_results=max_results, region=region))
|
| 245 |
-
results = []
|
| 246 |
-
for r in hits:
|
| 247 |
-
results.append({
|
| 248 |
-
"title": r.get("title", ""),
|
| 249 |
-
"url": r.get("href", ""),
|
| 250 |
-
"content": r.get("body", ""),
|
| 251 |
-
})
|
| 252 |
-
|
| 253 |
if extract_top > 0 and results and backend != "images":
|
| 254 |
urls_to_extract = [r["url"] for r in results[:extract_top] if r.get("url")]
|
| 255 |
with DDGS() as ddgs:
|
|
@@ -264,17 +245,10 @@ try:
|
|
| 264 |
break
|
| 265 |
except Exception as e:
|
| 266 |
_log(f"Warning: failed to extract {url}: {e}")
|
| 267 |
-
|
| 268 |
-
return {
|
| 269 |
-
"query": query,
|
| 270 |
-
"backend": backend,
|
| 271 |
-
"results": results,
|
| 272 |
-
"total_results": len(results),
|
| 273 |
-
}
|
| 274 |
|
| 275 |
except ImportError:
|
| 276 |
_log("Warning: duckduckgo_search not installed, search disabled")
|
| 277 |
-
|
| 278 |
def _search_web(query, backend="text", max_results=10, extract_top=0, region="wt-wt"):
|
| 279 |
raise RuntimeError("Search not available: duckduckgo_search not installed")
|
| 280 |
|
|
@@ -284,27 +258,9 @@ except ImportError:
|
|
| 284 |
# ---------------------------------------------------------------------------
|
| 285 |
|
| 286 |
_BENCHMARK_MODELS = [
|
| 287 |
-
{
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
"file": "gemma-4-E4B-it-Q4_K_M.gguf",
|
| 291 |
-
"size_gb": 2.5,
|
| 292 |
-
"prompt": "Explain recursion in programming in 3 sentences.",
|
| 293 |
-
},
|
| 294 |
-
{
|
| 295 |
-
"name": "Qwen3 8B",
|
| 296 |
-
"repo": "Qwen/Qwen3-8B-GGUF",
|
| 297 |
-
"file": "Qwen3-8B-Q4_K_M.gguf",
|
| 298 |
-
"size_gb": 5.0,
|
| 299 |
-
"prompt": "Explain recursion in programming in 3 sentences.",
|
| 300 |
-
},
|
| 301 |
-
{
|
| 302 |
-
"name": "Qwen3.8 27B",
|
| 303 |
-
"repo": "unsloth/Qwen3.8-27B-GGUF",
|
| 304 |
-
"file": "Qwen3.8-27B-Q4_0.gguf",
|
| 305 |
-
"size_gb": 16.0,
|
| 306 |
-
"prompt": "Explain recursion in programming in 3 sentences.",
|
| 307 |
-
},
|
| 308 |
]
|
| 309 |
_BENCHMARK_CACHE = os.path.join(tempfile.gettempdir(), "llm_benchmark")
|
| 310 |
_BENCHMARK_RESULTS = []
|
|
@@ -312,26 +268,20 @@ _LLAMA_CPP_BIN = None
|
|
| 312 |
|
| 313 |
|
| 314 |
def _ensure_llama_cpp():
|
| 315 |
-
"""Build or download llama.cpp binary if not cached."""
|
| 316 |
global _LLAMA_CPP_BIN
|
| 317 |
if _LLAMA_CPP_BIN and os.path.isfile(_LLAMA_CPP_BIN):
|
| 318 |
return _LLAMA_CPP_BIN
|
| 319 |
-
|
| 320 |
import subprocess
|
| 321 |
-
|
| 322 |
os.makedirs(_BENCHMARK_CACHE, exist_ok=True)
|
| 323 |
bin_dir = os.path.join(_BENCHMARK_CACHE, "llama_bin")
|
| 324 |
llama_cli = os.path.join(bin_dir, "llama-cli")
|
| 325 |
-
|
| 326 |
if os.path.isfile(llama_cli):
|
| 327 |
_LLAMA_CPP_BIN = llama_cli
|
| 328 |
return llama_cli
|
| 329 |
-
|
| 330 |
_log("Benchmark: cloning llama.cpp...")
|
| 331 |
src_dir = os.path.join(_BENCHMARK_CACHE, "llama_src")
|
| 332 |
if os.path.isdir(src_dir):
|
| 333 |
shutil.rmtree(src_dir, ignore_errors=True)
|
| 334 |
-
|
| 335 |
subprocess.check_call(
|
| 336 |
["git", "clone", "--depth=1", "https://github.com/ggml-org/llama.cpp.git", src_dir],
|
| 337 |
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
@@ -342,8 +292,7 @@ def _ensure_llama_cpp():
|
|
| 342 |
os.makedirs(build_dir, exist_ok=True)
|
| 343 |
os.makedirs(bin_dir, exist_ok=True)
|
| 344 |
subprocess.check_call(
|
| 345 |
-
["cmake", "-S", src_dir, "-B", build_dir,
|
| 346 |
-
"-DLLAMA_NATIVE=ON", "-DBUILD_SHARED_LIBS=OFF"],
|
| 347 |
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
| 348 |
)
|
| 349 |
subprocess.check_call(
|
|
@@ -358,124 +307,71 @@ def _ensure_llama_cpp():
|
|
| 358 |
_log(f"Benchmark: llama.cpp built at {llama_cli}")
|
| 359 |
else:
|
| 360 |
raise RuntimeError(f"llama-cli not found after build in {build_dir}")
|
| 361 |
-
|
| 362 |
_LLAMA_CPP_BIN = llama_cli
|
| 363 |
return llama_cli
|
| 364 |
|
| 365 |
|
| 366 |
def _run_benchmark(model_filter=None):
|
| 367 |
-
"""Run CPU benchmark on models using llama.cpp binary."""
|
| 368 |
global _BENCHMARK_RESULTS
|
| 369 |
if _BENCHMARK_RESULTS and not model_filter:
|
| 370 |
return _BENCHMARK_RESULTS
|
| 371 |
-
|
| 372 |
-
import subprocess
|
| 373 |
-
import re
|
| 374 |
from huggingface_hub import hf_hub_download
|
| 375 |
-
|
| 376 |
os.makedirs(_BENCHMARK_CACHE, exist_ok=True)
|
| 377 |
llama_cli = _ensure_llama_cpp()
|
| 378 |
n_threads = _parse_cpu_count() or 8
|
| 379 |
results = []
|
| 380 |
prompt = "Explain recursion in programming in 3 sentences."
|
| 381 |
-
|
| 382 |
models = _BENCHMARK_MODELS
|
| 383 |
if model_filter:
|
| 384 |
models = [m for m in _BENCHMARK_MODELS if m["name"] == model_filter]
|
| 385 |
if not models:
|
| 386 |
raise ValueError(f"Unknown model '{model_filter}'. Available: {[m['name'] for m in _BENCHMARK_MODELS]}")
|
| 387 |
-
|
| 388 |
for model_info in models:
|
| 389 |
result = {"name": model_info["name"], "status": "error"}
|
| 390 |
try:
|
| 391 |
_log(f"Benchmark: downloading {model_info['name']} (~{model_info['size_gb']} GB)...")
|
| 392 |
-
model_path = hf_hub_download(
|
| 393 |
-
repo_id=model_info["repo"],
|
| 394 |
-
filename=model_info["file"],
|
| 395 |
-
cache_dir=_BENCHMARK_CACHE,
|
| 396 |
-
)
|
| 397 |
-
|
| 398 |
_log(f"Benchmark: running {model_info['name']} with {n_threads} threads...")
|
| 399 |
env = os.environ.copy()
|
| 400 |
bin_dir = os.path.dirname(llama_cli)
|
| 401 |
env["LD_LIBRARY_PATH"] = bin_dir + ":" + env.get("LD_LIBRARY_PATH", "")
|
| 402 |
-
|
| 403 |
n_predict = 128 if model_info["size_gb"] <= 6 else 256
|
| 404 |
timeout_sec = 300 if model_info["size_gb"] <= 6 else 600
|
| 405 |
-
cmd = [
|
| 406 |
-
llama_cli,
|
| 407 |
-
"-m", model_path,
|
| 408 |
-
"-t", str(n_threads),
|
| 409 |
-
"-c", "2048",
|
| 410 |
-
"-n", str(n_predict),
|
| 411 |
-
"--temp", "0.7",
|
| 412 |
-
"--top-p", "0.9",
|
| 413 |
-
"-p", prompt,
|
| 414 |
-
"--no-display-prompt",
|
| 415 |
-
"--log-disable",
|
| 416 |
-
]
|
| 417 |
-
_log(f"Benchmark: model exists: {os.path.isfile(model_path)}, size: {os.path.getsize(model_path) if os.path.isfile(model_path) else 0}")
|
| 418 |
t0 = time.time()
|
| 419 |
try:
|
| 420 |
-
proc = subprocess.run(
|
| 421 |
-
cmd, capture_output=True, text=True, timeout=timeout_sec, env=env,
|
| 422 |
-
)
|
| 423 |
except subprocess.TimeoutExpired:
|
| 424 |
-
result["error"] = "Timeout
|
| 425 |
results.append(result)
|
| 426 |
continue
|
| 427 |
wall_time = time.time() - t0
|
| 428 |
output_text = proc.stdout.strip()
|
| 429 |
-
|
| 430 |
_log(f"Benchmark: {model_info['name']} exit code: {proc.returncode}")
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
prompt_tps = 0.0
|
| 434 |
-
gen_tps = 0.0
|
| 435 |
-
prompt_tok = 0
|
| 436 |
-
gen_tok = 0
|
| 437 |
for line in proc.stderr.splitlines():
|
| 438 |
tps_match = re.search(r"(\d+\.?\d*) tokens per second", line)
|
| 439 |
tok_match = re.search(r"/ (\d+) tokens", line)
|
| 440 |
-
if "prompt eval" in line.lower()
|
| 441 |
-
if tps_match:
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
if tps_match:
|
| 447 |
-
gen_tps = float(tps_match.group(1))
|
| 448 |
-
if tok_match:
|
| 449 |
-
gen_tok = int(tok_match.group(1))
|
| 450 |
-
|
| 451 |
if gen_tok == 0 and output_text:
|
| 452 |
gen_tok = len(output_text.split())
|
| 453 |
-
|
| 454 |
-
result.update({
|
| 455 |
-
"status": "success",
|
| 456 |
-
"total_time_sec": round(wall_time, 2),
|
| 457 |
-
"prompt_tokens": prompt_tok,
|
| 458 |
-
"completion_tokens": gen_tok,
|
| 459 |
-
"prompt_tokens_per_sec": round(prompt_tps, 1),
|
| 460 |
-
"generation_tokens_per_sec": round(gen_tps, 1),
|
| 461 |
-
"output": output_text[:500],
|
| 462 |
-
})
|
| 463 |
_log(f"Benchmark: {model_info['name']} -> {gen_tps:.1f} gen tok/s, {prompt_tps:.1f} prompt tok/s")
|
| 464 |
-
|
| 465 |
except Exception as e:
|
| 466 |
result["error"] = str(e)
|
| 467 |
_log(f"Benchmark ERROR: {model_info['name']}: {e}")
|
| 468 |
-
|
| 469 |
results.append(result)
|
| 470 |
-
|
| 471 |
-
# Free disk cache between models
|
| 472 |
import glob as _glob
|
| 473 |
for f in _glob.glob(os.path.join(_BENCHMARK_CACHE, "**", "*.gguf"), recursive=True):
|
| 474 |
-
try:
|
| 475 |
-
|
| 476 |
-
except Exception:
|
| 477 |
-
pass
|
| 478 |
-
|
| 479 |
if not model_filter:
|
| 480 |
_BENCHMARK_RESULTS = results
|
| 481 |
return results
|
|
@@ -498,21 +394,12 @@ def load_model(model_name):
|
|
| 498 |
|
| 499 |
|
| 500 |
def generate_audio(prompt, duration, steps, cfg_scale, seed, model_name):
|
| 501 |
-
_log(
|
| 502 |
-
f"Generating with {model_name}: prompt='{prompt}', "
|
| 503 |
-
f"duration={duration}s, steps={steps}, cfg={cfg_scale}, seed={seed}"
|
| 504 |
-
)
|
| 505 |
model = load_model(model_name)
|
| 506 |
-
audio = model.generate(
|
| 507 |
-
prompt=prompt, duration=duration, steps=steps,
|
| 508 |
-
cfg_scale=cfg_scale, seed=seed, batch_size=1,
|
| 509 |
-
)
|
| 510 |
audio = rearrange(audio, "b d n -> d (b n)")
|
| 511 |
audio = audio.to(torch.float32).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
|
| 512 |
-
output_path = os.path.join(
|
| 513 |
-
tempfile.gettempdir(),
|
| 514 |
-
f"stable_audio_{seed}_{hash(prompt) & 0xFFFFFFFF:08x}.wav",
|
| 515 |
-
)
|
| 516 |
torchaudio.save(output_path, audio, 44100)
|
| 517 |
_log("Generation complete!")
|
| 518 |
return output_path
|
|
@@ -524,49 +411,36 @@ def generate_audio(prompt, duration, steps, cfg_scale, seed, model_name):
|
|
| 524 |
|
| 525 |
with gr.Blocks(title="Respite API") as demo:
|
| 526 |
gr.Markdown("# Respite API - Music & SFX Generation")
|
| 527 |
-
gr.Markdown(
|
| 528 |
-
"Generate music and sound effects using "
|
| 529 |
-
"Stability AI's Stable Audio 3 Small models."
|
| 530 |
-
)
|
| 531 |
-
|
| 532 |
with gr.Row():
|
| 533 |
with gr.Column():
|
| 534 |
-
model_name = gr.Dropdown(
|
| 535 |
-
|
| 536 |
-
value="small-music", label="Model",
|
| 537 |
-
)
|
| 538 |
-
prompt = gr.Textbox(
|
| 539 |
-
label="Prompt",
|
| 540 |
-
placeholder="Describe the music or sound effect you want to generate...",
|
| 541 |
-
lines=2,
|
| 542 |
-
)
|
| 543 |
duration = gr.Slider(minimum=1, maximum=120, value=30, step=1, label="Duration (seconds)")
|
| 544 |
steps = gr.Slider(minimum=1, maximum=50, value=8, step=1, label="Steps")
|
| 545 |
cfg_scale = gr.Slider(minimum=0.0, maximum=10.0, value=1.0, step=0.1, label="CFG Scale")
|
| 546 |
seed = gr.Number(value=-1, label="Seed (-1 for random)")
|
| 547 |
btn = gr.Button("Generate", variant="primary")
|
| 548 |
-
|
| 549 |
with gr.Column():
|
| 550 |
audio_output = gr.Audio(label="Generated Audio", type="filepath")
|
| 551 |
-
|
| 552 |
-
btn.click(
|
| 553 |
-
fn=generate_audio,
|
| 554 |
-
inputs=[prompt, duration, steps, cfg_scale, seed, model_name],
|
| 555 |
-
outputs=audio_output,
|
| 556 |
-
)
|
| 557 |
|
| 558 |
|
| 559 |
# ---------------------------------------------------------------------------
|
| 560 |
-
#
|
| 561 |
#
|
| 562 |
-
#
|
| 563 |
-
#
|
| 564 |
-
#
|
| 565 |
-
# already on the same object.
|
| 566 |
# ---------------------------------------------------------------------------
|
| 567 |
|
| 568 |
-
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
|
| 571 |
@fa_app.get("/respite/resources")
|
| 572 |
def _resources():
|
|
@@ -599,11 +473,7 @@ def _add_routes(fa_app):
|
|
| 599 |
return JSONResponse({
|
| 600 |
"status": "complete",
|
| 601 |
"models": results,
|
| 602 |
-
"system": {
|
| 603 |
-
"cpu_cores": _parse_cpu_count(),
|
| 604 |
-
"ram_bytes": _parse_ram_bytes(),
|
| 605 |
-
"threads": _parse_cpu_count() or 8,
|
| 606 |
-
},
|
| 607 |
})
|
| 608 |
except Exception as e:
|
| 609 |
return JSONResponse({"error": str(e)}, status_code=500)
|
|
@@ -617,45 +487,18 @@ def _add_routes(fa_app):
|
|
| 617 |
binary_ok = r.returncode == 0
|
| 618 |
binary_info = r.stdout.strip()[:200] if binary_ok else r.stderr.strip()[:200]
|
| 619 |
from huggingface_hub import hf_hub_download
|
| 620 |
-
model_path = hf_hub_download(
|
| 621 |
-
repo_id="unsloth/gemma-4-E4B-it-GGUF",
|
| 622 |
-
filename="gemma-4-E4B-it-Q4_K_M.gguf",
|
| 623 |
-
cache_dir=_BENCHMARK_CACHE,
|
| 624 |
-
)
|
| 625 |
model_ok = os.path.isfile(model_path)
|
| 626 |
model_size = os.path.getsize(model_path) if model_ok else 0
|
| 627 |
-
return JSONResponse({
|
| 628 |
-
"binary_path": llama_cli,
|
| 629 |
-
"binary_exists": os.path.isfile(llama_cli),
|
| 630 |
-
"binary_ok": binary_ok,
|
| 631 |
-
"binary_info": binary_info,
|
| 632 |
-
"model_path": model_path,
|
| 633 |
-
"model_ok": model_ok,
|
| 634 |
-
"model_size_gb": round(model_size / 1024**3, 2),
|
| 635 |
-
})
|
| 636 |
except Exception as e:
|
| 637 |
return JSONResponse({"error": str(e)}, status_code=500)
|
| 638 |
|
| 639 |
-
_log("Respite API routes
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
# Try to add routes to demo.app (available after Blocks context exits)
|
| 643 |
-
if hasattr(demo, "app") and demo.app is not None:
|
| 644 |
-
_add_routes(demo.app)
|
| 645 |
-
_log("Routes added to demo.app directly")
|
| 646 |
-
else:
|
| 647 |
-
# demo.app might not exist yet. Use monkey-patch as fallback.
|
| 648 |
-
_log("demo.app not available, using monkey-patch fallback")
|
| 649 |
-
|
| 650 |
-
from gradio.routes import App as GradioApp
|
| 651 |
-
_orig_create_app = GradioApp.create_app
|
| 652 |
|
| 653 |
-
def _patched_create_app(blocks, **kwargs):
|
| 654 |
-
fa_app = _orig_create_app(blocks, **kwargs)
|
| 655 |
-
_add_routes(fa_app)
|
| 656 |
-
return fa_app
|
| 657 |
|
| 658 |
-
|
| 659 |
|
| 660 |
# Disable the Gradio Spaces file watcher thread which crashes because
|
| 661 |
# importing `spaces` in a new thread after CUDA init fails.
|
|
@@ -664,4 +507,4 @@ if hasattr(_gr_utils, "watchfn_spaces"):
|
|
| 664 |
_gr_utils.watchfn_spaces = lambda *a, **kw: None
|
| 665 |
|
| 666 |
demo.queue(max_size=4, default_concurrency_limit=1)
|
| 667 |
-
demo.launch()
|
|
|
|
| 5 |
import shutil
|
| 6 |
import tempfile
|
| 7 |
import threading
|
|
|
|
| 8 |
import spaces
|
| 9 |
+
import torch
|
| 10 |
import torchaudio
|
| 11 |
import gradio as gr
|
| 12 |
from fastapi.responses import JSONResponse
|
|
|
|
| 53 |
|
| 54 |
|
| 55 |
def _parse_cpu_count():
|
|
|
|
| 56 |
cpu_max = _read_cgroup_file("/sys/fs/cgroup/cpu.max")
|
| 57 |
if cpu_max:
|
| 58 |
parts = cpu_max.split()
|
|
|
|
| 63 |
return quota // period
|
| 64 |
except ValueError:
|
| 65 |
pass
|
|
|
|
| 66 |
quota = _read_cgroup_file("/sys/fs/cgroup/cpu/cpu.cfs_quota_us")
|
| 67 |
period = _read_cgroup_file("/sys/fs/cgroup/cpu/cpu.cfs_period_us")
|
| 68 |
if quota and period:
|
|
|
|
| 72 |
return q // p
|
| 73 |
except ValueError:
|
| 74 |
pass
|
|
|
|
| 75 |
cpuset = _read_cgroup_file("/sys/fs/cgroup/cpuset.cpus")
|
| 76 |
if cpuset:
|
| 77 |
count = 0
|
|
|
|
| 83 |
count += 1
|
| 84 |
if count > 0:
|
| 85 |
return count
|
|
|
|
| 86 |
return os.cpu_count()
|
| 87 |
|
| 88 |
|
| 89 |
def _parse_ram_bytes():
|
|
|
|
| 90 |
mem_max = _read_cgroup_file("/sys/fs/cgroup/memory.max")
|
| 91 |
if mem_max and mem_max != "max":
|
| 92 |
try:
|
|
|
|
| 95 |
return val
|
| 96 |
except ValueError:
|
| 97 |
pass
|
|
|
|
| 98 |
mem_limit = _read_cgroup_file("/sys/fs/cgroup/memory/memory.limit_in_bytes")
|
| 99 |
if mem_limit:
|
| 100 |
try:
|
|
|
|
| 103 |
return val
|
| 104 |
except ValueError:
|
| 105 |
pass
|
|
|
|
| 106 |
try:
|
| 107 |
with open("/proc/meminfo", "r", encoding="utf-8") as meminfo:
|
| 108 |
for line in meminfo:
|
|
|
|
| 170 |
storage = shutil.disk_usage(os.getcwd())
|
| 171 |
hardware = os.environ.get("SPACE_HARDWARE", "zero-a10g")
|
| 172 |
is_zerogpu = "zero" in hardware.lower()
|
|
|
|
| 173 |
allocated_cores = _parse_cpu_count()
|
| 174 |
allocated_ram = _parse_ram_bytes()
|
| 175 |
host_cores = os.cpu_count()
|
|
|
|
| 176 |
return {
|
| 177 |
"platform": platform.platform(),
|
| 178 |
"python_version": platform.python_version(),
|
|
|
|
| 192 |
|
| 193 |
|
| 194 |
# ---------------------------------------------------------------------------
|
| 195 |
+
# Web search (DuckDuckGo)
|
| 196 |
# ---------------------------------------------------------------------------
|
| 197 |
|
| 198 |
try:
|
|
|
|
| 201 |
def _search_web(query, backend="text", max_results=10, extract_top=0, region="wt-wt"):
|
| 202 |
extract_top = max(0, min(5, extract_top))
|
| 203 |
max_results = max(1, min(50, max_results))
|
|
|
|
| 204 |
with DDGS() as ddgs:
|
| 205 |
if backend == "news":
|
| 206 |
hits = list(ddgs.news(query, max_results=max_results, region=region))
|
|
|
|
| 216 |
if r.get("image"):
|
| 217 |
entry["image"] = r["image"]
|
| 218 |
results.append(entry)
|
|
|
|
| 219 |
elif backend == "images":
|
| 220 |
hits = list(ddgs.images(query, max_results=max_results, region=region))
|
| 221 |
results = []
|
|
|
|
| 228 |
"width": r.get("width"),
|
| 229 |
"height": r.get("height"),
|
| 230 |
})
|
| 231 |
+
else:
|
|
|
|
| 232 |
hits = list(ddgs.text(query, max_results=max_results, region=region))
|
| 233 |
+
results = [{"title": r.get("title", ""), "url": r.get("href", ""), "content": r.get("body", "")} for r in hits]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
if extract_top > 0 and results and backend != "images":
|
| 235 |
urls_to_extract = [r["url"] for r in results[:extract_top] if r.get("url")]
|
| 236 |
with DDGS() as ddgs:
|
|
|
|
| 245 |
break
|
| 246 |
except Exception as e:
|
| 247 |
_log(f"Warning: failed to extract {url}: {e}")
|
| 248 |
+
return {"query": query, "backend": backend, "results": results, "total_results": len(results)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
except ImportError:
|
| 251 |
_log("Warning: duckduckgo_search not installed, search disabled")
|
|
|
|
| 252 |
def _search_web(query, backend="text", max_results=10, extract_top=0, region="wt-wt"):
|
| 253 |
raise RuntimeError("Search not available: duckduckgo_search not installed")
|
| 254 |
|
|
|
|
| 258 |
# ---------------------------------------------------------------------------
|
| 259 |
|
| 260 |
_BENCHMARK_MODELS = [
|
| 261 |
+
{"name": "Gemma 4 E4B", "repo": "unsloth/gemma-4-E4B-it-GGUF", "file": "gemma-4-E4B-it-Q4_K_M.gguf", "size_gb": 2.5, "prompt": "Explain recursion in programming in 3 sentences."},
|
| 262 |
+
{"name": "Qwen3 8B", "repo": "Qwen/Qwen3-8B-GGUF", "file": "Qwen3-8B-Q4_K_M.gguf", "size_gb": 5.0, "prompt": "Explain recursion in programming in 3 sentences."},
|
| 263 |
+
{"name": "Qwen3.8 27B", "repo": "unsloth/Qwen3.8-27B-GGUF", "file": "Qwen3.8-27B-Q4_0.gguf", "size_gb": 16.0, "prompt": "Explain recursion in programming in 3 sentences."},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
]
|
| 265 |
_BENCHMARK_CACHE = os.path.join(tempfile.gettempdir(), "llm_benchmark")
|
| 266 |
_BENCHMARK_RESULTS = []
|
|
|
|
| 268 |
|
| 269 |
|
| 270 |
def _ensure_llama_cpp():
|
|
|
|
| 271 |
global _LLAMA_CPP_BIN
|
| 272 |
if _LLAMA_CPP_BIN and os.path.isfile(_LLAMA_CPP_BIN):
|
| 273 |
return _LLAMA_CPP_BIN
|
|
|
|
| 274 |
import subprocess
|
|
|
|
| 275 |
os.makedirs(_BENCHMARK_CACHE, exist_ok=True)
|
| 276 |
bin_dir = os.path.join(_BENCHMARK_CACHE, "llama_bin")
|
| 277 |
llama_cli = os.path.join(bin_dir, "llama-cli")
|
|
|
|
| 278 |
if os.path.isfile(llama_cli):
|
| 279 |
_LLAMA_CPP_BIN = llama_cli
|
| 280 |
return llama_cli
|
|
|
|
| 281 |
_log("Benchmark: cloning llama.cpp...")
|
| 282 |
src_dir = os.path.join(_BENCHMARK_CACHE, "llama_src")
|
| 283 |
if os.path.isdir(src_dir):
|
| 284 |
shutil.rmtree(src_dir, ignore_errors=True)
|
|
|
|
| 285 |
subprocess.check_call(
|
| 286 |
["git", "clone", "--depth=1", "https://github.com/ggml-org/llama.cpp.git", src_dir],
|
| 287 |
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
|
|
| 292 |
os.makedirs(build_dir, exist_ok=True)
|
| 293 |
os.makedirs(bin_dir, exist_ok=True)
|
| 294 |
subprocess.check_call(
|
| 295 |
+
["cmake", "-S", src_dir, "-B", build_dir, "-DLLAMA_NATIVE=ON", "-DBUILD_SHARED_LIBS=OFF"],
|
|
|
|
| 296 |
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
| 297 |
)
|
| 298 |
subprocess.check_call(
|
|
|
|
| 307 |
_log(f"Benchmark: llama.cpp built at {llama_cli}")
|
| 308 |
else:
|
| 309 |
raise RuntimeError(f"llama-cli not found after build in {build_dir}")
|
|
|
|
| 310 |
_LLAMA_CPP_BIN = llama_cli
|
| 311 |
return llama_cli
|
| 312 |
|
| 313 |
|
| 314 |
def _run_benchmark(model_filter=None):
|
|
|
|
| 315 |
global _BENCHMARK_RESULTS
|
| 316 |
if _BENCHMARK_RESULTS and not model_filter:
|
| 317 |
return _BENCHMARK_RESULTS
|
| 318 |
+
import subprocess, re
|
|
|
|
|
|
|
| 319 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 320 |
os.makedirs(_BENCHMARK_CACHE, exist_ok=True)
|
| 321 |
llama_cli = _ensure_llama_cpp()
|
| 322 |
n_threads = _parse_cpu_count() or 8
|
| 323 |
results = []
|
| 324 |
prompt = "Explain recursion in programming in 3 sentences."
|
|
|
|
| 325 |
models = _BENCHMARK_MODELS
|
| 326 |
if model_filter:
|
| 327 |
models = [m for m in _BENCHMARK_MODELS if m["name"] == model_filter]
|
| 328 |
if not models:
|
| 329 |
raise ValueError(f"Unknown model '{model_filter}'. Available: {[m['name'] for m in _BENCHMARK_MODELS]}")
|
|
|
|
| 330 |
for model_info in models:
|
| 331 |
result = {"name": model_info["name"], "status": "error"}
|
| 332 |
try:
|
| 333 |
_log(f"Benchmark: downloading {model_info['name']} (~{model_info['size_gb']} GB)...")
|
| 334 |
+
model_path = hf_hub_download(repo_id=model_info["repo"], filename=model_info["file"], cache_dir=_BENCHMARK_CACHE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
_log(f"Benchmark: running {model_info['name']} with {n_threads} threads...")
|
| 336 |
env = os.environ.copy()
|
| 337 |
bin_dir = os.path.dirname(llama_cli)
|
| 338 |
env["LD_LIBRARY_PATH"] = bin_dir + ":" + env.get("LD_LIBRARY_PATH", "")
|
|
|
|
| 339 |
n_predict = 128 if model_info["size_gb"] <= 6 else 256
|
| 340 |
timeout_sec = 300 if model_info["size_gb"] <= 6 else 600
|
| 341 |
+
cmd = [llama_cli, "-m", model_path, "-t", str(n_threads), "-c", "2048", "-n", str(n_predict), "--temp", "0.7", "--top-p", "0.9", "-p", prompt, "--no-display-prompt", "--log-disable"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
t0 = time.time()
|
| 343 |
try:
|
| 344 |
+
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_sec, env=env)
|
|
|
|
|
|
|
| 345 |
except subprocess.TimeoutExpired:
|
| 346 |
+
result["error"] = "Timeout"
|
| 347 |
results.append(result)
|
| 348 |
continue
|
| 349 |
wall_time = time.time() - t0
|
| 350 |
output_text = proc.stdout.strip()
|
|
|
|
| 351 |
_log(f"Benchmark: {model_info['name']} exit code: {proc.returncode}")
|
| 352 |
+
prompt_tps = gen_tps = 0.0
|
| 353 |
+
prompt_tok = gen_tok = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
for line in proc.stderr.splitlines():
|
| 355 |
tps_match = re.search(r"(\d+\.?\d*) tokens per second", line)
|
| 356 |
tok_match = re.search(r"/ (\d+) tokens", line)
|
| 357 |
+
if "prompt eval" in line.lower():
|
| 358 |
+
if tps_match: prompt_tps = float(tps_match.group(1))
|
| 359 |
+
if tok_match: prompt_tok = int(tok_match.group(1))
|
| 360 |
+
elif "eval time" in line.lower() and "prompt" not in line.lower():
|
| 361 |
+
if tps_match: gen_tps = float(tps_match.group(1))
|
| 362 |
+
if tok_match: gen_tok = int(tok_match.group(1))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
if gen_tok == 0 and output_text:
|
| 364 |
gen_tok = len(output_text.split())
|
| 365 |
+
result.update({"status": "success", "total_time_sec": round(wall_time, 2), "prompt_tokens": prompt_tok, "completion_tokens": gen_tok, "prompt_tokens_per_sec": round(prompt_tps, 1), "generation_tokens_per_sec": round(gen_tps, 1), "output": output_text[:500]})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
_log(f"Benchmark: {model_info['name']} -> {gen_tps:.1f} gen tok/s, {prompt_tps:.1f} prompt tok/s")
|
|
|
|
| 367 |
except Exception as e:
|
| 368 |
result["error"] = str(e)
|
| 369 |
_log(f"Benchmark ERROR: {model_info['name']}: {e}")
|
|
|
|
| 370 |
results.append(result)
|
|
|
|
|
|
|
| 371 |
import glob as _glob
|
| 372 |
for f in _glob.glob(os.path.join(_BENCHMARK_CACHE, "**", "*.gguf"), recursive=True):
|
| 373 |
+
try: os.unlink(f)
|
| 374 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
| 375 |
if not model_filter:
|
| 376 |
_BENCHMARK_RESULTS = results
|
| 377 |
return results
|
|
|
|
| 394 |
|
| 395 |
|
| 396 |
def generate_audio(prompt, duration, steps, cfg_scale, seed, model_name):
|
| 397 |
+
_log(f"Generating with {model_name}: prompt='{prompt}', duration={duration}s, steps={steps}, cfg={cfg_scale}, seed={seed}")
|
|
|
|
|
|
|
|
|
|
| 398 |
model = load_model(model_name)
|
| 399 |
+
audio = model.generate(prompt=prompt, duration=duration, steps=steps, cfg_scale=cfg_scale, seed=seed, batch_size=1)
|
|
|
|
|
|
|
|
|
|
| 400 |
audio = rearrange(audio, "b d n -> d (b n)")
|
| 401 |
audio = audio.to(torch.float32).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
|
| 402 |
+
output_path = os.path.join(tempfile.gettempdir(), f"stable_audio_{seed}_{hash(prompt) & 0xFFFFFFFF:08x}.wav")
|
|
|
|
|
|
|
|
|
|
| 403 |
torchaudio.save(output_path, audio, 44100)
|
| 404 |
_log("Generation complete!")
|
| 405 |
return output_path
|
|
|
|
| 411 |
|
| 412 |
with gr.Blocks(title="Respite API") as demo:
|
| 413 |
gr.Markdown("# Respite API - Music & SFX Generation")
|
| 414 |
+
gr.Markdown("Generate music and sound effects using Stability AI's Stable Audio 3 Small models.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
with gr.Row():
|
| 416 |
with gr.Column():
|
| 417 |
+
model_name = gr.Dropdown(choices=["small-music", "small-sfx"], value="small-music", label="Model")
|
| 418 |
+
prompt = gr.Textbox(label="Prompt", placeholder="Describe the music or sound effect you want to generate...", lines=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
duration = gr.Slider(minimum=1, maximum=120, value=30, step=1, label="Duration (seconds)")
|
| 420 |
steps = gr.Slider(minimum=1, maximum=50, value=8, step=1, label="Steps")
|
| 421 |
cfg_scale = gr.Slider(minimum=0.0, maximum=10.0, value=1.0, step=0.1, label="CFG Scale")
|
| 422 |
seed = gr.Number(value=-1, label="Seed (-1 for random)")
|
| 423 |
btn = gr.Button("Generate", variant="primary")
|
|
|
|
| 424 |
with gr.Column():
|
| 425 |
audio_output = gr.Audio(label="Generated Audio", type="filepath")
|
| 426 |
+
btn.click(fn=generate_audio, inputs=[prompt, duration, steps, cfg_scale, seed, model_name], outputs=audio_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
|
| 429 |
# ---------------------------------------------------------------------------
|
| 430 |
+
# Inject routes via monkey-patch on Gradio's App.create_app.
|
| 431 |
#
|
| 432 |
+
# Gradio's Blocks.launch() calls App.create_app() to build a NEW FastAPI app,
|
| 433 |
+
# discarding any routes added to demo.app earlier. We wrap that method so our
|
| 434 |
+
# routes get added to the app that is actually served.
|
|
|
|
| 435 |
# ---------------------------------------------------------------------------
|
| 436 |
|
| 437 |
+
from gradio.routes import App as GradioApp
|
| 438 |
+
|
| 439 |
+
_orig_create_app = GradioApp.create_app
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _patched_create_app(blocks, **kwargs):
|
| 443 |
+
fa_app = _orig_create_app(blocks, **kwargs)
|
| 444 |
|
| 445 |
@fa_app.get("/respite/resources")
|
| 446 |
def _resources():
|
|
|
|
| 473 |
return JSONResponse({
|
| 474 |
"status": "complete",
|
| 475 |
"models": results,
|
| 476 |
+
"system": {"cpu_cores": _parse_cpu_count(), "ram_bytes": _parse_ram_bytes(), "threads": _parse_cpu_count() or 8},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 477 |
})
|
| 478 |
except Exception as e:
|
| 479 |
return JSONResponse({"error": str(e)}, status_code=500)
|
|
|
|
| 487 |
binary_ok = r.returncode == 0
|
| 488 |
binary_info = r.stdout.strip()[:200] if binary_ok else r.stderr.strip()[:200]
|
| 489 |
from huggingface_hub import hf_hub_download
|
| 490 |
+
model_path = hf_hub_download(repo_id="unsloth/gemma-4-E4B-it-GGUF", filename="gemma-4-E4B-it-Q4_K_M.gguf", cache_dir=_BENCHMARK_CACHE)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
model_ok = os.path.isfile(model_path)
|
| 492 |
model_size = os.path.getsize(model_path) if model_ok else 0
|
| 493 |
+
return JSONResponse({"binary_path": llama_cli, "binary_exists": os.path.isfile(llama_cli), "binary_ok": binary_ok, "binary_info": binary_info, "model_path": model_path, "model_ok": model_ok, "model_size_gb": round(model_size / 1024**3, 2)})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
except Exception as e:
|
| 495 |
return JSONResponse({"error": str(e)}, status_code=500)
|
| 496 |
|
| 497 |
+
_log("Respite API routes injected into Gradio app")
|
| 498 |
+
return fa_app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
|
| 501 |
+
GradioApp.create_app = _patched_create_app
|
| 502 |
|
| 503 |
# Disable the Gradio Spaces file watcher thread which crashes because
|
| 504 |
# importing `spaces` in a new thread after CUDA init fails.
|
|
|
|
| 507 |
_gr_utils.watchfn_spaces = lambda *a, **kw: None
|
| 508 |
|
| 509 |
demo.queue(max_size=4, default_concurrency_limit=1)
|
| 510 |
+
demo.launch(ssr_mode=False)
|