@audiofool/moondog 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  // Moondog's own Stable Audio 3 install. Only when the listener asks, it downloads uv, Stability AI's
2
2
  // code, a Python environment and the chosen model's weights into one folder Moondog manages, only
3
3
  // from the pinned official sources (sources.mjs), and checks every file before anything runs it.
4
+ // The build is the one that runs here: MLX on a Mac with Apple silicon, the CPU build on Windows and Linux.
4
5
  // The terminal and the window are separate processes on that folder: a lock file names the process
5
6
  // that runs the job, and that process writes its progress to a status file the other one reads.
6
7
  import { spawn } from "node:child_process";
@@ -10,8 +11,8 @@ import { access, constants, lstat, mkdir, open, readdir, rename, rm, stat, statf
10
11
  import path from "node:path";
11
12
  import { fileURLToPath } from "node:url";
12
13
 
13
- import { checkStableAudioInstall, readGenerationSettings, readSavedSettings, resolveGenerationSettingsFile, resolveStableAudioManagedRoot, writeGenerationSettings } from "./local-generator.mjs";
14
- import { DEFAULT_STABLE_AUDIO_MODEL, isStableAudioModel, SHARED_WEIGHTS, STABLE_AUDIO_MODELS, STABLE_AUDIO_SOURCES } from "./sources.mjs";
14
+ import { checkStableAudioInstall, createLocalGenerator, readGenerationSettings, readSavedSettings, resolveGenerationSettingsFile, resolveStableAudioManagedRoot, stableAudioPrompt, stableAudioPython, writeGenerationSettings } from "./local-generator.mjs";
15
+ import { DEFAULT_STABLE_AUDIO_MODEL, isStableAudioModel, STABLE_AUDIO_SOURCES, stableAudioRuntime, stableAudioRuntimeModels, stableAudioSources } from "./sources.mjs";
15
16
 
16
17
  const MB = 1024 ** 2;
17
18
  // Room kept free after each step, so a download never fills the disk.
@@ -91,11 +92,18 @@ export function createStableAudioSetup({
91
92
  platform = process.platform,
92
93
  arch = process.arch,
93
94
  now = () => new Date(),
94
- sources = STABLE_AUDIO_SOURCES,
95
+ // The build that runs here, and what it downloads; none where no Stability AI build runs.
96
+ runtime = stableAudioRuntime({ platform, arch, environment }),
97
+ sources = stableAudioSources(runtime, { platform, arch }),
95
98
  freeSpace = async (folder) => { const info = await statfs(folder); return info.bavail * info.bsize; },
96
99
  } = {}) {
97
- const supported = platform === "darwin" && arch === "arm64";
100
+ const supported = Boolean(runtime && sources);
101
+ // Where nothing runs, the status still names the models and their sizes; install refuses.
102
+ if (!supported) sources = STABLE_AUDIO_SOURCES;
103
+ const build = supported ? runtime : "mlx";
104
+ const { models: buildModels, shared, weightsFolder } = stableAudioRuntimeModels(build);
98
105
  const root = resolveStableAudioManagedRoot(environment);
106
+ const uvName = platform === "win32" ? "uv.exe" : "uv";
99
107
  const files = {
100
108
  lock: path.join(root, "setup.lock"),
101
109
  job: path.join(root, "job.json"),
@@ -103,16 +111,22 @@ export function createStableAudioSetup({
103
111
  downloads: path.join(root, "downloads"),
104
112
  uv: path.join(root, "uv"),
105
113
  uvMarker: path.join(root, "uv", ".moondog.json"),
106
- mlx: path.join(root, "mlx"),
107
- codeMarker: path.join(root, "mlx", ".moondog-code.json"),
108
- venv: path.join(root, "mlx", ".venv"),
109
- envMarker: path.join(root, "mlx", ".venv", ".moondog-env.json"),
110
- weights: path.join(root, "mlx", "models", "mlx"),
114
+ // Each build in a folder of its own name: mlx, or tflite for the CPU build.
115
+ build: path.join(root, build),
116
+ codeMarker: path.join(root, build, ".moondog-code.json"),
117
+ venv: path.join(root, build, ".venv"),
118
+ envMarker: path.join(root, build, ".venv", ".moondog-env.json"),
119
+ weights: path.join(root, build, ...weightsFolder),
111
120
  licenses: resolveStableAudioLicenseFile(environment),
112
121
  };
113
- const weightFiles = (model) => [...SHARED_WEIGHTS, ...STABLE_AUDIO_MODELS[model].weights];
122
+ const weightFiles = (model) => [...shared, ...buildModels[model].weights];
114
123
  const weightSize = (name) => sources.weights.files[name].size;
115
- const part = (name) => path.join(files.downloads, `${name}.part`);
124
+ // The CPU build's weights sit in folders; their partial downloads stay side by side.
125
+ const part = (name) => path.join(files.downloads, `${name.replaceAll("/", "--")}.part`);
126
+ // The machine's own tar, which on Windows also opens uv's zip.
127
+ const tar = platform === "win32" ? path.join(environment.SystemRoot ?? environment.SYSTEMROOT ?? "C:\\Windows", "System32", "tar.exe")
128
+ : platform === "darwin" ? "/usr/bin/tar" : "tar";
129
+ const here = platform === "darwin" ? "this Mac" : "this computer";
116
130
  const pythonPins = { python: sources.python.version, packages: [...sources.python.packages] };
117
131
 
118
132
  // The job this process runs, or null.
@@ -123,7 +137,7 @@ export function createStableAudioSetup({
123
137
  let poll = null;
124
138
 
125
139
  const base = () => ({
126
- uv: readJson(files.uvMarker)?.version === sources.uv.version && sizeOf(path.join(files.uv, "uv")) !== null ? "ready" : "absent",
140
+ uv: readJson(files.uvMarker)?.version === sources.uv.version && sizeOf(path.join(files.uv, uvName)) !== null ? "ready" : "absent",
127
141
  code: readJson(files.codeMarker)?.commit === sources.code.commit ? "ready" : "absent",
128
142
  python: JSON.stringify(readJson(files.envMarker)) === JSON.stringify(pythonPins) ? "ready" : "absent",
129
143
  });
@@ -149,11 +163,11 @@ export function createStableAudioSetup({
149
163
  const steps = base();
150
164
  const current = jobView();
151
165
  const baseReady = Object.values(steps).every((state) => state === "ready");
152
- const ownFiles = (model) => STABLE_AUDIO_MODELS[model].weights.some((name) => sizeOf(path.join(files.weights, name)) !== null || sizeOf(part(name)) !== null);
166
+ const ownFiles = (model) => buildModels[model].weights.some((name) => sizeOf(path.join(files.weights, name)) !== null || sizeOf(part(name)) !== null);
153
167
  // A first setup stopped before any model's own weights arrived still left uv, Python, caches or the
154
168
  // shared encoder: the model it was for reads as partial, so its Remove can take them away.
155
- const leftover = !Object.keys(STABLE_AUDIO_MODELS).some(ownFiles) && existsSync(root) ? (current?.model ?? DEFAULT_STABLE_AUDIO_MODEL) : null;
156
- const models = Object.fromEntries(Object.keys(STABLE_AUDIO_MODELS).map((model) => {
169
+ const leftover = !Object.keys(buildModels).some(ownFiles) && existsSync(root) ? (current?.model ?? DEFAULT_STABLE_AUDIO_MODEL) : null;
170
+ const models = Object.fromEntries(Object.keys(buildModels).map((model) => {
157
171
  let bytes = 0;
158
172
  let complete = true;
159
173
  for (const name of weightFiles(model)) {
@@ -170,6 +184,7 @@ export function createStableAudioSetup({
170
184
  return {
171
185
  supported,
172
186
  root,
187
+ runtime,
173
188
  licenses: { accepted: Boolean(agreement?.accepted_at), at: agreement?.accepted_at ?? null, links: sources.licenses.map((license) => ({ ...license })) },
174
189
  job: current,
175
190
  models,
@@ -247,7 +262,7 @@ export function createStableAudioSetup({
247
262
  const free = await freeSpace(root);
248
263
  const needed = bytes + SPACE_MARGIN;
249
264
  if (free < needed) {
250
- throw setupError("setup_disk_full", `There is not enough space on this Mac: ${gigabytes(needed)} is needed and ${gigabytes(free)} is free.`, { needed, free });
265
+ throw setupError("setup_disk_full", `There is not enough space on ${here}: ${gigabytes(needed)} is needed and ${gigabytes(free)} is free.`, { needed, free });
251
266
  }
252
267
  };
253
268
 
@@ -255,7 +270,7 @@ export function createStableAudioSetup({
255
270
  const runCommand = (command, args, { env = environment, code, message }) => new Promise((resolve, reject) => {
256
271
  const { signal } = job.controller;
257
272
  if (signal.aborted) return reject(cancelled());
258
- const child = spawnImpl(command, args, { stdio: ["ignore", "ignore", "pipe"], env });
273
+ const child = spawnImpl(command, args, { stdio: ["ignore", "ignore", "pipe"], env, windowsHide: true });
259
274
  let tail = "";
260
275
  child.stderr?.setEncoding("utf8");
261
276
  child.stderr?.on("data", (chunk) => { tail = (tail + chunk).slice(-4000); });
@@ -371,18 +386,21 @@ export function createStableAudioSetup({
371
386
  };
372
387
 
373
388
  const setUpUv = async () => {
374
- if ((await executable(path.join(files.uv, "uv"))) && readJson(files.uvMarker)?.version === sources.uv.version) return;
389
+ if ((await executable(path.join(files.uv, uvName))) && readJson(files.uvMarker)?.version === sources.uv.version) return;
375
390
  step("uv", sources.uv.size);
376
391
  await ensureSpace(sources.uv.size * 2 + STEP_SPACE.uv);
377
- const archive = await download({ url: sources.uv.url, name: "uv.tar.gz", size: sources.uv.size, sha256: sources.uv.sha256,
378
- target: path.join(files.downloads, "uv.tar.gz"), onBytes: progress });
392
+ const archiveName = sources.uv.url.endsWith(".zip") ? "uv.zip" : "uv.tar.gz";
393
+ const archive = await download({ url: sources.uv.url, name: archiveName, size: sources.uv.size, sha256: sources.uv.sha256,
394
+ target: path.join(files.downloads, archiveName), onBytes: progress });
379
395
  const temporary = `${files.uv}.tmp-${job.token}`;
380
396
  try {
381
397
  await rm(temporary, { recursive: true, force: true });
382
398
  await mkdir(temporary, { recursive: true, mode: 0o700 });
383
- await runCommand("/usr/bin/tar", ["-xzf", archive, "-C", temporary, "--strip-components", "1"],
399
+ // Windows' zip holds uv.exe at its top; the tarballs hold uv in a folder.
400
+ const strip = sources.uv.strip ?? 1;
401
+ await runCommand(tar, [archiveName === "uv.zip" ? "-xf" : "-xzf", archive, "-C", temporary, ...(strip ? ["--strip-components", String(strip)] : [])],
384
402
  { code: "setup_verification_failed", message: "uv could not be unpacked. Try again." });
385
- if (!(await executable(path.join(temporary, "uv")))) throw setupError("setup_verification_failed", "uv was not in its download. Try again.");
403
+ if (!(await executable(path.join(temporary, uvName)))) throw setupError("setup_verification_failed", "uv was not in its download. Try again.");
386
404
  await writeJson(path.join(temporary, ".moondog.json"), { version: sources.uv.version });
387
405
  await rm(files.uv, { recursive: true, force: true });
388
406
  await rename(temporary, files.uv);
@@ -397,25 +415,27 @@ export function createStableAudioSetup({
397
415
  step("code");
398
416
  await ensureSpace(STEP_SPACE.code);
399
417
  const archive = await download({ url: sources.code.url, name: "code.tar.gz", target: path.join(files.downloads, "code.tar.gz"), onBytes: progress });
400
- const temporary = `${files.mlx}.tmp-${job.token}`;
418
+ const temporary = `${files.build}.tmp-${job.token}`;
401
419
  try {
402
420
  await rm(temporary, { recursive: true, force: true });
403
421
  await mkdir(temporary, { recursive: true, mode: 0o700 });
404
422
  step("verifying");
405
423
  const strip = String(sources.code.folder.split("/").length);
406
- await runCommand("/usr/bin/tar", ["-xzf", archive, "-C", temporary, "--strip-components", strip, sources.code.folder],
424
+ await runCommand(tar, ["-xzf", archive, "-C", temporary, "--strip-components", strip, sources.code.folder],
407
425
  { code: "setup_verification_failed", message: "Stable Audio 3's code could not be unpacked. Try again." });
408
426
  await verifyTree(temporary);
409
427
  // Weights and the environment from an earlier install move into the new tree.
410
- for (const kept of [path.join("models", "mlx"), ".venv"]) {
411
- if ((await stat(path.join(files.mlx, kept)).catch(() => null))?.isDirectory()) {
428
+ for (const kept of [path.join(...weightsFolder), ".venv"]) {
429
+ if ((await stat(path.join(files.build, kept)).catch(() => null))?.isDirectory()) {
430
+ // The code's own empty models/tflite folder gives way to the weights already there.
431
+ await rm(path.join(temporary, kept), { recursive: true, force: true });
412
432
  await mkdir(path.dirname(path.join(temporary, kept)), { recursive: true });
413
- await rename(path.join(files.mlx, kept), path.join(temporary, kept));
433
+ await rename(path.join(files.build, kept), path.join(temporary, kept));
414
434
  }
415
435
  }
416
436
  await writeJson(path.join(temporary, ".moondog-code.json"), { commit: sources.code.commit });
417
- await rm(files.mlx, { recursive: true, force: true });
418
- await rename(temporary, files.mlx);
437
+ await rm(files.build, { recursive: true, force: true });
438
+ await rename(temporary, files.build);
419
439
  } finally {
420
440
  await rm(temporary, { recursive: true, force: true });
421
441
  await rm(archive, { force: true });
@@ -423,7 +443,7 @@ export function createStableAudioSetup({
423
443
  };
424
444
 
425
445
  const setUpPython = async () => {
426
- const python = path.join(files.venv, "bin", "python");
446
+ const python = stableAudioPython(files.build, platform);
427
447
  if ((await executable(python)) && JSON.stringify(readJson(files.envMarker)) === JSON.stringify(pythonPins)) return;
428
448
  step("python");
429
449
  await ensureSpace(STEP_SPACE.python);
@@ -432,7 +452,7 @@ export function createStableAudioSetup({
432
452
  const env = Object.fromEntries(Object.entries(environment).filter(([name]) => !/^(UV_|PIP_|VIRTUAL_ENV$|CONDA_|PYTHON)/u.test(name)));
433
453
  Object.assign(env, { UV_CACHE_DIR: path.join(root, "uv-cache"), UV_PYTHON_INSTALL_DIR: path.join(root, "python"),
434
454
  UV_PYTHON_PREFERENCE: "only-managed", UV_NO_CONFIG: "1", UV_NO_PROGRESS: "1" });
435
- const uv = path.join(files.uv, "uv");
455
+ const uv = path.join(files.uv, uvName);
436
456
  const failed = { code: "setup_python_failed", message: "The Python environment could not be set up. Check the connection, then try again." };
437
457
  await runCommand(uv, ["venv", "--clear", "--python", sources.python.version, files.venv], { env, ...failed });
438
458
  await runCommand(uv, ["pip", "install", "--python", python, ...sources.python.packages], { env, ...failed });
@@ -445,7 +465,10 @@ export function createStableAudioSetup({
445
465
  const missing = names.filter((name) => sizeOf(path.join(files.weights, name)) !== weightSize(name));
446
466
  if (!missing.length) return;
447
467
  step("weights", total);
448
- await ensureSpace(missing.reduce((sum, name) => sum + weightSize(name) - Math.min(weightSize(name), sizeOf(part(name)) ?? 0), 0));
468
+ // The CPU build writes a weight cache beside each model file the first time it runs it (.xnnwc), at
469
+ // most about the file's own size, so the room for those caches is kept too.
470
+ const caches = build === "tflite" ? missing.reduce((sum, name) => sum + weightSize(name), 0) : 0;
471
+ await ensureSpace(caches + missing.reduce((sum, name) => sum + weightSize(name) - Math.min(weightSize(name), sizeOf(part(name)) ?? 0), 0));
449
472
  let done = total - missing.reduce((sum, name) => sum + weightSize(name), 0);
450
473
  for (const name of missing) {
451
474
  const { size, sha256 } = sources.weights.files[name];
@@ -457,19 +480,19 @@ export function createStableAudioSetup({
457
480
 
458
481
  const finish = async (model) => {
459
482
  step("verifying");
460
- const install = await checkStableAudioInstall(files.mlx, { model, platform, arch });
483
+ const install = await checkStableAudioInstall(files.build, { model, platform, arch, environment });
461
484
  if (install.state !== "ready") throw setupError("setup_verification_failed", "Stable Audio 3 was set up but is not ready to run. Try again.");
462
485
  // The download was the listener's ask, so this model is turned on, unless a folder they chose
463
486
  // themselves runs now (they can still pick this one with Use) or MOONDOG_SA3_DIR decides.
464
- const settings = await readGenerationSettings(environment);
487
+ const settings = await readGenerationSettings(environment, { platform, arch });
465
488
  if (settings.source === "environment") return;
466
489
  // A choice the listener made while this ran, here or in the other window or terminal, stands.
467
490
  if (JSON.stringify(await readSavedSettings(environment)) !== job.settingsAtStart) return;
468
- const runsNow = async () => (await checkStableAudioInstall(settings.path, { model: settings.model, platform, arch })).state === "ready";
491
+ const runsNow = async () => (await checkStableAudioInstall(settings.path, { model: settings.model, platform, arch, environment })).state === "ready";
469
492
  // A folder they chose, or one turned on that runs (~/Developer included), or a model of Moondog's
470
493
  // own already in use stays in use.
471
494
  if ((settings.source === "settings" || settings.enabled) && (await runsNow())) return;
472
- await writeGenerationSettings({ source: "managed", model, enabled: true }, environment);
495
+ await writeGenerationSettings({ source: "managed", model, enabled: true }, environment, { platform, arch });
473
496
  };
474
497
 
475
498
  const run = async (model, { baseOnly }) => {
@@ -498,7 +521,7 @@ export function createStableAudioSetup({
498
521
  */
499
522
  async install(model, { accepted = false, baseOnly = false } = {}) {
500
523
  if (!isStableAudioModel(model)) throw setupError("setup_model_unknown", "Choose medium or small-music.");
501
- if (!supported) throw setupError("setup_unsupported", "Stable Audio 3 needs a Mac with Apple silicon.");
524
+ if (!supported) throw setupError("setup_unsupported", "Stable Audio 3 needs a Mac with Apple silicon, or Windows or Linux on an x64 computer, or Linux on ARM.");
502
525
  if (job) throw setupError("setup_busy", "Stable Audio 3 is already being set up.");
503
526
  if (!readJson(files.licenses)?.accepted_at) {
504
527
  if (accepted !== true) {
@@ -572,14 +595,16 @@ export function createStableAudioSetup({
572
595
  if (!(await stat(root).catch(() => null))) return status();
573
596
  const token = randomBytes(8).toString("hex");
574
597
  await takeLock(model, token);
575
- const other = Object.keys(STABLE_AUDIO_MODELS).find((name) => name !== model);
598
+ const other = Object.keys(buildModels).find((name) => name !== model);
576
599
  try {
577
- for (const name of STABLE_AUDIO_MODELS[model].weights) {
600
+ for (const name of buildModels[model].weights) {
578
601
  await rm(path.join(files.weights, name), { force: true });
602
+ // The CPU build's weight cache of that file goes with it.
603
+ await rm(path.join(files.weights, `${name}.xnnwc`), { force: true });
579
604
  await rm(part(name), { force: true });
580
605
  }
581
606
  await rm(files.job, { force: true });
582
- const otherLeft = STABLE_AUDIO_MODELS[other].weights.some((name) => sizeOf(path.join(files.weights, name)) !== null || sizeOf(part(name)) !== null);
607
+ const otherLeft = buildModels[other].weights.some((name) => sizeOf(path.join(files.weights, name)) !== null || sizeOf(part(name)) !== null);
583
608
  if (!otherLeft) await rm(root, { recursive: true, force: true });
584
609
  } finally {
585
610
  await releaseLock(token);
@@ -588,14 +613,14 @@ export function createStableAudioSetup({
588
613
  // model that folder has, so a working own install is never checked for weights it never had.
589
614
  const settings = await readGenerationSettings({ ...environment, MOONDOG_SA3_DIR: "" }, { platform, arch });
590
615
  if (settings.source === "managed" && settings.model === model) {
591
- if (status().models[other].state === "ready") await writeGenerationSettings({ model: other }, environment);
616
+ if (status().models[other].state === "ready") await writeGenerationSettings({ model: other }, environment, { platform, arch });
592
617
  else {
593
- const candidates = [DEFAULT_STABLE_AUDIO_MODEL, ...Object.keys(STABLE_AUDIO_MODELS).filter((name) => name !== DEFAULT_STABLE_AUDIO_MODEL)];
618
+ const candidates = [DEFAULT_STABLE_AUDIO_MODEL, ...Object.keys(buildModels).filter((name) => name !== DEFAULT_STABLE_AUDIO_MODEL)];
594
619
  let found = DEFAULT_STABLE_AUDIO_MODEL;
595
620
  for (const name of candidates) {
596
- if ((await checkStableAudioInstall(settings.folder, { model: name, platform, arch })).state === "ready") { found = name; break; }
621
+ if ((await checkStableAudioInstall(settings.folder, { model: name, platform, arch, environment })).state === "ready") { found = name; break; }
597
622
  }
598
- await writeGenerationSettings({ source: "settings", model: found }, environment);
623
+ await writeGenerationSettings({ source: "settings", model: found }, environment, { platform, arch });
599
624
  }
600
625
  }
601
626
  push();
@@ -622,10 +647,30 @@ export function createStableAudioSetup({
622
647
 
623
648
  // A developer's way to try the real downloads from a terminal, into the state folder
624
649
  // MOONDOG_STATE_HOME names: node src/integrations/stable-audio/setup.mjs status | install
625
- // medium|small-music [--agree] [--base-only] | remove medium|small-music. --base-only stops before
626
- // the weights, so uv, the code and Python can be tried without gigabytes.
650
+ // medium|small-music [--agree] [--base-only] | use medium|small-music | remove medium|small-music | make [seconds]. --base-only
651
+ // stops before the weights, so uv, the code and Python can be tried without gigabytes; make makes one
652
+ // track with the install music making uses, as a listener's request would, and prints what it measured.
653
+ // MOONDOG_SA3_RUNTIME=tflite tries the CPU build on a Mac with Apple silicon.
627
654
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
628
655
  const [command = "status", model, ...flags] = process.argv.slice(2);
656
+ if (command === "make") {
657
+ const generator = createLocalGenerator();
658
+ const status = await generator.check();
659
+ const seconds = Number(model ?? 30);
660
+ console.log(`${status.runtime ?? "no runtime"} | ${status.model} | ${status.state}`);
661
+ try {
662
+ const made = await generator.generate({ prompt: stableAudioPrompt({ descriptors: [
663
+ { facet: "genre", term: "ambient" }, { facet: "instrument", term: "rhodes piano" }, { facet: "texture", term: "warm tape" }, { facet: "mood", term: "unhurried" },
664
+ ], bpm: 84 }), seconds, title: "Setup check" }, { onProgress: ({ stage }) => console.log(`stage ${stage}`) });
665
+ const receipt = await generator.receipt(made.id);
666
+ console.log(JSON.stringify({ id: made.id, seconds: made.seconds, duration_seconds: made.duration_seconds, elapsed_ms: made.elapsed_ms,
667
+ measured: made.measured ?? null, generator: receipt?.generator, audio: receipt?.audio && { ...receipt.audio, loudness: undefined } }, null, 2));
668
+ } catch (error) {
669
+ console.error(`${error.code ?? "error"}: ${error.message}`);
670
+ process.exitCode = 1;
671
+ }
672
+ process.exit();
673
+ }
629
674
  const setup = createStableAudioSetup();
630
675
  const line = (snapshot) => {
631
676
  const { job } = snapshot;
@@ -643,6 +688,10 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
643
688
  process.exitCode = end.job?.error ? 1 : 0;
644
689
  } else if (command === "remove") {
645
690
  console.log(line(await setup.remove(model)));
691
+ } else if (command === "use") {
692
+ // As /generation use does: music making turns on with this model of Moondog's own install.
693
+ if (!isStableAudioModel(model) || setup.status().models[model].state !== "ready") throw setupError("setup_model_unknown", `${model} isn't downloaded.`);
694
+ console.log(JSON.stringify(await writeGenerationSettings({ enabled: true, source: "managed", model })));
646
695
  } else {
647
696
  console.log(JSON.stringify(setup.status(), null, 2));
648
697
  }
@@ -1,6 +1,10 @@
1
1
  // The official sources Moondog's one-click setup downloads Stable Audio 3 from, each pinned to
2
- // the release, commit or snapshot tested with Moondog on Apple silicon, and the files every
3
- // download is verified against. Nothing here is fetched until the listener asks for a model.
2
+ // the release, commit or snapshot tested with Moondog, and the files every download is verified
3
+ // against. Nothing here is fetched until the listener asks for a model.
4
+ //
5
+ // Two of Stability AI's runtimes make the music. MLX runs on the GPU of a Mac with Apple silicon.
6
+ // The LiteRT build ("tflite") runs on the CPU of Windows and Linux, x64, and of Linux on ARM; it
7
+ // is slower, and on a laptop CPU the small model makes music faster than it plays.
4
8
 
5
9
  // The models a listener can choose, with the flags sa3_mlx.py takes and the weights text to music
6
10
  // loads. The codec encoder is only for --init-audio, so it is never downloaded.
@@ -13,6 +17,37 @@ export const DEFAULT_STABLE_AUDIO_MODEL = "medium";
13
17
  export const SHARED_WEIGHTS = Object.freeze(["t5gemma_f16.npz"]);
14
18
  export const isStableAudioModel = (value) => typeof value === "string" && Object.hasOwn(STABLE_AUDIO_MODELS, value);
15
19
 
20
+ // The same two models in the CPU build, with the flags sa3_tflite.py takes and the weights under its
21
+ // models/tflite folder, at Stability's own defaults: int8 (w8a8) models and the small SAME-S decoder,
22
+ // which decodes Medium too and is about seven times faster than SAME-L on a CPU. The small models stop
23
+ // at two minutes.
24
+ export const STABLE_AUDIO_TFLITE_MODELS = Object.freeze({
25
+ medium: Object.freeze({ dit: "medium", decoder: "same-s", precision: "w8a8", receipt: "sa3-medium-ARC", maxSeconds: 380, weights: Object.freeze(["sa3-m/dit_w8a8.tflite"]) }),
26
+ "small-music": Object.freeze({ dit: "sm-music", decoder: "same-s", precision: "w8a8", receipt: "sa3-sm-music-ARC", maxSeconds: 120, weights: Object.freeze(["sa3-sm-music/dit_w8a8.tflite"]) }),
27
+ });
28
+ // The text encoder and the decoder both models use.
29
+ export const TFLITE_SHARED_WEIGHTS = Object.freeze(["t5gemma/encoder_fp16.tflite", "same-s/dec_w8a8.tflite"]);
30
+
31
+ /**
32
+ * The runtime that makes music on this machine: "mlx" on a Mac with Apple silicon, "tflite" on the CPU of
33
+ * Windows and Linux (x64) and Linux on ARM, or null where no Stability AI build runs (an Intel Mac).
34
+ * MOONDOG_SA3_RUNTIME=tflite tries the CPU build on an Apple silicon Mac, for development.
35
+ */
36
+ export function stableAudioRuntime({ platform = process.platform, arch = process.arch, environment = process.env } = {}) {
37
+ if (platform === "darwin" && arch === "arm64") return environment?.MOONDOG_SA3_RUNTIME === "tflite" ? "tflite" : "mlx";
38
+ return ["win32-x64", "linux-x64", "linux-arm64"].includes(`${platform}-${arch}`) ? "tflite" : null;
39
+ }
40
+
41
+ /** A runtime's models, the weights all of them share, and the folder its weights sit in. */
42
+ export function stableAudioRuntimeModels(runtime) {
43
+ return runtime === "tflite"
44
+ ? { models: STABLE_AUDIO_TFLITE_MODELS, shared: TFLITE_SHARED_WEIGHTS, weightsFolder: ["models", "tflite"], script: "sa3_tflite.py" }
45
+ : { models: STABLE_AUDIO_MODELS, shared: SHARED_WEIGHTS, weightsFolder: ["models", "mlx"], script: "sa3_mlx.py" };
46
+ }
47
+
48
+ /** The longest track a model makes, in seconds, on a runtime. */
49
+ export const stableAudioMaxSeconds = (runtime, model) => stableAudioRuntimeModels(runtime).models[model]?.maxSeconds ?? 380;
50
+
16
51
  const HF_SNAPSHOT = "08b17423649b5714b22eab20f96bf00751f2358a";
17
52
  const CODE_COMMIT = "77e0398c26f7d22d801ec1bb036307e8b231f741";
18
53
 
@@ -104,3 +139,117 @@ export const STABLE_AUDIO_SOURCES = Object.freeze({
104
139
  Object.freeze({ id: "gemma-terms", name: "Gemma Terms of Use", url: "https://huggingface.co/stabilityai/stable-audio-3-optimized/blob/main/LICENSE_GEMMA.md" }),
105
140
  ]),
106
141
  });
142
+
143
+ // uv for each machine the CPU build runs on (the Mac's is above). Windows' zip holds uv.exe at its top.
144
+ const UV_RELEASE = "https://github.com/astral-sh/uv/releases/download/0.9.7";
145
+ const UV_BUILDS = Object.freeze({
146
+ "darwin-arm64": STABLE_AUDIO_SOURCES.uv,
147
+ "win32-x64": Object.freeze({ version: "0.9.7", url: `${UV_RELEASE}/uv-x86_64-pc-windows-msvc.zip`, size: 20_800_451,
148
+ sha256: "5d250c32d3604e28dbe18dc65c668ff628c53e00dde2c642576e831e4a60da64", strip: 0 }),
149
+ "linux-x64": Object.freeze({ version: "0.9.7", url: `${UV_RELEASE}/uv-x86_64-unknown-linux-gnu.tar.gz`, size: 21_420_448,
150
+ sha256: "b26fcc8dfa1c39b5a5613445af3be3eefda45d9a39359bee271eafe34913583e" }),
151
+ "linux-arm64": Object.freeze({ version: "0.9.7", url: `${UV_RELEASE}/uv-aarch64-unknown-linux-gnu.tar.gz`, size: 20_300_539,
152
+ sha256: "8b3d31a154673c6d357727d2083a33525b515589d153fa5b5455e1db9e9e6363" }),
153
+ });
154
+
155
+ const TFLITE_HF_SNAPSHOT = "30cb2644da54bfa63275d1bc7f1fa67fc718680f";
156
+ const TFLITE_CODE_COMMIT = "790793b89ddceea612be9ce42ff6830d18f6fa57";
157
+
158
+ // Stability AI's CPU build (MIT), from the newest commit, which carries its fixes to the SAME-S codec, with
159
+ // the weights of the Hugging Face snapshot those fixes shipped in. The manifest lists the files as GitHub's
160
+ // tarball holds them: its .bat files have Windows line endings.
161
+ export const STABLE_AUDIO_TFLITE_SOURCES = Object.freeze({
162
+ code: Object.freeze({
163
+ commit: TFLITE_CODE_COMMIT,
164
+ url: `https://codeload.github.com/Stability-AI/stable-audio-3/tar.gz/${TFLITE_CODE_COMMIT}`,
165
+ folder: `stable-audio-3-${TFLITE_CODE_COMMIT}/optimized/tflite`,
166
+ files: Object.freeze([
167
+ [".gitattributes", 106, "913830f0563a4c672c0a3ffb1d2213dfdca8b0b29979d6fb84dab111f824d5e5"],
168
+ [".gitignore", 562, "b50b199fa864581a0710277c7112f7734754f05cb32b63da6a27fd403a6aeac7"],
169
+ ["README.md", 27139, "a5cde8d37f43d48f636d97717677becc4b0262c6f96acacaeaa989756af60a90"],
170
+ ["bootstrap.ps1", 4310, "86199f02ebaf733c4cdd98787831bd2d1151fa4457b910d688b359dc765f0b93"],
171
+ ["bootstrap.sh", 8106, "5b7657b5ae1adbcdcb29354dce86c6a4b977af0e74d7d7c92ea910a79ecb30c3"],
172
+ ["build/README.md", 7061, "e9ab249dd0782f516562957caa58eddfb7af2b84838dae4a82ca974a0d527504"],
173
+ ["build/build_all.sh", 5100, "dad6694252787f34f258f3e564248fc948bef8fc310f7370a62e28d06fd20c9d"],
174
+ ["build/build_dit.sh", 4203, "f42786117d142369037951c5c9bf65fe6bdcbd61f6eacb3c641d36be9ed60fde"],
175
+ ["build/build_dit_small.sh", 4294, "0a4e2138a2e4119c7a54f93a34d8e66c39fd2e225bc3468d4bff48600881319d"],
176
+ ["build/build_paths.py", 1632, "5efcac6efb816c4b680fe8be7650b8030329a916ede91af87eb1dc47678402d3"],
177
+ ["build/enc_rht.py", 4707, "48525621d547c47c8de30ff0c1e9d02bd552dd8e74875222d37432a8e1e56383"],
178
+ ["build/export/export_dit.py", 20548, "a1c7e12746a534114602a48eda4d39ac379c9dd609daeaab443a88e7f890e2cf"],
179
+ ["build/export/export_enc_windowed.py", 1435, "7f2653560c8dd66112a7b92659d18a586f20b25449292d5c43d390bbbed74557"],
180
+ ["build/export/export_same_s_fixed.py", 1837, "2b67d29a339f8d15fe9721364e049856a25dbb30f1cfc1bb61e328d8aea75d6a"],
181
+ ["build/export/export_windowed_param.py", 1645, "e0103a2b54fa196c17d2a2c3e902c452903cffc937dbfb5c3fa926e3beeb2579"],
182
+ ["build/extract/extract_same_l_decoder_weights.py", 2986, "9c886a9d9c153b89cf55fc0c403ab83f6d6c7bf2171c1a60a626346073f85128"],
183
+ ["build/extract/extract_same_l_encoder_weights.py", 3207, "59a537bd8c24c47b078e697fa9613fa295e0f6afa4beb4a6b8f1aa015c08f3f6"],
184
+ ["build/extract/extract_same_s_decoder_weights.py", 2719, "ed8de0d3c7219421a160fbd76444dfd687a4658c0cb7b07bcab8350f58801eaf"],
185
+ ["build/extract/extract_same_s_encoder_weights.py", 2852, "f595f5557a2162e31452ec523d8bb946e64216aa6a14af871884b081b2d07658"],
186
+ ["build/quant_merge/merge_rungs_generic.py", 6804, "449e20200a436503950e0a6850339f7dbb9409199c3634702962f33c4345ac8c"],
187
+ ["build/quant_merge/quant_one.py", 3163, "ff96622ada544925e181cf6fa60a5ed537a5b25806082f5c0e62189be923dd47"],
188
+ ["build/tfl_surgery.py", 6301, "05305cf439b2f8d6154fc8cd4d306642738e2da569214e826ada436896ac44fa"],
189
+ ["build/torch_defs/limiter.py", 3873, "52659fba64944be7bea52edf025fbd628d94e1630757f10797fc710f2c58996a"],
190
+ ["build/torch_defs/same_l_decoder_torch.py", 11021, "f929cabc57137ff0f141280413296002355df8810004f2d65b698e8b8e61f9c4"],
191
+ ["build/torch_defs/same_l_encoder_torch.py", 7483, "a5103af23083d825185f2e49a433d05a6210a4f0f2cd9d85f5d25b148aa5d9ee"],
192
+ ["build/torch_defs/same_s_decoder_torch.py", 18086, "25f2920d297877aa41fae727ea9bf7e9462bc06e7beeff011e69771deb11b192"],
193
+ ["build/torch_defs/same_s_encoder_torch.py", 5371, "b21d8ccbfe50ba83d119ca2c640f64a01217e21b6f067de72b01a8ba4caae727"],
194
+ ["build/torch_defs/windowed_decoder.py", 3268, "3257219ac18e4e38631e4ba66c4dec51d5ca5a76af11224cbb9d51e0bf446f42"],
195
+ ["build/verify_final.py", 2836, "2e779fb94295b9299328dc52a98e080ea775fb053cf496e58a013f3db1ef5e0f"],
196
+ ["docs/RUNGS.md", 6376, "c4bd7aed3352f926738646924f9edcfc55628cace8a5e006d58c5af53788f321"],
197
+ ["docs/img/dit-ram-rung-vs-varlen-small.png", 84406, "4eea47638de62b87f1d8a32e60eb7a6bde94a1ff6a960001963cb00116f600ae"],
198
+ ["docs/img/dit-ram-rung-vs-varlen.png", 72229, "6b57d719628a2e64119b95abe3e2a36f2179aef309c5b96ca9fcd5079827dc7a"],
199
+ ["install.bat", 1633, "35c16ffc134aba8264be39e8a9699d85a12e12431e9b5ea32a87009b18a7644c"],
200
+ ["install.sh", 6085, "436409b5702f80767a554a033e55a30b26b3c44e0d3440d33004b183bb3573b1"],
201
+ ["models/__init__.py", 0, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
202
+ ["models/defs/__init__.py", 0, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
203
+ ["models/defs/tflite_pipeline.py", 7053, "229f34424d8ace818e416a8a3e50b92b859a074af44f4d5ed29eddc845b30e64"],
204
+ ["models/tflite/.gitkeep", 0, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
205
+ ["models/tokenizer.model", 4241003, "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2"],
206
+ ["output/.gitkeep", 0, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
207
+ ["requirements-gradio.txt", 170, "f1f4a2b95c58fc80b7881e7ee9bee98f9e565f2be58ccee63d53d5e4a8ccb896"],
208
+ ["requirements.txt", 150, "4f0a6bdfde92238996b6bd09bc067d3ae777dced99872ce16fe26b028aa85244"],
209
+ ["sa3", 3144, "aac881529e5e253803c59b334c5af466ed2242c92c3d4a6ba2429c3dda134792"],
210
+ ["sa3-gradio", 1267, "91a3a7f9304e969be2c40bf3d6c9740fbf1a0523b9367750afe6d8de0b010f8d"],
211
+ ["sa3.bat", 808, "a02fb71cf35402d38d6f1b26e77b72071e886b1cdd33f0341a4e7e6d69471710"],
212
+ ["sa3.ps1", 540, "37e76880dee628520234f801becf23892439c2d94a91d85caceda3610db5c010"],
213
+ ["scripts/examples.py", 7696, "9a8d376357b3fcf5c79c38f43bbf5e565999f09c8b08bccd4b7d3a2979b6479d"],
214
+ ["scripts/install.py", 6495, "86a2421ed034d4aa21e16e291741ae5cabd200fb84512f0706c7b94604c40fad"],
215
+ ["scripts/lora_core.py", 13769, "7c27fbb6231517cd16c87cb07ba9ae3f1cbc6838e47093a840894380bcb88104"],
216
+ ["scripts/lora_patch.py", 18363, "e302943921a7fa84681a96df68e4930ecd62477018c029aee03e1f7698ab688c"],
217
+ ["scripts/rung_decoder.py", 6512, "c2e82c53e3189e0fc3a1f948c19d84b5016e90e9eddac6e27c9e2daa20c612e7"],
218
+ ["scripts/rung_dit.py", 12790, "229531d9a6298094427def0aa2715814c0324ba0bde819cd77f7f8797168f061"],
219
+ ["scripts/rung_encoder.py", 5561, "cbfa3ca9693f67fa3216f5d8143db82e7b963d54eeac0e99b2ebfb1d8570419a"],
220
+ ["scripts/sa3_gradio.py", 67687, "ce7dcde67e1092a1ae1db0a270a4d3258169e6099cd2cf7e4d904bcd909434c8"],
221
+ ["scripts/sa3_tflite.py", 49542, "6e7a993346d17740d6a43c9d9a061b0bc30ad37eed4a191e5fe16fdcdeb8b0e7"],
222
+ ["scripts/spec.py", 6574, "3e85ee7850a4e3861733823c1c712a123550c48c1cbd47cbb0e0baea2f31b42d"],
223
+ ["scripts/test_lora_patch.py", 14194, "f36de7afd8a19f7b48db5f1f5526c4b729d6dff294d7ed9ce7d5bb965204ac40"],
224
+ ["scripts/test_windows_compat.py", 8345, "fc21b66730650ea476f26e61688e17aeaeff8ea293a9c5a3ffcc83a6820b7495"],
225
+ ["scripts/weights.py", 12618, "24c783e2fc06aa34285120ad98eebd9ccb2ecce9f39ca776ca55eb028c772e33"],
226
+ ]),
227
+ }),
228
+ // LiteRT and what it needs, the same pins on every machine (colorama only matters on Windows). The
229
+ // script imports Hugging Face's client only to download a missing file, which Moondog never asks of it.
230
+ python: Object.freeze({
231
+ version: "3.11.14",
232
+ packages: Object.freeze([
233
+ "ai-edge-litert==2.3.0", "backports-strenum==1.3.1", "cffi==2.1.1", "colorama==0.4.6", "flatbuffers==25.12.19",
234
+ "ml-dtypes==0.6.0", "numpy==2.4.6", "protobuf==7.36.2", "pycparser==3.12", "sentencepiece==0.2.3", "soundfile==0.14.0",
235
+ "tqdm==4.70.1", "typing-extensions==4.16.0",
236
+ ]),
237
+ }),
238
+ weights: Object.freeze({
239
+ url: (name) => `https://huggingface.co/stabilityai/stable-audio-3-optimized/resolve/${TFLITE_HF_SNAPSHOT}/tflite/${name}`,
240
+ files: Object.freeze({
241
+ "t5gemma/encoder_fp16.tflite": Object.freeze({ size: 563_818_608, sha256: "8530d0b3e6b9b9dcf1239145c2a853fb749708eaddbb472ff8f0802b50059372" }),
242
+ "same-s/dec_w8a8.tflite": Object.freeze({ size: 94_092_016, sha256: "2fc31cdc42a54342233fb8c6da636565b1191d97002665e21812e981490434a6" }),
243
+ "sa3-m/dit_w8a8.tflite": Object.freeze({ size: 1_667_708_664, sha256: "e60ea3a8b530de93ee7f1fd7b4426597006dbcde7bce45750d39c439f4ef9602" }),
244
+ "sa3-sm-music/dit_w8a8.tflite": Object.freeze({ size: 539_350_360, sha256: "1d8ef99bf10f51cc52b68f7b527d3773828e700758b253edd8a8e088a906e241" }),
245
+ }),
246
+ }),
247
+ licenses: STABLE_AUDIO_SOURCES.licenses,
248
+ });
249
+
250
+ /** What the setup downloads for a runtime on this machine, uv included; null where nothing runs. */
251
+ export function stableAudioSources(runtime, { platform = process.platform, arch = process.arch } = {}) {
252
+ const uv = UV_BUILDS[`${platform}-${arch}`];
253
+ if (!uv || !runtime) return null;
254
+ return runtime === "tflite" ? Object.freeze({ ...STABLE_AUDIO_TFLITE_SOURCES, uv }) : STABLE_AUDIO_SOURCES;
255
+ }