Spaces:
Running on Zero
Running on Zero
File size: 5,880 Bytes
5189638 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | """Runpod Serverless worker: one whole Rickroll song per job.
Input (job["input"]):
lyrics str, required, up to 100,000 characters (any text; see README)
style str, optional; omitted = the default style prompt in backend/build_config.json,
"" = a genuinely empty style
seed int, optional, 0..4294967295; omitted = random
Output on success:
{"status": "completed", "audio": {"format": "wav", "url": ...} | {"format": "mp3", "base64": ...},
"duration_seconds", "seed", "notes", "sections", "sung_lyrics", "report"}
Output when the input cannot become a song (job still COMPLETED):
{"status": "rejected", "message": ...}
Any other failure raises, so Runpod marks the job FAILED.
While running, progress updates are {"completed", "total", "label", "notes"}.
"""
from __future__ import annotations
import base64
import logging
import os
import secrets
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import runpod # noqa: E402
import soundfile as sf # noqa: E402
from backend.build_pipeline import build_step, prepare_build_runtime, start_build # noqa: E402
from backend.build_plan import BuildPlanError, BuildUserError, load_build_config # noqa: E402
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
_LOG = logging.getLogger("rickroll.worker")
_MAX_LYRICS = 100_000
# The pinned HOT-Step engine is compiled for SM120a only (RTX 5090, RTX PRO Blackwell).
_COMPUTE_CAPABILITY = "12.0"
def _gpu_problem() -> str | None:
"""Explain why this machine cannot run the engine, or None when it can."""
try:
query = subprocess.run(["nvidia-smi", "--query-gpu=name,compute_cap,driver_version", "--format=csv,noheader"],
capture_output=True, text=True, timeout=30, check=True).stdout.strip()
except (OSError, subprocess.SubprocessError) as exc:
return f"No NVIDIA GPU is visible ({type(exc).__name__})."
name, capability, driver = (part.strip() for part in query.splitlines()[0].split(","))
_LOG.info("GPU: %s, compute capability %s, driver %s", name, capability, driver)
if capability != _COMPUTE_CAPABILITY:
return (f"{name} has compute capability {capability}; the engine is built for {_COMPUTE_CAPABILITY} only "
"(RTX 5090 or RTX PRO Blackwell). Restrict the endpoint to the ADA_32_PRO / BLACKWELL_32 / "
"BLACKWELL_96 pools.")
return None
_STARTUP_ERROR = _gpu_problem()
if _STARTUP_ERROR is None:
# Verify (and on first boot download) the engine, base models and adapter before taking jobs.
try:
prepare_build_runtime()
except Exception as exc: # reported on every job so it is visible in the endpoint's job history
_LOG.exception("Native runtime preparation failed")
_STARTUP_ERROR = f"Native runtime preparation failed: {exc}"
_DEFAULT_STYLE = load_build_config()["style_prompt"]
def _deliver(audio_path: Path, job_id: str) -> dict:
"""Upload the WAV when a bucket is configured; otherwise inline a 320 kbps MP3."""
if os.getenv("BUCKET_ENDPOINT_URL"):
from runpod.serverless.utils.rp_upload import upload_file_to_bucket
url = upload_file_to_bucket(file_name=f"{job_id}.wav", file_location=str(audio_path),
bucket_name=os.environ["BUCKET_NAME"],
prefix=os.getenv("BUCKET_PREFIX") or None)
return {"format": "wav", "url": url}
# Runpod caps a job result at 20 MB, so a 3-minute WAV cannot be returned inline.
mp3 = audio_path.with_suffix(".mp3")
data, rate = sf.read(str(audio_path), dtype="float32", always_2d=True)
sf.write(str(mp3), data, rate, format="MP3", subtype="MPEG_LAYER_III",
bitrate_mode="CONSTANT", compression_level=0.0)
return {"format": "mp3", "base64": base64.b64encode(mp3.read_bytes()).decode("ascii")}
def handler(job: dict) -> dict:
if _STARTUP_ERROR:
return {"error": _STARTUP_ERROR, "refresh_worker": True}
data = job.get("input") or {}
lyrics, style, seed = data.get("lyrics"), data.get("style", _DEFAULT_STYLE), data.get("seed")
if not isinstance(lyrics, str) or not lyrics.strip():
return {"status": "rejected", "message": "Add some words to turn into a song."}
if len(lyrics) > _MAX_LYRICS:
return {"status": "rejected", "message": f"Lyrics must be at most {_MAX_LYRICS:,} characters."}
if seed is None:
seed = secrets.randbelow(2**32)
try:
status = start_build(lyrics, style, seed)
notes = status["notes"]
def progress(completed: int, total: int, label: str) -> None:
runpod.serverless.progress_update(job, {"completed": completed, "total": total,
"label": label, "notes": notes})
while not status["done"]:
status = build_step(status["run_id"], progress)
except (BuildUserError, BuildPlanError) as exc:
return {"status": "rejected", "message": str(exc)}
result = status["result"]
audio_path = Path(result["audio"])
run_directory = Path(result["report"]).parent
try:
return {"status": "completed", "audio": _deliver(audio_path, job["id"]),
"duration_seconds": sf.info(str(audio_path)).duration, "seed": result["seed"],
"notes": result["notes"], "sections": result["sections"],
"sung_lyrics": result["sung_lyrics"], "report": result["report_data"]}
finally:
# Section takes and codec state are only needed while the song is built.
shutil.rmtree(run_directory, ignore_errors=True)
if __name__ == "__main__":
runpod.serverless.start({"handler": handler})
|