Split any YouTube song into stems
TypeScript
feat: prefetch vocals engine (setup + background), resumable downloads
Daniel Ravina0b1d8b5f642e
diff --git a/README.md b/README.mdindex 120baa4..c822dd4 100644--- a/README.md+++ b/README.md@@ -29,7 +29,7 @@ Grab installers from [Releases](https://github.com/danielravina/stemkit/releases- **macOS** (Apple Silicon): `StemKit-x.y.z-mac-arm64.dmg`- **Windows**: `StemKit-Setup-x.y.z.exe` (installer) or portable `.zip`-First launch creates a private Python environment and downloads the separation engine (~2 GB, one time) plus model weights (~80 MB). The first split also downloads the neural vocals engine (~913 MB, one time). ffmpeg is bundled — nothing else to install.+First launch creates a private Python environment and downloads the separation engine (~2 GB) plus the neural vocals engine (~913 MB) — one time, up front. ffmpeg is bundled — nothing else to install.> **macOS first launch**: builds are signed with a Developer ID but not notarized, so macOS may say it "cannot verify the developer". One-time fix: **System Settings → Privacy & Security → Open Anyway** (or `xattr -cr /Applications/StemKit.app`).>diff --git a/src/main/env.ts b/src/main/env.tsindex 974292f..dc34a7d 100644--- a/src/main/env.ts+++ b/src/main/env.ts@@ -1,5 +1,5 @@import { spawn, execFile } from 'child_process'-import { existsSync, writeFileSync, readdirSync, createWriteStream, mkdirSync, chmodSync, unlinkSync } from 'fs'+import { existsSync, writeFileSync, readdirSync, createWriteStream, mkdirSync, chmodSync, unlinkSync, statSync, renameSync } from 'fs'import { homedir } from 'os'import { join } from 'path'import { app, BrowserWindow, net } from 'electron'@@ -115,6 +115,8 @@ let gpuProbe: Promise<boolean> | null = null(MPS on Apple Silicon, CUDA on NVIDIA). CPU-only machines stay onthe demucs engine, which is much faster without GPU acceleration */export function hasGpuAcceleration(): Promise<boolean> {+ // test hook: simulates a CPU-only machine (the Windows path)+ if (process.env.STEMKIT_FORCE_CPU === '1') return Promise.resolve(false)if (!gpuProbe) {gpuProbe = runCapture(venvPython(),@@ -381,30 +383,67 @@ export async function refreshReady(): Promise<boolean> {return state.ready}-function downloadTo(url: string, dest: string, label: string): Promise<void> {+function downloadTo(+ url: string,+ dest: string,+ label: string,+ onProgress?: (pct: number) => void+): Promise<void> {return new Promise((resolve, reject) => {+ // download into <dest>.part so an interrupted fetch can resume and a+ // partial file is never mistaken for the real one; rename on success+ const part = dest + '.part'+ const base = existsSync(part) ? statSync(part).size : 0let lastPct = -1- const req = net.request({ url, redirect: 'follow' })+ let lastFine = -1+ const req = net.request({+ url,+ redirect: 'follow',+ ...(base > 0 ? { headers: { Range: `bytes=${base}-` } } : {})+ })req.on('response', (res) => {- if (res.statusCode !== 200) {+ if (res.statusCode === 416 && base > 0) {+ // the .part already holds the whole file (killed right before the rename)+ renameSync(part, dest)+ onProgress?.(100)+ resolve()+ return+ }+ if (res.statusCode !== 200 && res.statusCode !== 206) {reject(new Error(`${label} download failed (HTTP ${res.statusCode})`))return}- const total = Number(res.headers['content-length'] ?? 0)- const out = createWriteStream(dest)+ const resumed = res.statusCode === 206 && base > 0+ const start = resumed ? base : 0+ const total = start + Number(res.headers['content-length'] ?? 0)+ const out = createWriteStream(part, { flags: resumed ? 'append' : 'w' })let done = 0res.on('data', (chunk: Buffer) => {done += chunk.lengthout.write(chunk)if (total > 0) {- const pct = Math.floor((done / total) * 100)+ const pct = Math.floor(((start + done) / total) * 100)if (pct >= lastPct + 10) {lastPct = pctsendEnvEvent(`${label}: ${pct}%`)}+ if (onProgress && pct > lastFine) {+ lastFine = pct+ onProgress(pct)+ }}})- res.on('end', () => out.end(() => resolve()))+ res.on('end', () =>+ out.end(() => {+ try {+ renameSync(part, dest)+ onProgress?.(100)+ resolve()+ } catch (e) {+ reject(e instanceof Error ? e : new Error(String(e)))+ }+ })+ )res.on('error', (e) => {out.close()reject(e instanceof Error ? e : new Error(String(e)))@@ -415,6 +454,59 @@ function downloadTo(url: string, dest: string, label: string): Promise<void> {})}+/* Mel-band roformer vocals checkpoint. Fetched once per machine: during+ setup for new installs, in the background for existing ones, and awaited+ by the pipeline so a split never races the download. Non-fatal — the lazy+ download inside roformer.py stays as the fallback */+const CKPT_NAME = 'MelBandRoformer.ckpt'+const CKPT_URL =+ 'https://huggingface.co/KimberleyJSN/melbandroformer/resolve/main/MelBandRoformer.ckpt'++export function vocalsEnginePath(): string {+ return join(modelsDir(), CKPT_NAME)+}++let vocalsEnginePromise: Promise<boolean> | null = null+const vocalsProgressListeners = new Set<(pct: number) => void>()++export function ensureVocalsEngine(onProgress?: (pct: number) => void): Promise<boolean> {+ if (onProgress) vocalsProgressListeners.add(onProgress)+ const detach = (): boolean => {+ if (onProgress) vocalsProgressListeners.delete(onProgress)+ return true+ }+ if (existsSync(vocalsEnginePath())) {+ detach()+ return Promise.resolve(true)+ }+ if (!vocalsEnginePromise) {+ vocalsEnginePromise = (async () => {+ if (!(await hasGpuAcceleration())) {+ sendEnvEvent('No GPU acceleration — skipping the vocals engine download')+ return false+ }+ mkdirSync(modelsDir(), { recursive: true })+ sendEnvEvent('Downloading the vocals engine (~913MB, one time)')+ await downloadTo(CKPT_URL, vocalsEnginePath(), 'vocals engine', (pct) => {+ for (const listener of vocalsProgressListeners) listener(pct)+ })+ sendEnvEvent('Vocals engine ready', 'success')+ return true+ })()+ .catch((err) => {+ sendEnvEvent(+ `Vocals engine download failed: ${err instanceof Error ? err.message : String(err)} — it will download before the first split`,+ 'error'+ )+ return false+ })+ .finally(() => {+ vocalsEnginePromise = null+ })+ }+ return vocalsEnginePromise.then(detach)+}+function extractArchive(archive: string, dest: string): Promise<void> {return new Promise((resolve, reject) => {mkdirSync(dest, { recursive: true })@@ -563,6 +655,9 @@ export async function bootstrap(): Promise<boolean> {writeFileSync(join(venv, '.ready'), JSON.stringify({ createdAt: Date.now() }))await refreshReady()sendEnvEvent('Engine ready', 'success')+ // one consolidated wait for new installs: grab the vocals engine now so+ // the first split starts instantly (never blocks setup on failure)+ await ensureVocalsEngine().catch(() => false)return true} catch (err) {sendEnvEvent(err instanceof Error ? err.message : String(err), 'error')diff --git a/src/main/index.ts b/src/main/index.tsindex 9af49cb..673ea41 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -8,6 +8,7 @@ import {bootstrap,updateYtDlp,refreshReady,+ ensureVocalsEngine,getStatus} from './env'import { loadSongs, removeSong, stemBuffers, stemsDir, stemsFor, mixWavPath } from './library'@@ -102,7 +103,10 @@ async function createWindow(): Promise<void> {}app.whenReady().then(async () => {- await refreshReady()+ // existing install (e.g. right after an update): pre-fetch the vocals+ // engine in the background so the first split doesn't stall on a 913MB+ // download. Fresh installs get it during setup instead+ if (await refreshReady()) void ensureVocalsEngine()ipcMain.handle('env:status', async () => {await detectTools()diff --git a/src/main/pipeline.ts b/src/main/pipeline.tsindex b1df535..62c2617 100644--- a/src/main/pipeline.ts+++ b/src/main/pipeline.ts@@ -10,6 +10,7 @@ import {roformerScript,modelsDir,ensureEngineDeps,+ ensureVocalsEngine,hasGpuAcceleration,getStatus,ytDlpRuntimeArgs@@ -266,11 +267,24 @@ export async function startJob(// the demucs phase takes roughly twice as long as the vocals pass,// so the bar reflects that splitconst roformerSpan = otherStems.length > 0 ? 35 : 100+ // the first slice of the vocals phase is the engine download, when+ // one is needed; awaiting it here means roformer.py never races+ // the background fetch on the same checkpoint file+ const downloadSpan = Math.round(roformerSpan * 0.3)if (wantsVocals) {if (!(await ensureEngineDeps())) {bail('Could not prepare the engine components for vocal separation')}- progress(job, 'separate', 0, 'Separating vocals (first run downloads a 913MB engine)')+ await ensureVocalsEngine((pct) =>+ progress(+ job,+ 'separate',+ Math.round((pct / 100) * downloadSpan),+ `Downloading vocals engine (913MB): ${pct}%`+ )+ )+ const vocalsBase = downloadSpan+ progress(job, 'separate', vocalsBase, 'Separating vocals')await runProcess(job,venvPython(),@@ -285,9 +299,12 @@ export async function startJob('--device','auto'],- lineParsers((pct, msg) =>- msg ? pct : Math.round((pct / 100) * roformerSpan)- )+ lineParsers((pct, msg) => {+ if (!msg) return vocalsBase + Math.round((pct / 100) * (roformerSpan - vocalsBase))+ // fallback path: roformer.py downloading the engine itself+ const m = msg.match(/(\d+)%/)+ return m ? Math.round((Number(m[1]) / 100) * downloadSpan) : pct+ }))}if (otherStems.length > 0) {