Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-735]): add local AudioLDM2 long-form music backend behind generator-agnostic selector

[._.]/ Adam Eivyfdc836d4f82d
diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsx
index 858bf3bbe8..52d41a4b8d 100644
--- a/client/src/components/pipeline/stages/AudioStage.jsx
+++ b/client/src/components/pipeline/stages/AudioStage.jsx
@@ -83,6 +83,24 @@ export default function AudioStage({ issue, onStageUpdate }) {
const [genPrompt, setGenPrompt] = useState('');
const [genDuration, setGenDuration] = useState(12);
const [genModelId, setGenModelId] = useState('');
+ const [genEngineId, setGenEngineId] = useState('');
+
+ // The selected backend's descriptor (models + duration window + readiness).
+ // Falls back to the legacy single-engine shape when the server predates the
+ // `engines` array, so an older API still drives the picker.
+ const genEngines = generators?.engines ?? (generators
+ ? [{
+ id: generators.defaultEngine || 'musicgen',
+ name: 'MusicGen',
+ models: generators.models || [],
+ defaultModelId: generators.defaultModelId,
+ defaultDurationSec: generators.defaultDurationSec,
+ minDurationSec: generators.minDurationSec,
+ maxDurationSec: generators.maxDurationSec,
+ ready: generators.ready,
+ }]
+ : []);
+ const activeEngine = genEngines.find((e) => e.id === genEngineId) || genEngines[0] || null;
// Per-line VO start-offset drafts (seconds into the stitched episode). Kept
// separate from text drafts; committed on blur via the same patch queue.
@@ -98,12 +116,29 @@ export default function AudioStage({ issue, onStageUpdate }) {
});
if (result) {
setGenerators(result);
- setGenModelId((prev) => prev || result.defaultModelId || result.models?.[0]?.id || '');
- if (Number.isFinite(result.defaultDurationSec)) setGenDuration(result.defaultDurationSec);
+ // Default to the server's default engine, then that engine's default
+ // model + duration. Falls back to the flattened legacy fields.
+ const engines = result.engines ?? [];
+ const defEngine = engines.find((e) => e.id === result.defaultEngine) || engines[0] || null;
+ setGenEngineId((prev) => prev || defEngine?.id || result.defaultEngine || 'musicgen');
+ setGenModelId((prev) => prev || defEngine?.defaultModelId || result.defaultModelId || result.models?.[0]?.id || '');
+ const defDuration = defEngine?.defaultDurationSec ?? result.defaultDurationSec;
+ if (Number.isFinite(defDuration)) setGenDuration(defDuration);
}
}
};
+ // Switching engine re-anchors the model + duration to the new backend's
+ // defaults so a stale model id (valid only on the prior engine) can't be sent.
+ const handleEngineChange = (engineId) => {
+ setGenEngineId(engineId);
+ const engine = genEngines.find((e) => e.id === engineId);
+ if (engine) {
+ setGenModelId(engine.defaultModelId || engine.models?.[0]?.id || '');
+ if (Number.isFinite(engine.defaultDurationSec)) setGenDuration(engine.defaultDurationSec);
+ }
+ };
+
const handleGenerateMusic = async () => {
const prompt = genPrompt.trim();
if (!prompt) { toast.error('Describe the music you want first'); return; }
@@ -111,7 +146,7 @@ export default function AudioStage({ issue, onStageUpdate }) {
// Owns its own error toast → silent so the helper doesn't double-toast.
const result = await generatePipelineMusic(
issue.id,
- { prompt, durationSec: genDuration, modelId: genModelId || undefined },
+ { prompt, engine: genEngineId || undefined, durationSec: genDuration, modelId: genModelId || undefined },
{ silent: true },
).catch((err) => {
toast.error(err.message || 'Music generation failed');
@@ -499,7 +534,7 @@ export default function AudioStage({ issue, onStageUpdate }) {
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"
>
<Wand2 size={14} />
- {genPanelOpen ? 'Close generator' : 'Generate (MusicGen)'}
+ {genPanelOpen ? 'Close generator' : 'Generate music'}
</button>
</div>
</div>
@@ -508,75 +543,97 @@ export default function AudioStage({ issue, onStageUpdate }) {
<div className="mb-3 p-3 bg-port-bg border border-port-border rounded-lg">
{generators === null ? (
<p className="text-xs text-gray-500">Loading generators…</p>
- ) : !generators.ready ? (
- <p className="text-xs text-gray-400">
- Local music generation isn't installed yet. Run{' '}
- <code className="text-gray-300">INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh</code>{' '}
- to bootstrap the MusicGen (MLX) runtime, then reopen this panel.
- </p>
) : (
<div className="space-y-3">
- <div>
- <label htmlFor="musicgen-prompt" className="block text-xs text-gray-400 mb-1">Describe the music</label>
- <textarea
- id="musicgen-prompt"
- value={genPrompt}
- onChange={(e) => setGenPrompt(e.target.value)}
- rows={2}
- maxLength={800}
- placeholder="e.g. tense cinematic synth pad, slow build, minor key"
- className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
- />
- </div>
- <div className="flex items-end gap-3 flex-wrap">
+ {genEngines.length > 1 ? (
<div>
- <label htmlFor="musicgen-model" className="block text-xs text-gray-400 mb-1">Model</label>
+ <label htmlFor="music-engine" className="block text-xs text-gray-400 mb-1">Engine</label>
<select
- id="musicgen-model"
- value={genModelId}
- onChange={(e) => setGenModelId(e.target.value)}
+ id="music-engine"
+ value={activeEngine?.id || ''}
+ onChange={(e) => handleEngineChange(e.target.value)}
className="px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
>
- {(generators.models || []).map((m) => (
- <option key={m.id} value={m.id}>{m.name}</option>
+ {genEngines.map((eng) => (
+ <option key={eng.id} value={eng.id}>
+ {eng.name}{eng.ready ? '' : ' (not installed)'}
+ </option>
))}
</select>
</div>
- <div>
- <label htmlFor="musicgen-duration" className="block text-xs text-gray-400 mb-1">
- Length (s)
- </label>
- <input
- id="musicgen-duration"
- type="number"
- min={generators.minDurationSec ?? 1}
- max={generators.maxDurationSec ?? 30}
- step="1"
- value={genDuration}
- onChange={(e) => {
- // Clamp to the server's accepted range so a blank/typed
- // out-of-range value can't 400 on Generate. NaN → default.
- const min = generators.minDurationSec ?? 1;
- const max = generators.maxDurationSec ?? 30;
- const n = Number(e.target.value);
- setGenDuration(Number.isFinite(n) ? Math.max(min, Math.min(max, n)) : (generators.defaultDurationSec ?? 12));
- }}
- className="w-24 px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
- />
- </div>
- <button
- type="button"
- onClick={handleGenerateMusic}
- disabled={generating || !genPrompt.trim()}
- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm disabled:opacity-50"
- >
- {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
- {generating ? 'Generating…' : 'Generate'}
- </button>
- </div>
- <p className="text-[11px] text-gray-600">
- Runs on-device via MLX — a {generators.maxDurationSec ?? 30}s clip takes ~tens of seconds. The track lands in your music library and is attached to this issue.
- </p>
+ ) : null}
+
+ {!activeEngine?.ready ? (
+ <p className="text-xs text-gray-400">
+ {activeEngine?.name || 'This engine'} isn't installed yet. Run{' '}
+ <code className="text-gray-300">INSTALL_{(activeEngine?.id || 'musicgen').toUpperCase()}=1 bash scripts/setup-image-video.sh</code>{' '}
+ to bootstrap its runtime, then reopen this panel.
+ </p>
+ ) : (
+ <>
+ <div>
+ <label htmlFor="musicgen-prompt" className="block text-xs text-gray-400 mb-1">Describe the music</label>
+ <textarea
+ id="musicgen-prompt"
+ value={genPrompt}
+ onChange={(e) => setGenPrompt(e.target.value)}
+ rows={2}
+ maxLength={800}
+ placeholder="e.g. tense cinematic synth pad, slow build, minor key"
+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
+ />
+ </div>
+ <div className="flex items-end gap-3 flex-wrap">
+ <div>
+ <label htmlFor="musicgen-model" className="block text-xs text-gray-400 mb-1">Model</label>
+ <select
+ id="musicgen-model"
+ value={genModelId}
+ onChange={(e) => setGenModelId(e.target.value)}
+ className="px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
+ >
+ {(activeEngine.models || []).map((m) => (
+ <option key={m.id} value={m.id}>{m.name}</option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="musicgen-duration" className="block text-xs text-gray-400 mb-1">
+ Length (s)
+ </label>
+ <input
+ id="musicgen-duration"
+ type="number"
+ min={activeEngine.minDurationSec ?? 1}
+ max={activeEngine.maxDurationSec ?? 30}
+ step="1"
+ value={genDuration}
+ onChange={(e) => {
+ // Clamp to the engine's accepted range so a blank/typed
+ // out-of-range value can't 400 on Generate. NaN → default.
+ const min = activeEngine.minDurationSec ?? 1;
+ const max = activeEngine.maxDurationSec ?? 30;
+ const n = Number(e.target.value);
+ setGenDuration(Number.isFinite(n) ? Math.max(min, Math.min(max, n)) : (activeEngine.defaultDurationSec ?? 12));
+ }}
+ className="w-24 px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"
+ />
+ </div>
+ <button
+ type="button"
+ onClick={handleGenerateMusic}
+ disabled={generating || !genPrompt.trim()}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm disabled:opacity-50"
+ >
+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {generating ? 'Generating…' : 'Generate'}
+ </button>
+ </div>
+ <p className="text-[11px] text-gray-600">
+ Runs on-device — up to {activeEngine.maxDurationSec ?? 30}s. The track lands in your music library and is attached to this issue.
+ </p>
+ </>
+ )}
</div>
)}
</div>
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index de38997a56..278cd36406 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -616,19 +616,21 @@ export const deletePipelineMusicTrack = (filename) =>
// ---- Local-OSS music generation (Phase 4c.2) ----
-// Available MusicGen generators + whether the opt-in MLX runtime is installed.
-// Returns { models, defaultModelId, defaultDurationSec, minDurationSec,
-// maxDurationSec, ready }. `ready=false` → show the install hint instead of
-// the prompt box.
+// Available local music backends + whether each opt-in runtime is installed.
+// Returns { engines: [{ id, name, models, defaultModelId, defaultDurationSec,
+// minDurationSec, maxDurationSec, ready }], defaultEngine, ... } — the default
+// engine's fields are also flattened to the top level for back-compat. A
+// per-engine `ready=false` → show that engine's install hint, not the prompt.
export const listPipelineMusicGenerators = (options = {}) =>
request('/pipeline/audio/music/generators', options);
-// Generate a background-music track with MusicGen (MLX) and attach it to the
-// issue (source: 'gen'). Long-running (~tens of seconds); callers own a busy
-// state. Returns { issue, stage, music, durationSec, modelId }.
-export const generatePipelineMusic = (issueId, { prompt, durationSec, modelId } = {}, options = {}) =>
+// Generate a background-music track with a local backend (`engine`: 'musicgen'
+// | 'audioldm2') and attach it to the issue (source: 'gen'). Long-running
+// (~tens of seconds); callers own a busy state. Returns
+// { issue, stage, music, durationSec, modelId, engine }.
+export const generatePipelineMusic = (issueId, { prompt, engine, durationSec, modelId } = {}, options = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music/generate`, {
method: 'POST',
- body: JSON.stringify({ prompt, durationSec, modelId }),
+ body: JSON.stringify({ prompt, engine, durationSec, modelId }),
...options,
});
diff --git a/scripts/generate_audioldm2.py b/scripts/generate_audioldm2.py
new file mode 100644
index 0000000000..22d824d29c
--- /dev/null
+++ b/scripts/generate_audioldm2.py
@@ -0,0 +1,189 @@
+#!/usr/bin/env python3
+"""
+PortOS AudioLDM2 runner — local OSS long-form background-music generation.
+Spawned by `server/services/pipeline/musicGen.js` as a sibling backend to
+`scripts/generate_musicgen.py`.
+
+Pipeline Audio Phase 4c.2 shipped local MusicGen (MLX) as the first generator
+behind the audio stage's `source: 'gen'` library entry. AudioLDM2 is the second
+backend: a latent-diffusion text-to-audio model (CVSSP/audioldm2) that runs via
+HuggingFace `diffusers`. Its draw over MusicGen is *long-form* output — MusicGen
+degrades past ~30s (trained on 30s windows), whereas AudioLDM2 takes an explicit
+`audio_length_in_s` and renders coherent clips well past that, with no API key
+and no network at inference time (after the one-time weight download).
+
+This script deliberately MIRRORS generate_musicgen.py's CLI/contract so the JS
+side can spawn either behind the same `generateMusic` path:
+ --model <hf-repo> --text <prompt> --output <wav> --duration <seconds>
+ [--runtime-dir <dir>] [--seed <int>] [--steps <int>] [--guidance <float>]
+
+Progress protocol (mirrors the image/video/musicgen sidecars): STAGE:<name>
+[:detail] lines on stderr drive the JS-side phase tracker; a final
+`RESULT:<json>` line on stdout reports the saved path + actual duration.
+
+Output: a 16 kHz mono 16-bit PCM WAV at --output. AudioLDM2 generates at 16 kHz;
+we write the WAV with the stdlib `wave` module (+ numpy for the float→int16
+conversion) rather than depending on scipy/soundfile, matching the musicgen
+sidecar so the runtime's dependency surface stays small.
+"""
+
+import argparse
+import json
+import os
+import sys
+import wave
+
+
+# AudioLDM2 decodes audio at 16 kHz (fixed by the model's VAE / vocoder).
+SAMPLE_RATE = 16000
+
+
+def log_stage(name, detail=""):
+ """Emit a STAGE: line the JS sidecar tails for phase/progress display."""
+ line = f"STAGE:{name}" + (f":{detail}" if detail else "")
+ print(line, file=sys.stderr, flush=True)
+
+
+def _import_pipeline(runtime_dir):
+ """Resolve the diffusers AudioLDM2Pipeline class.
+
+ AudioLDM2 ships in HuggingFace `diffusers` (a pip package), so unlike the
+ MLX MusicGen example we normally just import it. `runtime_dir` is honored
+ for parity with the musicgen sidecar — if a caller vendored a diffusers
+ build into a clone dir, prepend it to sys.path first. Raising a clear
+ ImportError lets the JS side surface "run the installer" rather than a bare
+ traceback.
+ """
+ if runtime_dir and os.path.isdir(runtime_dir) and runtime_dir not in sys.path:
+ sys.path.insert(0, runtime_dir)
+ try:
+ from diffusers import AudioLDM2Pipeline # type: ignore
+ return AudioLDM2Pipeline
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import AudioLDM2Pipeline from diffusers. Run "
+ "`INSTALL_AUDIOLDM2=1 bash scripts/setup-image-video.sh` to build "
+ f"the venv (torch + diffusers + transformers; looked in: {runtime_dir})."
+ ) from exc
+
+
+def _pick_device():
+ """Prefer Apple-Silicon MPS, then CUDA, else CPU.
+
+ Returns the torch device string. AudioLDM2 runs on all three; MPS is the
+ common case on PortOS's target hardware (Apple Silicon), CUDA covers Linux
+ GPU boxes, CPU is the slow fallback so generation still completes.
+ """
+ import torch
+
+ if torch.backends.mps.is_available():
+ return "mps"
+ if torch.cuda.is_available():
+ return "cuda"
+ return "cpu"
+
+
+def _to_int16_pcm(audio):
+ """Flatten a numpy audio array to a 1-D int16 numpy buffer.
+
+ AudioLDM2 returns a float array (shape [batch, samples]); we take the first
+ waveform, flatten to mono, clip to [-1, 1] so a hot sample can't wrap on the
+ int16 cast, and scale to full-scale PCM. Mirrors the musicgen sidecar's
+ conversion so both backends emit byte-identical WAV framing.
+ """
+ import numpy as np
+
+ arr = np.array(audio, dtype=np.float32)
+ if arr.ndim > 1:
+ arr = arr[0]
+ arr = arr.reshape(-1)
+ np.clip(arr, -1.0, 1.0, out=arr)
+ return (arr * 32767.0).astype(np.int16)
+
+
+def _write_wav(path, pcm_int16):
+ with wave.open(path, "wb") as wav:
+ wav.setnchannels(1)
+ wav.setsampwidth(2) # 16-bit
+ wav.setframerate(SAMPLE_RATE)
+ wav.writeframes(pcm_int16.tobytes())
+
+
+def main():
+ parser = argparse.ArgumentParser(description="PortOS AudioLDM2 runner (diffusers)")
+ parser.add_argument("--model", default="cvssp/audioldm2",
+ help="HF repo id of the AudioLDM2 weights")
+ parser.add_argument("--text", required=True, help="Text prompt")
+ parser.add_argument("--output", required=True, help="Output WAV path")
+ parser.add_argument("--duration", type=float, default=20.0,
+ help="Target clip length in seconds (long-form supported)")
+ parser.add_argument("--runtime-dir", default=os.environ.get("PORTOS_AUDIOLDM2_RUNTIME_DIR", ""),
+ help="Optional dir prepended to sys.path before importing diffusers")
+ parser.add_argument("--seed", type=int, default=0,
+ help="RNG seed for reproducible generation")
+ parser.add_argument("--steps", type=int, default=200,
+ help="Number of diffusion inference steps")
+ parser.add_argument("--guidance", type=float, default=3.5,
+ help="Classifier-free guidance scale")
+ args = parser.parse_args()
+
+ text = (args.text or "").strip()
+ if not text:
+ print("ERROR: --text is required", file=sys.stderr, flush=True)
+ return 2
+
+ # AudioLDM2 supports long-form, but a hard floor keeps the VAE from
+ # producing a zero-length latent; the ceiling is a sanity guard, not a model
+ # limit (the JS side clamps to MAX_DURATION_SEC for its engine before here).
+ duration = max(1.0, min(float(args.duration or 20.0), 300.0))
+ steps = max(1, int(args.steps or 200))
+
+ log_stage("import-runtime")
+ AudioLDM2Pipeline = _import_pipeline(args.runtime_dir)
+
+ import torch
+
+ device = _pick_device()
+ # float16 on accelerators halves memory + speeds inference; CPU stays float32
+ # because half-precision matmul is unsupported / slow there.
+ dtype = torch.float32 if device == "cpu" else torch.float16
+
+ log_stage("load-model", args.model)
+ pipe = AudioLDM2Pipeline.from_pretrained(args.model, torch_dtype=dtype)
+ pipe = pipe.to(device)
+
+ generator = torch.Generator(device=device).manual_seed(int(args.seed or 0))
+
+ log_stage("generate", f"{duration:.1f}s/{steps}steps")
+ out = pipe(
+ text,
+ num_inference_steps=steps,
+ audio_length_in_s=duration,
+ guidance_scale=float(args.guidance or 3.5),
+ generator=generator,
+ )
+
+ log_stage("encode-wav")
+ pcm = _to_int16_pcm(out.audios)
+ out_dir = os.path.dirname(os.path.abspath(args.output))
+ if out_dir:
+ os.makedirs(out_dir, exist_ok=True)
+ _write_wav(args.output, pcm)
+
+ # The rendered length can differ slightly from the request (the model
+ # quantizes to its latent frame rate). Report what we actually wrote so the
+ # JS side persists truth — identical contract to the musicgen sidecar.
+ actual_seconds = len(pcm) / float(SAMPLE_RATE)
+ result = {
+ "output": args.output,
+ "model": args.model,
+ "durationSec": round(actual_seconds, 3),
+ "sampleRate": SAMPLE_RATE,
+ }
+ print("RESULT:" + json.dumps(result), flush=True)
+ log_stage("done")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index 6e7ded7a5c..4747e00523 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -13,6 +13,7 @@
# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)
# INSTALL_MUSICGEN '1' to bootstrap a venv at ~/.portos/venv-musicgen + clone ml-explore/mlx-examples to ~/.portos/mlx-examples for local MusicGen (MLX) background-music generation (pipeline audio stage). Default: 0; opt in with INSTALL_MUSICGEN=1 (macOS / Apple Silicon only).
# MLX_EXAMPLES_PIN commit SHA of ml-explore/mlx-examples to check out for MusicGen (default: main).
+# INSTALL_AUDIOLDM2 '1' to bootstrap a venv at ~/.portos/venv-audioldm2 (torch + diffusers) for local AudioLDM2 long-form background-music generation (pipeline audio stage, second backend alongside MusicGen). Default: 0; opt in with INSTALL_AUDIOLDM2=1 (runs on MPS / CUDA / CPU).
set -euo pipefail
@@ -366,6 +367,51 @@ if [[ "$INSTALL_MUSICGEN" == "1" ]]; then
fi
fi
+INSTALL_AUDIOLDM2="${INSTALL_AUDIOLDM2:-0}"
+if [[ "$INSTALL_AUDIOLDM2" == "1" ]]; then
+ # Local long-form background-music generation for the pipeline audio stage
+ # (Phase 4c.2, second backend alongside MusicGen). AudioLDM2 is a latent
+ # diffusion text-to-audio model shipped in HuggingFace `diffusers` (a pip
+ # package — no clone needed), so this is just a sibling torch venv. The sidecar
+ # `scripts/generate_audioldm2.py` imports `AudioLDM2Pipeline` from diffusers;
+ # server/lib/pythonSetup.js (resolveAudioldm2Python) looks for python3 here.
+ # Runs on Apple-Silicon MPS, CUDA, or CPU — not gated to macOS like MusicGen.
+ # This is a bash installer, so the venv layout is the POSIX bin/python3 (same
+ # as the MusicGen block); the Windows Scripts/python.exe path is resolved on
+ # the JS side by pythonSetup's AUDIOLDM2_VENV_CANDIDATES.
+ AUDIOLDM2_VENV="${HOME}/.portos/venv-audioldm2"
+ AUDIOLDM2_PY="$AUDIOLDM2_VENV/bin/python3"
+ mkdir -p "${HOME}/.portos"
+
+ if [[ ! -x "$AUDIOLDM2_PY" ]]; then
+ echo "📦 Creating AudioLDM2 venv at ${AUDIOLDM2_VENV}..."
+ "$PYTHON_BIN" -m venv "$AUDIOLDM2_VENV"
+ fi
+ echo "📦 Installing AudioLDM2 (diffusers) packages into ${AUDIOLDM2_VENV}..."
+ "$AUDIOLDM2_PY" -m pip install --upgrade pip wheel setuptools >/dev/null
+ # torch runs the model; diffusers provides AudioLDM2Pipeline; transformers +
+ # sentencepiece supply the text encoders (T5 / GPT-2 / CLAP) AudioLDM2 chains;
+ # accelerate speeds device placement; numpy/scipy back the audio math. We write
+ # WAV via the stdlib `wave` module in the sidecar, so no soundfile dep.
+ "$AUDIOLDM2_PY" -m pip install --upgrade \
+ torch \
+ diffusers \
+ "transformers<5" \
+ sentencepiece \
+ accelerate \
+ numpy \
+ scipy \
+ "huggingface_hub[hf_xet]"
+ # Verify the pipeline class imports — a clean import means generation only
+ # needs the one-time weight download, not a broken venv.
+ if ! "$AUDIOLDM2_PY" -c "import torch; from diffusers import AudioLDM2Pipeline" 2>/dev/null; then
+ echo "❌ AudioLDM2 venv built but 'import torch; from diffusers import AudioLDM2Pipeline' failed." >&2
+ echo " Check that torch + diffusers installed cleanly in ${AUDIOLDM2_VENV}." >&2
+ exit 1
+ fi
+ echo "✅ AudioLDM2 venv ready: $AUDIOLDM2_PY"
+fi
+
INSTALL_FLUX2="${INSTALL_FLUX2:-$DEFAULT_INSTALL_FLUX2}"
if [[ "$INSTALL_FLUX2" == "1" ]]; then
@@ -439,6 +485,9 @@ fi
if [[ "$INSTALL_MUSICGEN" == "1" ]] && is_macos; then
echo " MusicGen: ${HOME}/.portos/venv-musicgen/bin/python3 (separate venv, MLX runtime @ ${HOME}/.portos/mlx-examples/musicgen)"
fi
+if [[ "$INSTALL_AUDIOLDM2" == "1" ]]; then
+ echo " AudioLDM2: ${HOME}/.portos/venv-audioldm2/bin/python3 (separate venv, diffusers — long-form audio)"
+fi
if [[ "$INSTALL_FLUX2" == "1" ]]; then
echo " FLUX.2: ${HOME}/.portos/venv-flux2/bin/python3 (separate venv)"
echo " Z-Image: reuses the FLUX.2 venv (Apache 2.0, no HF login needed)"
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 491bff349d..d72bfdbeea 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -210,6 +210,44 @@ export function invalidateMusicgenPython() {
cachedMusicgenPython = null;
}
+// AudioLDM2 (Pipeline Audio Phase 4c.2 — second music backend) runs in its own
+// venv at ~/.portos/venv-audioldm2 — torch + diffusers + transformers, kept
+// apart from MusicGen's MLX pile. AudioLDM2 ships in HuggingFace `diffusers` (a
+// pip package), so unlike MusicGen there's no clone to import from; the sidecar
+// has an optional --runtime-dir for parity but normally just imports diffusers.
+// `INSTALL_AUDIOLDM2=1 bash scripts/setup-image-video.sh` provisions the venv.
+const AUDIOLDM2_VENV_CANDIDATES = IS_WIN
+ ? [
+ join(HOME, '.portos', 'venv-audioldm2', 'Scripts', 'python.exe'),
+ join(PATHS.data, 'python', 'venv-audioldm2', 'Scripts', 'python.exe'),
+ ]
+ : [
+ join(HOME, '.portos', 'venv-audioldm2', 'bin', 'python3'),
+ join(PATHS.data, 'python', 'venv-audioldm2', 'bin', 'python3'),
+ ];
+
+export const AUDIOLDM2_VENV_DEFAULT = AUDIOLDM2_VENV_CANDIDATES[0];
+
+// Optional dir prepended to the sidecar's sys.path before importing diffusers.
+// AudioLDM2 normally imports straight from the venv's diffusers, so this is an
+// empty sentinel (the sidecar's --runtime-dir is a no-op when blank); kept for
+// argv parity with the MusicGen sidecar and so a vendored diffusers build can
+// be pointed at later without a contract change.
+export const AUDIOLDM2_RUNTIME_DIR = '';
+
+let cachedAudioldm2Python = null;
+export function resolveAudioldm2Python() {
+ if (cachedAudioldm2Python && existsSync(cachedAudioldm2Python)) return cachedAudioldm2Python;
+ for (const p of AUDIOLDM2_VENV_CANDIDATES) {
+ if (existsSync(p)) { cachedAudioldm2Python = p; return p; }
+ }
+ return null;
+}
+
+export function invalidateAudioldm2Python() {
+ cachedAudioldm2Python = null;
+}
+
// Used by /api/image-gen/setup/* routes to validate user-supplied pythonPath
// before exec. Single-user / Tailnet model means we trust the operator, but
// "you can shell out to anything" is still too sharp — restrict to actual
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 3970d0f937..7ad42d882e 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -87,12 +87,10 @@ import {
} from '../services/pipeline/musicLibrary.js';
import {
generateMusic,
- MUSICGEN_MODELS,
- DEFAULT_MUSICGEN_MODEL_ID,
- DEFAULT_DURATION_SEC,
- MIN_DURATION_SEC,
- MAX_DURATION_SEC,
- isMusicGenReady,
+ ENGINES,
+ DEFAULT_ENGINE_ID,
+ getEngine,
+ isEngineReady,
} from '../services/pipeline/musicGen.js';
import { uploadSingle } from '../lib/multipart.js';
import { parseComicScript } from '../lib/comicScriptParser.js';
@@ -900,26 +898,51 @@ router.get('/audio/music-library', asyncHandler(async (_req, res) => {
}));
// Local-OSS music generators available to the audio stage (Phase 4c.2).
-// `ready` reflects whether the opt-in MusicGen venv is provisioned, so the UI
-// can show an install hint instead of letting the user type a prompt that 503s.
+// Returns every selectable backend under `engines` (each carrying its models,
+// duration window and a `ready` flag for the opt-in venv) plus a `defaultEngine`
+// id. The top-level `models`/`ready`/duration fields mirror the default engine
+// for backward compatibility with pre-multi-engine clients.
router.get('/audio/music/generators', asyncHandler(async (_req, res) => {
+ const engines = Object.values(ENGINES).map((engine) => ({
+ id: engine.id,
+ name: engine.name,
+ models: engine.models.map(({ id, name }) => ({ id, name })),
+ defaultModelId: engine.defaultModelId,
+ defaultDurationSec: engine.defaultDurationSec,
+ minDurationSec: engine.minDurationSec,
+ maxDurationSec: engine.maxDurationSec,
+ ready: isEngineReady(engine.id),
+ }));
+ const fallback = engines.find((e) => e.id === DEFAULT_ENGINE_ID) ?? engines[0];
res.json({
- models: MUSICGEN_MODELS.map(({ id, name }) => ({ id, name })),
- defaultModelId: DEFAULT_MUSICGEN_MODEL_ID,
- defaultDurationSec: DEFAULT_DURATION_SEC,
- minDurationSec: MIN_DURATION_SEC,
- maxDurationSec: MAX_DURATION_SEC,
- ready: isMusicGenReady(),
+ engines,
+ defaultEngine: DEFAULT_ENGINE_ID,
+ // Back-compat: flatten the default engine's fields to the top level.
+ models: fallback.models,
+ defaultModelId: fallback.defaultModelId,
+ defaultDurationSec: fallback.defaultDurationSec,
+ minDurationSec: fallback.minDurationSec,
+ maxDurationSec: fallback.maxDurationSec,
+ ready: fallback.ready,
});
}));
-// Generate a background-music track with MusicGen (MLX) and attach it to the
-// issue as a `source: 'gen'` track. The generated WAV lands in the shared
+// Every model id across all engines — the schema validates `modelId` against
+// this union and `generateMusic` resolves it within the chosen engine (falling
+// back to that engine's default for a mismatched id).
+const ALL_MODEL_IDS = Object.values(ENGINES).flatMap((e) => e.models.map((m) => m.id));
+// The widest duration window across engines; per-engine clamping happens in the
+// service, so the schema just rejects absurd values.
+const MAX_ENGINE_DURATION = Math.max(...Object.values(ENGINES).map((e) => e.maxDurationSec));
+
+// Generate a background-music track with the selected backend and attach it to
+// the issue as a `source: 'gen'` track. The generated WAV lands in the shared
// music library, so it's reusable across issues exactly like an upload.
const musicGenerateSchema = z.object({
prompt: z.string().trim().min(1).max(800),
- durationSec: z.number().min(MIN_DURATION_SEC).max(MAX_DURATION_SEC).optional(),
- modelId: z.enum(MUSICGEN_MODELS.map((m) => m.id)).optional(),
+ engine: z.enum(Object.keys(ENGINES)).optional(),
+ durationSec: z.number().min(1).max(MAX_ENGINE_DURATION).optional(),
+ modelId: z.enum(ALL_MODEL_IDS).optional(),
});
router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req, res) => {
const body = validateRequest(musicGenerateSchema, req.body ?? {});
@@ -930,8 +953,9 @@ router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req,
issuesSvc.assertStageUnlocked(issue, 'audio');
const gen = await generateMusic({
prompt: body.prompt,
- durationSec: body.durationSec ?? DEFAULT_DURATION_SEC,
- modelId: body.modelId ?? DEFAULT_MUSICGEN_MODEL_ID,
+ engine: body.engine ?? DEFAULT_ENGINE_ID,
+ durationSec: body.durationSec,
+ modelId: body.modelId,
}).catch((err) => { throw mapServiceError(err); });
const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(
req.params.id,
@@ -942,7 +966,7 @@ router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req,
errorMessage: '',
}),
).catch((err) => { throw mapServiceError(err); });
- res.json({ issue: updatedIssue, stage, music: stage.music, durationSec: gen.durationSec, modelId: gen.modelId });
+ res.json({ issue: updatedIssue, stage, music: stage.music, durationSec: gen.durationSec, modelId: gen.modelId, engine: gen.engine });
}));
router.post('/issues/:id/stages/audio/music/upload', musicUpload, asyncHandler(async (req, res) => {
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index b8c2bbeeb7..935bf0ac4d 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -1,22 +1,30 @@
/**
- * Local OSS music generation — MusicGen via MLX (Pipeline Audio Phase 4c.2).
+ * Local OSS music generation — generator-agnostic backend selector
+ * (Pipeline Audio Phase 4c.2).
*
- * The first generator behind the audio stage's `source: 'gen'` library entry.
- * Meta's MusicGen (MLX port) renders bounded text-conditioned clips on-device:
- * no network, no API key — the same "local OSS first" posture as the Kokoro /
- * Piper voice path in `audio.js`. A future 3rd-party engine (Suno, etc.) would
- * plug in here as a sibling generator behind the same `generateMusic` contract;
- * we ship local-only for now per the product decision.
+ * The audio stage's `source: 'gen'` library entry renders text-conditioned
+ * background music on-device: no network, no API key — the same "local OSS
+ * first" posture as the Kokoro / Piper voice path in `audio.js`. Each backend
+ * is a sibling Python sidecar behind one `generateMusic` contract:
*
- * Runtime: the MLX MusicGen code lives in ml-explore/mlx-examples (not a pip
- * package), so generation needs the opt-in venv + clone from
- * `INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh`. When that isn't set
- * up, `generateMusic` throws a 503 with the install hint rather than a bare
- * spawn error — exactly like the FLUX.2 venv gate.
+ * - `musicgen` — Meta's MusicGen via MLX (Apple Silicon). Bounded clips
+ * (≤30s; trained on 30s windows, degrades past that). First backend.
+ * - `audioldm2` — AudioLDM2 latent diffusion via HuggingFace `diffusers`.
+ * Long-form (well past 30s), torch on MPS/CUDA/CPU. Second backend.
*
- * Output: a 32 kHz mono WAV written into the shared music library (PATHS.music)
- * under a `music-gen-<uuid>.wav` basename, so the picker treats a generated
- * track identically to an uploaded one.
+ * An ENGINES registry holds each backend's models, duration window, sidecar
+ * script, venv resolver and install hint, so the route, UI and `generateMusic`
+ * stay engine-agnostic — adding a third backend is one ENGINES entry plus its
+ * Python sidecar, with the route contract unchanged.
+ *
+ * Runtime: each backend has an opt-in venv from
+ * `INSTALL_<ENGINE>=1 bash scripts/setup-image-video.sh`. When it isn't set up,
+ * `generateMusic` throws a 503 with that backend's install hint rather than a
+ * bare spawn error — exactly like the FLUX.2 venv gate.
+ *
+ * Output: a mono WAV written into the shared music library (PATHS.music) under
+ * a `music-gen-<uuid>.wav` basename, so the picker treats a generated track
+ * identically to an uploaded one.
*/
import { spawn } from 'child_process';
@@ -28,26 +36,32 @@ import { randomUUID } from 'crypto';
import { PATHS, ensureDir } from '../../lib/fileUtils.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { hfTokenEnv } from '../../lib/hfToken.js';
-import { resolveMusicgenPython, MUSICGEN_RUNTIME_DIR, MUSICGEN_VENV_DEFAULT } from '../../lib/pythonSetup.js';
+import {
+ resolveMusicgenPython, MUSICGEN_RUNTIME_DIR, MUSICGEN_VENV_DEFAULT,
+ resolveAudioldm2Python, AUDIOLDM2_RUNTIME_DIR, AUDIOLDM2_VENV_DEFAULT,
+} from '../../lib/pythonSetup.js';
import { ServerError } from '../../lib/errorHandler.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
-// scripts/generate_musicgen.py lives at the repo root — resolve module-relative
-// so the path is correct regardless of the server process's cwd.
-const SIDECAR_SCRIPT = join(__dirname, '../../../scripts/generate_musicgen.py');
+// The sidecar scripts live at the repo root — resolve module-relative so the
+// paths are correct regardless of the server process's cwd.
+const MUSICGEN_SCRIPT = join(__dirname, '../../../scripts/generate_musicgen.py');
+const AUDIOLDM2_SCRIPT = join(__dirname, '../../../scripts/generate_audioldm2.py');
+// Back-compat alias: the original single-backend constant name.
+const SIDECAR_SCRIPT = MUSICGEN_SCRIPT;
-// Practical clip-length window. MusicGen was trained on 30s windows and
-// degrades past that; the floor keeps at least one decoder step.
+// MusicGen's practical clip-length window. It was trained on 30s windows and
+// degrades past that; the floor keeps at least one decoder step. Exported as
+// the module-level defaults for backward compatibility — `musicgen` is the
+// default engine, so these mirror its ENGINES entry.
export const MIN_DURATION_SEC = 1;
export const MAX_DURATION_SEC = 30;
export const DEFAULT_DURATION_SEC = 12;
-// Registry of selectable generators. "Pick generator first" (the PLAN's
-// gating decision) resolves to MusicGen across three size tiers; medium is the
-// default — a quality/speed balance that fits comfortably in unified memory.
-// Kept as a small in-module constant rather than threaded through the
-// image/video `media-models.json` registry, whose seed/merge/migration
-// machinery doesn't apply to a one-shot audio generator.
+// MusicGen model tiers; medium is the default — a quality/speed balance that
+// fits comfortably in unified memory. Kept as a small in-module constant rather
+// than threaded through the image/video `media-models.json` registry, whose
+// seed/merge/migration machinery doesn't apply to a one-shot audio generator.
export const MUSICGEN_MODELS = Object.freeze([
{ id: 'musicgen-small', repo: 'facebook/musicgen-small', name: 'MusicGen Small (~2 GB, fastest)' },
{ id: 'musicgen-medium', repo: 'facebook/musicgen-medium', name: 'MusicGen Medium (~6 GB, balanced)' },
@@ -55,46 +69,134 @@ export const MUSICGEN_MODELS = Object.freeze([
]);
export const DEFAULT_MUSICGEN_MODEL_ID = 'musicgen-medium';
+// AudioLDM2 model tiers; the base model is the default — long-form text-to-audio
+// with the smallest weights. `audioldm2-large` and `-music` trade size for
+// fidelity / music-specialization.
+export const AUDIOLDM2_MODELS = Object.freeze([
+ { id: 'audioldm2', repo: 'cvssp/audioldm2', name: 'AudioLDM2 Base (~3 GB, long-form)' },
+ { id: 'audioldm2-large', repo: 'cvssp/audioldm2-large', name: 'AudioLDM2 Large (~7 GB, best quality)' },
+ { id: 'audioldm2-music', repo: 'cvssp/audioldm2-music', name: 'AudioLDM2 Music (~3 GB, music-tuned)' },
+]);
+export const DEFAULT_AUDIOLDM2_MODEL_ID = 'audioldm2';
+
+/**
+ * Backend registry. Each engine is fully described here so the route, UI and
+ * `generateMusic` stay generator-agnostic. Fields:
+ * - `id`/`name` — stable id (the contract stored on the request) + label
+ * - `models`/`defaultModelId` — selectable weights for this backend
+ * - duration window — min/max/default seconds, clamped before spawn
+ * - `scriptPath` — the Python sidecar
+ * - `runtimeDir` — value for the sidecar's --runtime-dir flag
+ * - `resolvePython` — () => venv interpreter path | null (readiness probe)
+ * - `venvDefault`/`installEnv` — install-hint pieces for the 503 message
+ */
+export const ENGINES = Object.freeze({
+ musicgen: {
+ id: 'musicgen',
+ name: 'MusicGen (MLX)',
+ models: MUSICGEN_MODELS,
+ defaultModelId: DEFAULT_MUSICGEN_MODEL_ID,
+ minDurationSec: 1,
+ maxDurationSec: 30,
+ defaultDurationSec: 12,
+ scriptPath: MUSICGEN_SCRIPT,
+ runtimeDir: MUSICGEN_RUNTIME_DIR,
+ resolvePython: resolveMusicgenPython,
+ venvDefault: MUSICGEN_VENV_DEFAULT,
+ installEnv: 'INSTALL_MUSICGEN',
+ },
+ audioldm2: {
+ id: 'audioldm2',
+ name: 'AudioLDM2 (diffusers)',
+ models: AUDIOLDM2_MODELS,
+ defaultModelId: DEFAULT_AUDIOLDM2_MODEL_ID,
+ minDurationSec: 1,
+ maxDurationSec: 120,
+ defaultDurationSec: 20,
+ scriptPath: AUDIOLDM2_SCRIPT,
+ runtimeDir: AUDIOLDM2_RUNTIME_DIR,
+ resolvePython: resolveAudioldm2Python,
+ venvDefault: AUDIOLDM2_VENV_DEFAULT,
+ installEnv: 'INSTALL_AUDIOLDM2',
+ },
+});
+
+export const DEFAULT_ENGINE_ID = 'musicgen';
+
+// Resolve a requested engine id to its registry entry, falling back to the
+// default engine for unknown/absent ids (the route validates against the known
+// set, but generateMusic can be called directly).
+export function getEngine(engineId) {
+ return ENGINES[engineId] || ENGINES[DEFAULT_ENGINE_ID];
+}
+
+// Look up a model within a specific engine. Returns null for unknown ids so the
+// caller can fall back to the engine's default.
+export function getEngineModel(engineId, modelId) {
+ const engine = getEngine(engineId);
+ return engine.models.find((m) => m.id === modelId) || null;
+}
+
+// Back-compat: MusicGen-specific model lookup (pre-multi-engine callers/tests).
export function getMusicgenModel(modelId) {
return MUSICGEN_MODELS.find((m) => m.id === modelId) || null;
}
-// Whether the opt-in MusicGen venv is provisioned. The UI gates its "Generate"
-// affordance on this so users see an install hint instead of a 503 after
-// typing a prompt. Cheap (an existsSync probe behind resolveMusicgenPython's
-// cache) — safe to call per request.
+// Whether a backend's opt-in venv is provisioned. The UI gates its "Generate"
+// affordance on this so users see an install hint instead of a 503 after typing
+// a prompt. Cheap (an existsSync probe behind the resolver's cache) — safe to
+// call per request.
+export function isEngineReady(engineId) {
+ return getEngine(engineId).resolvePython() !== null;
+}
+
+// Back-compat: MusicGen readiness probe.
export function isMusicGenReady() {
return resolveMusicgenPython() !== null;
}
-// Clamp a requested duration into the model's usable window. Non-finite input
-// falls back to the default rather than throwing — the route validates shape,
-// this guards the math.
-export function clampDuration(durationSec) {
+// Clamp a requested duration into an engine's usable window. Non-finite input
+// falls back to that engine's default rather than throwing — the route
+// validates shape, this guards the math. `engineId` defaults to the module's
+// default engine so the back-compat signature `clampDuration(seconds)` keeps
+// the original MusicGen window.
+export function clampDuration(durationSec, engineId = DEFAULT_ENGINE_ID) {
+ const engine = getEngine(engineId);
const n = Number(durationSec);
- if (!Number.isFinite(n)) return DEFAULT_DURATION_SEC;
- return Math.max(MIN_DURATION_SEC, Math.min(MAX_DURATION_SEC, n));
+ if (!Number.isFinite(n)) return engine.defaultDurationSec;
+ return Math.max(engine.minDurationSec, Math.min(engine.maxDurationSec, n));
}
/**
- * Build the `{ bin, args }` for the MusicGen sidecar. Pure — unit-tested
- * without spawning Python. `runtimeDir` is the mlx-examples musicgen/ package
- * dir the sidecar adds to sys.path.
+ * Build the `{ bin, args }` for a backend's sidecar. Pure — unit-tested without
+ * spawning Python. Both sidecars share the same flag contract
+ * (`--model/--text/--duration/--output/--runtime-dir`), so one builder serves
+ * every engine; `engineId` selects the duration window + script + runtime dir.
*/
-export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, runtimeDir = MUSICGEN_RUNTIME_DIR, repo, prompt, durationSec, outputPath }) {
+export function buildSidecarArgs({ engineId = DEFAULT_ENGINE_ID, pythonPath, scriptPath, runtimeDir, repo, prompt, durationSec, outputPath }) {
+ const engine = getEngine(engineId);
return {
bin: pythonPath,
args: [
- scriptPath,
+ scriptPath ?? engine.scriptPath,
'--model', repo,
'--text', prompt,
- '--duration', String(clampDuration(durationSec)),
+ '--duration', String(clampDuration(durationSec, engine.id)),
'--output', outputPath,
- '--runtime-dir', runtimeDir,
+ '--runtime-dir', runtimeDir ?? engine.runtimeDir,
],
};
}
+/**
+ * Back-compat wrapper: build the MusicGen sidecar argv. Pre-existing callers
+ * and tests use this name; it forwards to the engine-agnostic builder pinned to
+ * the `musicgen` engine.
+ */
+export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, runtimeDir = MUSICGEN_RUNTIME_DIR, repo, prompt, durationSec, outputPath }) {
+ return buildSidecarArgs({ engineId: 'musicgen', pythonPath, scriptPath, runtimeDir, repo, prompt, durationSec, outputPath });
+}
+
// Pull the saved path + actual duration out of the sidecar's `RESULT:<json>`
// line. Returns null when no parseable result line is present so the caller
// can fail with a useful message instead of a malformed success.
@@ -110,23 +212,27 @@ function parseResultLine(stdout) {
/**
* Generate a background-music track and land it in the shared music library.
- * Returns `{ filename, durationSec, modelId, model }`. Throws a ServerError
- * (503) when the MusicGen venv isn't provisioned, or (500) when the sidecar
- * exits non-zero / produces no result.
+ * Returns `{ filename, durationSec, modelId, model, engine }`. Throws a
+ * ServerError (503) when the selected backend's venv isn't provisioned, or
+ * (500) when the sidecar exits non-zero / produces no result.
*
+ * `engine` selects the backend (`musicgen` | `audioldm2`); unknown ids fall
+ * back to the default. `modelId` is resolved within that engine's registry.
* `signal` (optional AbortSignal) SIGTERMs the child — wired through so a
* future cancel button can abort a long render.
*/
-export async function generateMusic({ prompt, durationSec = DEFAULT_DURATION_SEC, modelId = DEFAULT_MUSICGEN_MODEL_ID, signal } = {}) {
+export async function generateMusic({ prompt, engine: engineId = DEFAULT_ENGINE_ID, durationSec, modelId, signal } = {}) {
const text = (prompt || '').trim();
if (!text) {
throw new ServerError('prompt is required', { status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });
}
- const model = getMusicgenModel(modelId) || getMusicgenModel(DEFAULT_MUSICGEN_MODEL_ID);
- const pythonPath = resolveMusicgenPython();
+ const engine = getEngine(engineId);
+ const model = getEngineModel(engine.id, modelId) || getEngineModel(engine.id, engine.defaultModelId);
+ const resolvedDuration = durationSec ?? engine.defaultDurationSec;
+ const pythonPath = engine.resolvePython();
if (!pythonPath) {
throw new ServerError(
- `MusicGen runtime not found. Run \`INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected venv at ${MUSICGEN_VENV_DEFAULT}).`,
+ `${engine.name} runtime not found. Run \`${engine.installEnv}=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected venv at ${engine.venvDefault}).`,
{ status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' },
);
}
@@ -134,14 +240,14 @@ export async function generateMusic({ prompt, durationSec = DEFAULT_DURATION_SEC
await ensureDir(PATHS.music);
const filename = `music-gen-${randomUUID()}.wav`;
const outputPath = join(PATHS.music, filename);
- const { bin, args } = buildMusicGenArgs({ pythonPath, repo: model.repo, prompt: text, durationSec, outputPath });
+ const { bin, args } = buildSidecarArgs({ engineId: engine.id, pythonPath, repo: model.repo, prompt: text, durationSec: resolvedDuration, outputPath });
- console.log(`🎼 Generating music [${model.id}] ${clampDuration(durationSec)}s: "${text.slice(0, 60)}"`);
- // MusicGen's facebook/* weights are ungated, so a token isn't required — but
- // pass it through when the user has one set so the first download doesn't hit
- // anonymous HF rate limits.
+ console.log(`🎼 Generating music [${engine.id}/${model.id}] ${clampDuration(resolvedDuration, engine.id)}s: "${text.slice(0, 60)}"`);
+ // The default backends use ungated HF weights (facebook/* and cvssp/*), so a
+ // token isn't required — but pass it through when the user has one set so the
+ // first download doesn't hit anonymous HF rate limits.
const env = safeChildProcessEnv(await hfTokenEnv());
- const result = await runMusicGenProcess({ bin, args, env, signal });
+ const result = await runSidecarProcess({ bin, args, env, signal });
// A clean exit isn't enough — the sidecar could exit 0 yet write nothing (or
// a truncated file) if the runtime changes shape. Require both a parsed
// RESULT line AND a non-empty file on disk before we persist the library
@@ -158,19 +264,20 @@ export async function generateMusic({ prompt, durationSec = DEFAULT_DURATION_SEC
}
return {
filename,
- durationSec: Number.isFinite(parsed.durationSec) ? parsed.durationSec : clampDuration(durationSec),
+ durationSec: Number.isFinite(parsed.durationSec) ? parsed.durationSec : clampDuration(resolvedDuration, engine.id),
modelId: model.id,
model: model.name,
+ engine: engine.id,
};
}
-// Spawn the sidecar and resolve `{ ok, stdout, reason? }`. STAGE: lines on
-// stderr are echoed to pm2 logs so a stuck first-run model download is visible
-// (mirrors the image/video sidecars). Captures stdout for the RESULT line and
-// a bounded stderr tail for the failure reason. Not a route handler — the
-// spawn-error / close branches must not throw (they run outside the Express
+// Spawn a backend sidecar and resolve `{ ok, stdout, reason? }`. STAGE: lines
+// on stderr are echoed to pm2 logs so a stuck first-run model download is
+// visible (mirrors the image/video sidecars). Captures stdout for the RESULT
+// line and a bounded stderr tail for the failure reason. Not a route handler —
+// the spawn-error / close branches must not throw (they run outside the Express
// lifecycle), so they resolve a structured result instead.
-function runMusicGenProcess({ bin, args, env, signal }) {
+function runSidecarProcess({ bin, args, env, signal }) {
return new Promise((resolve) => {
const proc = spawn(bin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
let stdout = '';
diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.js
index 9f03cee17f..9ddf630ad5 100644
--- a/server/services/pipeline/musicGen.test.js
+++ b/server/services/pipeline/musicGen.test.js
@@ -1,10 +1,24 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { rm, readdir } from 'fs/promises';
+import { writeFileSync, mkdtempSync } from 'fs';
+
+// ---- Pure-helper tests (no mocks needed) ---------------------------------
import {
buildMusicGenArgs,
+ buildSidecarArgs,
clampDuration,
getMusicgenModel,
+ getEngine,
+ getEngineModel,
+ isEngineReady,
+ ENGINES,
+ DEFAULT_ENGINE_ID,
MUSICGEN_MODELS,
+ AUDIOLDM2_MODELS,
DEFAULT_MUSICGEN_MODEL_ID,
+ DEFAULT_AUDIOLDM2_MODEL_ID,
MIN_DURATION_SEC,
MAX_DURATION_SEC,
DEFAULT_DURATION_SEC,
@@ -31,23 +45,136 @@ describe('MUSICGEN_MODELS registry', () => {
});
});
+describe('AUDIOLDM2_MODELS registry', () => {
+ it('has a stable, unique id + cvssp repo for each model', () => {
+ const ids = AUDIOLDM2_MODELS.map((m) => m.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ for (const m of AUDIOLDM2_MODELS) {
+ expect(typeof m.id).toBe('string');
+ expect(m.repo).toMatch(/^cvssp\/audioldm2/);
+ expect(typeof m.name).toBe('string');
+ }
+ });
+
+ it('default model id resolves within the audioldm2 engine', () => {
+ expect(getEngineModel('audioldm2', DEFAULT_AUDIOLDM2_MODEL_ID)).toBeTruthy();
+ });
+});
+
+describe('ENGINES backend registry', () => {
+ it('exposes both backends with the fields the route + UI consume', () => {
+ expect(Object.keys(ENGINES).sort()).toEqual(['audioldm2', 'musicgen']);
+ for (const engine of Object.values(ENGINES)) {
+ expect(typeof engine.id).toBe('string');
+ expect(typeof engine.name).toBe('string');
+ expect(Array.isArray(engine.models)).toBe(true);
+ expect(engine.models.length).toBeGreaterThan(0);
+ expect(engine.models.some((m) => m.id === engine.defaultModelId)).toBe(true);
+ expect(engine.minDurationSec).toBeGreaterThanOrEqual(1);
+ expect(engine.maxDurationSec).toBeGreaterThanOrEqual(engine.minDurationSec);
+ expect(engine.defaultDurationSec).toBeGreaterThanOrEqual(engine.minDurationSec);
+ expect(engine.defaultDurationSec).toBeLessThanOrEqual(engine.maxDurationSec);
+ expect(typeof engine.resolvePython).toBe('function');
+ expect(typeof engine.installEnv).toBe('string');
+ expect(engine.scriptPath).toMatch(/generate_\w+\.py$/);
+ }
+ });
+
+ it('default engine is musicgen (back-compat)', () => {
+ expect(DEFAULT_ENGINE_ID).toBe('musicgen');
+ expect(getEngine(DEFAULT_ENGINE_ID).id).toBe('musicgen');
+ });
+
+ it('audioldm2 has a wider duration window than musicgen (long-form)', () => {
+ expect(ENGINES.audioldm2.maxDurationSec).toBeGreaterThan(ENGINES.musicgen.maxDurationSec);
+ });
+
+ it('musicgen window mirrors the legacy module-level constants', () => {
+ expect(ENGINES.musicgen.minDurationSec).toBe(MIN_DURATION_SEC);
+ expect(ENGINES.musicgen.maxDurationSec).toBe(MAX_DURATION_SEC);
+ expect(ENGINES.musicgen.defaultDurationSec).toBe(DEFAULT_DURATION_SEC);
+ });
+});
+
+describe('getEngine / getEngineModel', () => {
+ it('falls back to the default engine for an unknown id', () => {
+ expect(getEngine('does-not-exist').id).toBe(DEFAULT_ENGINE_ID);
+ expect(getEngine(undefined).id).toBe(DEFAULT_ENGINE_ID);
+ });
+
+ it('resolves a model within the named engine', () => {
+ expect(getEngineModel('musicgen', 'musicgen-small').repo).toBe('facebook/musicgen-small');
+ expect(getEngineModel('audioldm2', 'audioldm2-large').repo).toBe('cvssp/audioldm2-large');
+ });
+
+ it('returns null when the model belongs to a different engine', () => {
+ // musicgen-small is not an audioldm2 model — selection must not bleed across engines.
+ expect(getEngineModel('audioldm2', 'musicgen-small')).toBeNull();
+ expect(getEngineModel('musicgen', 'audioldm2')).toBeNull();
+ });
+});
+
describe('clampDuration', () => {
- it('passes through an in-range value', () => {
+ it('passes through an in-range value (default engine)', () => {
expect(clampDuration(12)).toBe(12);
});
- it('floors at MIN and caps at MAX', () => {
- expect(clampDuration(0)).toBe(MIN_DURATION_SEC);
- expect(clampDuration(-5)).toBe(MIN_DURATION_SEC);
- expect(clampDuration(9999)).toBe(MAX_DURATION_SEC);
+ it('floors at MIN and caps at MAX for musicgen', () => {
+ expect(clampDuration(0, 'musicgen')).toBe(ENGINES.musicgen.minDurationSec);
+ expect(clampDuration(-5, 'musicgen')).toBe(ENGINES.musicgen.minDurationSec);
+ expect(clampDuration(9999, 'musicgen')).toBe(ENGINES.musicgen.maxDurationSec);
+ });
+ it('uses the audioldm2 window when that engine is named', () => {
+ // 90s is over musicgen's 30s ceiling but inside audioldm2's window.
+ expect(clampDuration(90, 'audioldm2')).toBe(90);
+ expect(clampDuration(9999, 'audioldm2')).toBe(ENGINES.audioldm2.maxDurationSec);
});
- it('falls back to the default on non-finite input', () => {
- expect(clampDuration(NaN)).toBe(DEFAULT_DURATION_SEC);
- expect(clampDuration('abc')).toBe(DEFAULT_DURATION_SEC);
+ it('falls back to the engine default on non-finite input', () => {
+ expect(clampDuration(NaN, 'musicgen')).toBe(ENGINES.musicgen.defaultDurationSec);
+ expect(clampDuration('abc', 'audioldm2')).toBe(ENGINES.audioldm2.defaultDurationSec);
expect(clampDuration(undefined)).toBe(DEFAULT_DURATION_SEC);
});
});
-describe('buildMusicGenArgs', () => {
+describe('buildSidecarArgs', () => {
+ const base = {
+ pythonPath: '/venv/bin/python3',
+ repo: 'facebook/musicgen-medium',
+ prompt: 'tense cinematic synth',
+ durationSec: 10,
+ outputPath: '/data/music/music-gen-abc.wav',
+ };
+
+ it('routes to the musicgen sidecar script for the musicgen engine', () => {
+ const { bin, args } = buildSidecarArgs({ ...base, engineId: 'musicgen' });
+ expect(bin).toBe('/venv/bin/python3');
+ expect(args[0]).toMatch(/generate_musicgen\.py$/);
+ const flag = (name) => args[args.indexOf(name) + 1];
+ expect(flag('--model')).toBe('facebook/musicgen-medium');
+ expect(flag('--text')).toBe('tense cinematic synth');
+ expect(flag('--output')).toBe('/data/music/music-gen-abc.wav');
+ });
+
+ it('routes to the audioldm2 sidecar script for the audioldm2 engine', () => {
+ const { args } = buildSidecarArgs({ ...base, engineId: 'audioldm2', repo: 'cvssp/audioldm2' });
+ expect(args[0]).toMatch(/generate_audioldm2\.py$/);
+ expect(args[args.indexOf('--model') + 1]).toBe('cvssp/audioldm2');
+ });
+
+ it('clamps the duration to the engine window', () => {
+ // 120s clamps to musicgen's 30s but passes through for audioldm2.
+ const mg = buildSidecarArgs({ ...base, engineId: 'musicgen', durationSec: 120 });
+ expect(mg.args[mg.args.indexOf('--duration') + 1]).toBe(String(ENGINES.musicgen.maxDurationSec));
+ const ald = buildSidecarArgs({ ...base, engineId: 'audioldm2', durationSec: 120 });
+ expect(ald.args[ald.args.indexOf('--duration') + 1]).toBe('120');
+ });
+
+ it('passes the runtime-dir flag (default per engine)', () => {
+ const { args } = buildSidecarArgs({ ...base, engineId: 'audioldm2' });
+ expect(args).toContain('--runtime-dir');
+ });
+});
+
+describe('buildMusicGenArgs (back-compat wrapper)', () => {
const base = {
pythonPath: '/venv/bin/python3',
repo: 'facebook/musicgen-medium',
@@ -57,7 +184,7 @@ describe('buildMusicGenArgs', () => {
runtimeDir: '/home/u/.portos/mlx-examples/musicgen',
};
- it('builds the sidecar argv with every flag the script expects', () => {
+ it('builds the musicgen sidecar argv with every flag the script expects', () => {
const { bin, args } = buildMusicGenArgs(base);
expect(bin).toBe('/venv/bin/python3');
expect(args[0]).toMatch(/generate_musicgen\.py$/);
@@ -80,3 +207,164 @@ describe('buildMusicGenArgs', () => {
expect(args[args.indexOf('--duration') + 1]).toBe(String(MIN_DURATION_SEC));
});
});
+
+// ---- generateMusic backend-selection tests (mocked subprocess) -----------
+// These exercise the JS plumbing only — they never run Python. The spawn mock
+// records which sidecar script was launched and synthesizes a success/failure
+// without any model weights.
+
+// Shared mutable state for the mock factories — defined via vi.hoisted so it's
+// initialized before the (hoisted) vi.mock factories run.
+const h = vi.hoisted(() => ({
+ testDir: '',
+ spawnCalls: [],
+ mockExitCode: 0,
+ mockStdout: '',
+ mockWriteOutput: true,
+ musicgenPython: '/fake/venv-musicgen/bin/python3',
+ audioldm2Python: '/fake/venv-audioldm2/bin/python3',
+}));
+// Set after the top-level imports resolve; the fileUtils mock reads it through
+// a getter so the (eagerly-built) PATHS object always reflects the final value.
+h.testDir = mkdtempSync(join(tmpdir(), 'musicgen-test-'));
+const TEST_DIR = h.testDir;
+const spawnCalls = h.spawnCalls;
+
+vi.mock('child_process', async () => {
+ const actual = await vi.importActual('child_process');
+ return {
+ ...actual,
+ spawn: (bin, args, _opts) => {
+ h.spawnCalls.push({ bin, args });
+ const listeners = {};
+ const proc = {
+ stdout: { on: (event, cb) => { if (event === 'data' && h.mockStdout) cb(Buffer.from(h.mockStdout)); } },
+ stderr: { on: (event, cb) => { if (event === 'data') cb(Buffer.from('STAGE:generate\n')); } },
+ on: (event, cb) => { listeners[event] = cb; },
+ kill: () => {},
+ };
+ Promise.resolve().then(() => {
+ if (h.mockExitCode === 0 && h.mockWriteOutput) {
+ const outPath = args[args.indexOf('--output') + 1];
+ writeFileSync(outPath, Buffer.from('fake-wav-bytes'));
+ }
+ listeners.close?.(h.mockExitCode, null);
+ });
+ return proc;
+ },
+ };
+});
+
+// PATHS.music points at the temp dir so the fake WAV lands somewhere writable.
+// `music` is a getter so the value reflects h.testDir even though this factory
+// runs (hoisted) before the top-level `h.testDir = mkdtempSync(...)` assignment.
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, get music() { return h.testDir; } },
+ ensureDir: async () => {},
+ };
+});
+
+vi.mock('../../lib/hfToken.js', () => ({ hfTokenEnv: async () => ({}) }));
+
+// Venv resolvers — flip readiness per engine per test.
+vi.mock('../../lib/pythonSetup.js', async () => {
+ const actual = await vi.importActual('../../lib/pythonSetup.js');
+ return {
+ ...actual,
+ resolveMusicgenPython: () => h.musicgenPython,
+ resolveAudioldm2Python: () => h.audioldm2Python,
+ };
+});
+
+const { generateMusic } = await import('./musicGen.js');
+
+beforeEach(() => {
+ h.spawnCalls.length = 0;
+ h.mockExitCode = 0;
+ h.mockWriteOutput = true;
+ h.mockStdout = 'STAGE:done\nRESULT:{"output":"x","durationSec":12.5,"sampleRate":32000}\n';
+ h.musicgenPython = '/fake/venv-musicgen/bin/python3';
+ h.audioldm2Python = '/fake/venv-audioldm2/bin/python3';
+});
+
+afterEach(async () => {
+ for (const f of await readdir(TEST_DIR).catch(() => [])) {
+ await rm(join(TEST_DIR, f), { force: true }).catch(() => {});
+ }
+});
+
+describe('generateMusic backend selection', () => {
+ it('defaults to the musicgen sidecar', async () => {
+ const res = await generateMusic({ prompt: 'calm piano' });
+ expect(spawnCalls).toHaveLength(1);
+ expect(spawnCalls[0].bin).toBe('/fake/venv-musicgen/bin/python3');
+ expect(spawnCalls[0].args[0]).toMatch(/generate_musicgen\.py$/);
+ expect(res.engine).toBe('musicgen');
+ expect(res.modelId).toBe(DEFAULT_MUSICGEN_MODEL_ID);
+ expect(res.filename).toMatch(/^music-gen-.*\.wav$/);
+ });
+
+ it('routes to the audioldm2 sidecar + venv when engine=audioldm2', async () => {
+ const res = await generateMusic({ prompt: 'ambient drone', engine: 'audioldm2', durationSec: 60 });
+ expect(spawnCalls).toHaveLength(1);
+ expect(spawnCalls[0].bin).toBe('/fake/venv-audioldm2/bin/python3');
+ expect(spawnCalls[0].args[0]).toMatch(/generate_audioldm2\.py$/);
+ // 60s is within audioldm2's window — it passes through, not clamped to 30.
+ expect(spawnCalls[0].args[spawnCalls[0].args.indexOf('--duration') + 1]).toBe('60');
+ expect(res.engine).toBe('audioldm2');
+ expect(res.modelId).toBe(DEFAULT_AUDIOLDM2_MODEL_ID);
+ });
+
+ it('resolves modelId within the selected engine', async () => {
+ await generateMusic({ prompt: 'jazz', engine: 'audioldm2', modelId: 'audioldm2-music' });
+ expect(spawnCalls[0].args[spawnCalls[0].args.indexOf('--model') + 1]).toBe('cvssp/audioldm2-music');
+ });
+
+ it('falls back to the engine default for a cross-engine modelId', async () => {
+ // Passing a musicgen model id to the audioldm2 engine must not leak through.
+ await generateMusic({ prompt: 'jazz', engine: 'audioldm2', modelId: 'musicgen-small' });
+ expect(spawnCalls[0].args[spawnCalls[0].args.indexOf('--model') + 1]).toBe('cvssp/audioldm2');
+ });
+
+ it('throws 503 with the engine-specific install hint when that venv is missing', async () => {
+ h.audioldm2Python = null;
+ await expect(generateMusic({ prompt: 'x', engine: 'audioldm2' }))
+ .rejects.toMatchObject({ status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' });
+ await expect(generateMusic({ prompt: 'x', engine: 'audioldm2' }))
+ .rejects.toThrow(/INSTALL_AUDIOLDM2/);
+ // musicgen still works — readiness is per engine.
+ const res = await generateMusic({ prompt: 'x' });
+ expect(res.engine).toBe('musicgen');
+ });
+
+ it('rejects an empty prompt with 400 before spawning anything', async () => {
+ await expect(generateMusic({ prompt: ' ', engine: 'audioldm2' }))
+ .rejects.toMatchObject({ status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });
+ expect(spawnCalls).toHaveLength(0);
+ });
+
+ it('fails 500 and unlinks the partial when the sidecar writes no audio', async () => {
+ h.mockWriteOutput = false;
+ await expect(generateMusic({ prompt: 'x', engine: 'audioldm2' }))
+ .rejects.toMatchObject({ status: 500, code: 'PIPELINE_MUSIC_GEN_FAILED' });
+ expect(await readdir(TEST_DIR)).toHaveLength(0);
+ });
+
+ it('fails 500 when the sidecar exits non-zero', async () => {
+ h.mockExitCode = 1;
+ await expect(generateMusic({ prompt: 'x' }))
+ .rejects.toMatchObject({ status: 500, code: 'PIPELINE_MUSIC_GEN_FAILED' });
+ });
+});
+
+describe('isEngineReady', () => {
+ it('reflects each engine resolver independently', () => {
+ h.musicgenPython = '/fake/venv-musicgen/bin/python3';
+ h.audioldm2Python = null;
+ expect(isEngineReady('musicgen')).toBe(true);
+ expect(isEngineReady('audioldm2')).toBe(false);
+ });
+});