Split any YouTube song into stems
TypeScript
feat: quality settings (vocals engine, fine-tuned demucs, extra pass)
Daniel Ravinad3e784354f3c
diff --git a/README.md b/README.mdindex c822dd4..9b63084 100644--- a/README.md+++ b/README.md@@ -29,7 +29,12 @@ 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) plus the neural vocals engine (~913 MB) — one time, up front. ffmpeg is bundled — nothing else to install.+First launch creates a private Python environment and downloads the separation engine (~2 GB) — one time. ffmpeg is bundled — nothing else to install.++Optional quality upgrades live behind a gear icon in the app (Settings), each with its own one-time download:+- **Studio-quality vocals** (Mel-Band Roformer): +913 MB — runs on GPU or CPU (CPU is slower)+- **Fine-tuned demucs** (htdemucs_ft): +~320 MB, up to 4× slower+- **Refinement passes**: 2 shifts instead of 1, up to 3× slower> **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/python/separate.py b/python/separate.pyindex b0e2813..b0d655e 100644--- a/python/separate.py+++ b/python/separate.py@@ -73,10 +73,18 @@ def main():is_module = not hasattr(raw_tqdm, "update")real_tqdm = raw_tqdm.tqdm if is_module else raw_tqdm+ # demucs runs one tqdm per "leg" (bag model x shift), each sweeping 0-100+ # on its own. The UI expects a single monotonic sweep for the whole call,+ # so legs are counted globally: pct = (legs_done + leg_frac) / legs.+ # legs_total is filled in once the model is loaded (the patch installs+ # before that point)+ leg_state = {"done": 0, "total": 0, "last": -1.0, "legs": 0}+class ProgressTqdm(real_tqdm):def __init__(self, *a, **kw):super().__init__(*a, **kw)- self._last = 0.0+ if self.total:+ leg_state["total"] = self.totaldef update(self, n=1):super().update(n)@@ -84,17 +92,25 @@ def main():def close(self):self._report(True)+ if self.total and self.n >= self.total:+ leg_state["done"] += 1super().close()def _report(self, force):- total = self.total or 0+ legs = leg_state["legs"]+ if not legs:+ return+ total = leg_state["total"] or self.total or 0if not total:returnfrac = min(1.0, max(0.0, self.n / total))now = time.time()- if force or now - self._last >= 0.5:- emit(type="progress", stage="separate", pct=int(frac * 100))- self._last = now+ if force or now - leg_state["last"] >= 0.5:+ global_pct = int(+ ((leg_state["done"] + frac) / legs) * 100+ )+ emit(type="progress", stage="separate", pct=min(99, global_pct))+ leg_state["last"] = nowdapply.tqdm = types.SimpleNamespace(tqdm=ProgressTqdm) if is_module else ProgressTqdm@@ -113,6 +129,7 @@ def main():fail(f"model load failed: {e}")model.to(device)model.eval()+ leg_state["legs"] = max(1, len(getattr(model, "models", [1]))) * max(1, args.shifts)audio, sr = load_wav(args.input)target_sr = model.sampleratediff --git a/src/main/env.ts b/src/main/env.tsindex dc34a7d..a01ca73 100644--- a/src/main/env.ts+++ b/src/main/env.ts@@ -3,6 +3,7 @@ import { existsSync, writeFileSync, readdirSync, createWriteStream, mkdirSync, cimport { homedir } from 'os'import { join } from 'path'import { app, BrowserWindow, net } from 'electron'+import type { EngineStatus } from '../shared/types'export interface ToolInfo {found: boolean@@ -110,13 +111,18 @@ const ENGINE_DEPS = ['beartype', 'rotary_embedding_torch', 'einops']let engineDepsReady = falselet gpuProbe: Promise<boolean> | null = null+let gpuInfo: boolean | undefined-/* true when the venv's torch can run the roformer engine on a GPU- (MPS on Apple Silicon, CUDA on NVIDIA). CPU-only machines stay on- the demucs engine, which is much faster without GPU acceleration */+/* informational only: whether the venv's torch can use a GPU (MPS on Apple+ Silicon, CUDA on NVIDIA). Engine choice no longer depends on this — it is+ surfaced in Settings as "GPU acceleration available — fast" vs "not+ available — CPU, slower" */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 (process.env.STEMKIT_FORCE_CPU === '1') {+ gpuInfo = false+ return Promise.resolve(false)+ }if (!gpuProbe) {gpuProbe = runCapture(venvPython(),@@ -128,10 +134,18 @@ export function hasGpuAcceleration(): Promise<boolean> {).then((out) => out.trim().endsWith('1')).catch(() => false)+ .then((gpu) => {+ gpuInfo = gpu+ return gpu+ })}return gpuProbe}+export function gpuAccelerationInfo(): boolean | undefined {+ return gpuInfo+}+/* venvs created before the roformer engine lack a few small packages;verify and install them once per session */export async function ensureEngineDeps(): Promise<boolean> {@@ -418,12 +432,15 @@ function downloadTo(const total = start + Number(res.headers['content-length'] ?? 0)const out = createWriteStream(part, { flags: resumed ? 'append' : 'w' })let done = 0+ // downloads surfaced in the UI (with an onProgress observer) report+ // finer-grained progress than the plain setup-log ones+ const step = onProgress ? 2 : 10res.on('data', (chunk: Buffer) => {done += chunk.lengthout.write(chunk)if (total > 0) {const pct = Math.floor(((start + done) / total) * 100)- if (pct >= lastPct + 10) {+ if (pct >= lastPct + step) {lastPct = pctsendEnvEvent(`${label}: ${pct}%`)}@@ -454,10 +471,11 @@ function downloadTo(})}-/* 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 */+/* Mel-band roformer vocals checkpoint. Fetched once per machine when the+ "studio-quality vocals" setting is enabled (explicitly, non-default), and+ awaited by the pipeline so a split never races the download. Non-fatal —+ the lazy download inside roformer.py stays as the fallback. Runs on CPU+ too: the toggle deliberately decouples quality from hardware */const CKPT_NAME = 'MelBandRoformer.ckpt'const CKPT_URL ='https://huggingface.co/KimberleyJSN/melbandroformer/resolve/main/MelBandRoformer.ckpt'@@ -481,10 +499,6 @@ export function ensureVocalsEngine(onProgress?: (pct: number) => void): Promise<}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) => {@@ -507,6 +521,103 @@ export function ensureVocalsEngine(onProgress?: (pct: number) => void): Promise<return vocalsEnginePromise.then(detach)}+/* htdemucs_ft checkpoint (~320MB, fine-tuned demucs). Fetched through the+ venv's torch-hub (get_model) so the cache location and file naming match+ exactly what separate.py expects at separation time. Progress is parsed+ from the downloader's output and reported via env events */+let ftWeightsPromise: Promise<boolean> | null = null+const ftProgressListeners = new Set<(pct: number) => void>()+let ftVerified = false++// htdemucs_ft is a bag of 4 checkpoints (demucs/remote/htdemucs_ft.yaml);+// torch-hub downloads them one after another, each with its own bar+const FT_BAG_COUNT = 4++function torchHubFetch(model: string, onProgress?: (pct: number) => void): Promise<void> {+ return new Promise((resolve, reject) => {+ const child = spawn(+ venvPython(),+ ['-c', `from demucs.pretrained import get_model; get_model(${JSON.stringify(model)})`],+ { env: { ...process.env } }+ )+ let lastPct = 0+ let filesDone = 0+ let stderrTail = ''+ child.stderr?.on('data', (chunk: Buffer) => {+ stderrTail = (stderrTail + chunk.toString()).slice(-1000)+ for (const piece of chunk.toString().split(/[\r\n]/)) {+ const m = piece.match(/(\d{1,3})%/)+ if (!m) continue+ const pct = Math.min(100, parseInt(m[1], 10))+ if (pct < lastPct) {+ // the next checkpoint's bar wrapped — count the previous as done+ filesDone = Math.min(filesDone + 1, FT_BAG_COUNT - 1)+ }+ lastPct = pct+ const overall = Math.min(+ 99,+ Math.round(((filesDone + pct / 100) / FT_BAG_COUNT) * 100)+ )+ sendEnvEvent(`fine-tuned engine: ${overall}%`)+ onProgress?.(overall)+ }+ })+ child.on('error', reject)+ child.on('close', (code) => {+ if (code === 0) {+ onProgress?.(100)+ resolve()+ } else {+ reject(+ new Error(+ stderrTail.split('\n').filter(Boolean).slice(-1).join('') ||+ `fine-tuned engine download exited ${code}`+ )+ )+ }+ })+ })+}++export function ensureFtWeights(onProgress?: (pct: number) => void): Promise<boolean> {+ if (onProgress) ftProgressListeners.add(onProgress)+ const detach = (): boolean => {+ if (onProgress) ftProgressListeners.delete(onProgress)+ return true+ }+ if (!ftWeightsPromise) {+ ftWeightsPromise = (async () => {+ sendEnvEvent('Downloading the fine-tuned engine (~320MB, one time)')+ await torchHubFetch('htdemucs_ft', (pct) => {+ for (const listener of ftProgressListeners) listener(pct)+ })+ sendEnvEvent('Fine-tuned engine ready', 'success')+ ftVerified = true+ return true+ })()+ .catch((err) => {+ sendEnvEvent(+ `Fine-tuned engine download failed: ${err instanceof Error ? err.message : String(err)} — it will download before the next split`,+ 'error'+ )+ return false+ })+ .finally(() => {+ ftWeightsPromise = null+ })+ }+ return ftWeightsPromise.then(detach)+}++export function engineStatus(): EngineStatus {+ return {+ vocalsDownloading: vocalsEnginePromise !== null,+ vocalsReady: existsSync(vocalsEnginePath()),+ ftDownloading: ftWeightsPromise !== null,+ ftVerified+ }+}+function extractArchive(archive: string, dest: string): Promise<void> {return new Promise((resolve, reject) => {mkdirSync(dest, { recursive: true })@@ -586,7 +697,7 @@ export async function bootstrap(): Promise<boolean> {child.on('error', reject)})- sendEnvEvent('Downloading the separation engine (~2GB, one time) — grab a coffee')+ sendEnvEvent('Downloading the separation engine — grab a coffee')let lastGeneric = 0await new Promise<void>((resolve, reject) => {const child = spawn(pip, [@@ -616,7 +727,7 @@ export async function bootstrap(): Promise<boolean> {const now = Date.now()if (now - lastGeneric > 8000) {lastGeneric = now- sendEnvEvent('Still downloading — this happens only once')+ sendEnvEvent('Still downloading…')}continue}@@ -655,9 +766,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)+ // no checkpoint prefetch here: the optional engines (~913MB vocals,+ // ~170MB fine-tuned) download only when their settings toggles are on,+ // handled by the app-start prefetch in index.tsreturn true} catch (err) {sendEnvEvent(err instanceof Error ? err.message : String(err), 'error')diff --git a/src/main/index.ts b/src/main/index.tsindex c42b235..efd1414 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3,14 +3,20 @@ import { join, normalize, extname } from 'path'import { existsSync, copyFileSync, mkdirSync, createReadStream, statSync } from 'fs'import { createServer, type Server } from 'http'import type { AddressInfo } from 'net'+import type { AppSettings } from '../shared/types'import {detectTools,bootstrap,updateYtDlp,refreshReady,ensureVocalsEngine,+ ensureFtWeights,+ hasGpuAcceleration,+ gpuAccelerationInfo,+ engineStatus,getStatus} from './env'+import { loadSettings, saveSettings } from './settings'import { loadSongs, removeSong, stemBuffers, stemsDir, stemsFor, mixWavPath } from './library'import { startJob, cancelJob, searchYouTube } from './pipeline'import { initUpdater } from './updater'@@ -112,14 +118,24 @@ app.whenReady().then(async () => {return}- // 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()+ // existing install (e.g. right after an update): pre-fetch the engine+ // checkpoints the user opted into, in the background, so the first split+ // doesn't stall on a download. Nothing is fetched while both toggles are+ // off (the defaults)+ if (await refreshReady()) {+ const settings = loadSettings()+ if (settings.roformerVocals) void ensureVocalsEngine()+ if (settings.htdemucsFt) void ensureFtWeights()+ // warm the informational GPU probe so Settings can show it right away+ void hasGpuAcceleration()+ }ipcMain.handle('env:status', async () => {await detectTools()- return getStatus()+ const status = { ...getStatus(), gpu: gpuAccelerationInfo() }+ // the probe result lands on a later status call; never blocks ready+ if (status.ready) void hasGpuAcceleration()+ return status})ipcMain.handle('env:bootstrap', async () => {@@ -185,6 +201,15 @@ app.whenReady().then(async () => {ipcMain.handle('search:youtube', (_e, query: string) => searchYouTube(query))ipcMain.handle('app:version', () => app.getVersion())+ ipcMain.handle('settings:get', () => loadSettings())+ ipcMain.handle('settings:set', (_e, patch: Partial<AppSettings>) => saveSettings(patch))+ // the renderer confirms optional-engine downloads explicitly; nothing+ // starts as a side effect of flipping a toggle+ ipcMain.handle('engines:status', () => engineStatus())+ ipcMain.handle('engines:fetch', (_e, which: 'vocals' | 'ft') => {+ if (which === 'vocals') void ensureVocalsEngine()+ else void ensureFtWeights()+ })initUpdater()ipcMain.handle('open-external', (_e, url: string) => {if (/^https:\/\/(www\.)?(youtube\.com|youtu\.be)\//.test(url)) {diff --git a/src/main/pipeline.ts b/src/main/pipeline.tsindex 62c2617..28dde91 100644--- a/src/main/pipeline.ts+++ b/src/main/pipeline.ts@@ -11,10 +11,11 @@ import {modelsDir,ensureEngineDeps,ensureVocalsEngine,- hasGpuAcceleration,+ ensureFtWeights,getStatus,ytDlpRuntimeArgs} from './env'+import { loadSettings } from './settings'import {songDir,stemsDir,@@ -100,15 +101,27 @@ export async function startJob(return}- // the roformer engine needs GPU acceleration to be practical; without it- // the job quietly stays on the demucs engine+ // engine resolution from settings: roformer vocals when opted in (runs on+ // CPU too — no GPU fallback by design), otherwise htdemucs / htdemucs_ft.+ // The stored model tag encodes the variant so the cache below re-splits+ // whenever the effective engine changes. Suffixes are appended only when+ // non-default, so tags written by older versions stay cache-compatible+ const settings = loadSettings()const wantsVocals = !stems?.length || stems.includes('vocals')- let model = requestedModel- if (requestedModel === MODEL_DEFAULT && wantsVocals && !(await hasGpuAcceleration())) {- model = 'htdemucs'+ let engine: string+ if (requestedModel === MODEL_EXTENDED) {+ engine = requestedModel+ } else if (requestedModel === MODEL_DEFAULT && settings.roformerVocals && wantsVocals) {+ engine = MODEL_DEFAULT+ } else {+ engine = settings.htdemucsFt ? 'htdemucs_ft' : 'htdemucs'}+ const modelTag =+ engine ++ (settings.htdemucsFt && engine !== MODEL_EXTENDED ? '-ft' : '') ++ (settings.shifts === 2 ? '@s2' : '')- const job: ActiveJob = { videoId, model, cancelled: false }+ const job: ActiveJob = { videoId, model: modelTag, cancelled: false }jobs.set(videoId, job)const startedAt = Date.now()@@ -120,14 +133,14 @@ export async function startJob(const existing = loadSongs().find((s) => s.videoId === videoId)const covered =existing &&- existing.model === model &&+ existing.model === modelTag &&!!existing.stems?.length &&(stems?.length ? stems.every((s) => existing.stems!.includes(s)) : true)if (covered && stemsPresent(videoId, stemsFor(existing))) {send({ kind: 'done', data: { videoId, song: existing } })return}- if (existing && (existing.model !== model || !stemsPresent(videoId, stemsFor(existing)))) {+ if (existing && (existing.model !== modelTag || !stemsPresent(videoId, stemsFor(existing)))) {rmSync(songDir(videoId), { recursive: true, force: true })}@@ -220,28 +233,40 @@ export async function startJob(let scriptError: string | null = nullconst producedStems: string[] = []- const lineParsers = (mapPct: (pct: number, msg?: string) => number) => ({- onLine: (line: string): void => {- let parsed: Record<string, unknown>- try {- parsed = JSON.parse(line)- } catch {- return- }- if (parsed.type === 'progress') {- const pct = Number(parsed.pct ?? 0)- const message =- typeof parsed.message === 'string' ? parsed.message : undefined- progress(job, 'separate', mapPct(pct, message), message)- } else if (parsed.type === 'error') {- scriptError = `Separation failed: ${String(parsed.message)}`- } else if (parsed.type === 'done' && Array.isArray(parsed.stems)) {- producedStems.push(...(parsed.stems as unknown[]).map(String))+ const lineParsers = (mapPct: (pct: number, msg?: string) => number) => {+ // the separate stage must never move backwards: scripts can emit+ // multiple internal sweeps, and message-only events (pct 0) update+ // the status text without touching the bar+ let lastPct = 0+ return {+ onLine: (line: string): void => {+ let parsed: Record<string, unknown>+ try {+ parsed = JSON.parse(line)+ } catch {+ return+ }+ if (parsed.type === 'progress') {+ const pct = Number(parsed.pct ?? 0)+ const message =+ typeof parsed.message === 'string' ? parsed.message : undefined+ if (message && pct === 0) {+ progress(job, 'separate', lastPct, message)+ return+ }+ const mapped = Math.max(lastPct, mapPct(pct, message))+ lastPct = mapped+ progress(job, 'separate', mapped, message)+ } else if (parsed.type === 'error') {+ scriptError = `Separation failed: ${String(parsed.message)}`+ } else if (parsed.type === 'done' && Array.isArray(parsed.stems)) {+ producedStems.push(...(parsed.stems as unknown[]).map(String))+ }}}- })+ }- if (model === MODEL_EXTENDED) {+ if (engine === MODEL_EXTENDED) {progress(job, 'separate', 0, 'Separating stems')await runProcess(job,@@ -256,11 +281,13 @@ export async function startJob(MODEL_EXTENDED,'--device','auto',+ '--shifts',+ String(settings.shifts),...(stems?.length ? ['--only', stems.join(',')] : [])],lineParsers((pct) => pct))- } else if (model === MODEL_DEFAULT) {+ } else if (engine === MODEL_DEFAULT) {const otherStems = (stems?.length ? stems : ['drums', 'bass', 'other', 'vocals']).filter((s) => s !== 'vocals')@@ -308,6 +335,20 @@ export async function startJob()}if (otherStems.length > 0) {+ if (settings.htdemucsFt) {+ if (+ !(await ensureFtWeights((pct) =>+ progress(+ job,+ 'separate',+ wantsVocals ? roformerSpan : 0,+ `Downloading fine-tuned engine (~320MB): ${pct}%`+ )+ ))+ ) {+ bail('Could not download the fine-tuned engine weights')+ }+ }progress(job,'separate',@@ -324,9 +365,11 @@ export async function startJob('--out',stemsDir(videoId),'--model',- 'htdemucs',+ settings.htdemucsFt ? 'htdemucs_ft' : 'htdemucs','--device','auto',+ '--shifts',+ String(settings.shifts),'--only',otherStems.join(',')],@@ -339,6 +382,15 @@ export async function startJob(}} else {progress(job, 'separate', 0, 'Separating stems')+ if (settings.htdemucsFt) {+ if (+ !(await ensureFtWeights((pct) =>+ progress(job, 'separate', 0, `Downloading fine-tuned engine (~320MB): ${pct}%`)+ ))+ ) {+ bail('Could not download the fine-tuned engine weights')+ }+ }await runProcess(job,venvPython(),@@ -349,9 +401,11 @@ export async function startJob('--out',stemsDir(videoId),'--model',- model,+ engine,'--device','auto',+ '--shifts',+ String(settings.shifts),...(stems?.length ? ['--only', stems.join(',')] : [])],lineParsers((pct) => pct)diff --git a/src/main/settings.ts b/src/main/settings.tsnew file mode 100644index 0000000..ec2b4d6--- /dev/null+++ b/src/main/settings.ts@@ -0,0 +1,32 @@+import { readFileSync, writeFileSync } from 'fs'+import { join } from 'path'+import { BrowserWindow } from 'electron'+import { userDataDir } from './env'+import { DEFAULT_SETTINGS, type AppSettings } from '../shared/types'++function settingsFile(): string {+ return join(userDataDir(), 'settings.json')+}++export function loadSettings(): AppSettings {+ try {+ const data = JSON.parse(readFileSync(settingsFile(), 'utf8'))+ return { ...DEFAULT_SETTINGS, ...(data && typeof data === 'object' ? data : {}) }+ } catch {+ return { ...DEFAULT_SETTINGS }+ }+}++export function saveSettings(patch: Partial<AppSettings>): AppSettings {+ const merged = { ...loadSettings(), ...patch }+ const next: AppSettings = {+ shifts: merged.shifts === 2 ? 2 : 1,+ htdemucsFt: !!merged.htdemucsFt,+ roformerVocals: !!merged.roformerVocals+ }+ writeFileSync(settingsFile(), JSON.stringify(next, null, 2))+ for (const win of BrowserWindow.getAllWindows()) {+ win.webContents.send('settings:changed', next)+ }+ return next+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 2bd1b65..b2c7026 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,5 +1,5 @@import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'-import type { JobEvent, EnvEvent, UpdateEvent, StemKitApi } from '../shared/types'+import type { JobEvent, EnvEvent, UpdateEvent, AppSettings, StemKitApi } from '../shared/types'function subscribe<T>(channel: string, cb: (data: T) => void): () => void {const handler = (_e: IpcRendererEvent, data: T): void => cb(data)@@ -24,9 +24,14 @@ const api: StemKitApi = {openExternal: (url) => ipcRenderer.invoke('open-external', url),getAppVersion: () => ipcRenderer.invoke('app:version'),installUpdate: () => ipcRenderer.invoke('update:install'),+ getSettings: () => ipcRenderer.invoke('settings:get'),+ setSettings: (patch) => ipcRenderer.invoke('settings:set', patch),+ enginesStatus: () => ipcRenderer.invoke('engines:status'),+ fetchEngine: (which) => ipcRenderer.invoke('engines:fetch', which),onUpdateEvent: (cb) => subscribe<UpdateEvent>('update:event', cb),onJobEvent: (cb) => subscribe<JobEvent>('job:event', cb),- onEnvEvent: (cb) => subscribe<EnvEvent>('env:event', cb)+ onEnvEvent: (cb) => subscribe<EnvEvent>('env:event', cb),+ onSettingsChange: (cb) => subscribe<AppSettings>('settings:changed', cb)}contextBridge.exposeInMainWorld('stemkit', api)diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 1048c15..9e28dd3 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useState } from 'react'-import type { EnvStatus, JobProgress, JobStage, Song, UpdateEvent } from '../../shared/types'+import type { AppSettings, EnvStatus, JobProgress, JobStage, Song, UpdateEvent } from '../../shared/types'import { MODEL_DEFAULT } from '../../shared/types'import { parseVideoId } from '../../shared/url'import { Sidebar } from './components/Sidebar'@@ -7,6 +7,7 @@ import { Home } from './components/Home'import { Processing } from './components/Processing'import { Player } from './components/Player'import { Setup } from './components/Setup'+import { Settings } from './components/Settings'import { LogoMark } from './components/Icons'interface EnvLog {@@ -45,10 +46,14 @@ export default function App(): React.ReactElement {const [envLogs, setEnvLogs] = useState<EnvLog[]>([])const [update, setUpdate] = useState<UpdateEvent | null>(null)const [appVersion, setAppVersion] = useState<string | undefined>(undefined)+ const [settings, setSettings] = useState<AppSettings | null>(null)+ const [settingsOpen, setSettingsOpen] = useState(false)useEffect(() => {void window.stemkit.envStatus().then(setStatus)void window.stemkit.listSongs().then(setSongs)+ void window.stemkit.getSettings().then(setSettings)+ const offSettings = window.stemkit.onSettingsChange(setSettings)const offJob = window.stemkit.onJobEvent((ev) => {if (ev.kind === 'progress') {setJobs((prev) => ({ ...prev, [ev.data.videoId]: ev.data }))@@ -73,6 +78,7 @@ export default function App(): React.ReactElement {offJob()offEnv()offUpdate()+ offSettings()}}, [])@@ -223,8 +229,13 @@ export default function App(): React.ReactElement {hasSongs={displaySongs.length > 0}songs={displaySongs}pending={pendingMap}+ settings={settings ?? undefined}onStart={(u, m, s) => void startUrl(u, m, s)}onSelect={(id) => setActiveId(id)}+ onOpenSettings={() => {+ void window.stemkit.envStatus().then(setStatus)+ setSettingsOpen(true)+ }}/>)}@@ -241,8 +252,20 @@ export default function App(): React.ReactElement {onDelete={(id) => void deleteSong(id)}onAdd={() => setActiveId(null)}onInstallUpdate={() => window.stemkit.installUpdate()}+ onOpenSettings={() => {+ void window.stemkit.envStatus().then(setStatus)+ setSettingsOpen(true)+ }}/><main className="flex-1 min-w-0">{main}</main>+ {settings && settingsOpen && (+ <Settings+ settings={settings}+ gpu={status.gpu}+ onChange={(patch) => void window.stemkit.setSettings(patch)}+ onClose={() => setSettingsOpen(false)}+ />+ )}</div>)}diff --git a/src/renderer/src/components/Home.tsx b/src/renderer/src/components/Home.tsxindex 383ac2d..64f78e8 100644--- a/src/renderer/src/components/Home.tsx+++ b/src/renderer/src/components/Home.tsx@@ -3,6 +3,7 @@ import {MODEL_DEFAULT,MODEL_EXTENDED,DEFAULT_STEMS,+ type AppSettings,type SearchResult,type Song,type StemId@@ -10,18 +11,29 @@ import {import { parseVideoId } from '../../../shared/url'import { STEM_INFO, PREFERRED_ORDER } from '../lib/stems'import { fmtTime } from '../lib/format'+import { GearIcon } from './Icons'interface Props {hasSongs: booleansongs: Song[]pending?: Record<string, { label: string; error?: boolean }>+ settings?: AppSettingsonStart: (url: string, model: string, stems?: string[]) => voidonSelect: (videoId: string) => void+ onOpenSettings: () => void}const ALL_STEMS = PREFERRED_ORDER-export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props): React.ReactElement {+export function Home({+ hasSongs,+ songs,+ pending = {},+ settings,+ onStart,+ onSelect,+ onOpenSettings+}: Props): React.ReactElement {const [query, setQuery] = useState('')const [selected, setSelected] = useState<Set<StemId>>(new Set<StemId>(DEFAULT_STEMS as StemId[]))const [results, setResults] = useState<SearchResult[]>([])@@ -34,6 +46,32 @@ export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Propsconst usesExtended = [...selected].some((id) => id === 'guitar' || id === 'piano')const derivedModel = usesExtended ? MODEL_EXTENDED : MODEL_DEFAULTconst orderedSelection = ALL_STEMS.filter((id) => selected.has(id))+ // the fine-tuned engine only covers the standard 4-stem split; guitar and+ // piano always run through the 6-source engine, so they're unavailable+ // while it's on+ const ftOn = !!settings?.htdemucsFt+ useEffect(() => {+ if (!ftOn) return+ setSelected((prev) => {+ if (!prev.has('guitar') && !prev.has('piano')) return prev+ const next = new Set(prev)+ next.delete('guitar')+ next.delete('piano')+ return next+ })+ }, [ftOn])+ const engineLabel = usesExtended+ ? '6-source engine'+ : settings?.roformerVocals+ ? 'studio engine'+ : settings?.htdemucsFt+ ? 'enhanced engine'+ : 'standard engine'+ const timeHint = usesExtended || settings?.roformerVocals+ ? 'A 4-minute song takes about three minutes to split.'+ : settings?.htdemucsFt || settings?.shifts === 2+ ? 'A 4-minute song takes a little longer with the quality options on.'+ : 'A 4-minute song takes about three minutes to split.'const toggleStem = (id: StemId): void => {setSelected((prev) => {@@ -142,16 +180,24 @@ export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props<span className="text-[11px] font-semibold uppercase tracking-widest text-white/30">Instruments</span>- <span className="text-[11px] text-white/30 font-medium">- {selected.size === 0- ? 'select at least one'- : usesExtended- ? `6-source engine · ${selected.size} stems`- : `roformer engine · ${selected.size} stems`}+ <span className="flex items-center gap-1.5">+ <span className="text-[11px] text-white/30 font-medium">+ {selected.size === 0+ ? 'select at least one'+ : `${engineLabel} · ${selected.size} stems`}+ </span>+ <button+ onClick={onOpenSettings}+ title="Quality settings"+ className="no-drag w-5 h-5 rounded-md hover:bg-white/10 text-white/35 hover:text-white flex items-center justify-center transition-colors"+ >+ <GearIcon className="w-3 h-3" />+ </button></span></div><div className="flex items-center gap-1.5 flex-wrap">{ALL_STEMS.map((id) => {+ if (ftOn && (id === 'guitar' || id === 'piano')) return nullconst info = STEM_INFO[id]const on = selected.has(id)return (@@ -267,9 +313,7 @@ export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props)}{!hasSongs && results.length === 0 && !searching && (- <p className="mt-8 text-center text-xs text-white/25 leading-relaxed">- A 4-minute song takes about three minutes to split.- </p>+ <p className="mt-8 text-center text-xs text-white/25 leading-relaxed">{timeHint}</p>)}</div></div>diff --git a/src/renderer/src/components/Icons.tsx b/src/renderer/src/components/Icons.tsxindex f205727..a476ab5 100644--- a/src/renderer/src/components/Icons.tsx+++ b/src/renderer/src/components/Icons.tsx@@ -101,6 +101,15 @@ export function PlusIcon({ className = base }: IconProps) {)}+export function GearIcon({ className = base }: IconProps) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>+ <circle cx="12" cy="12" r="3" />+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z" />+ </svg>+ )+}+export function XIcon({ className = base }: IconProps) {return (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" className={className}>diff --git a/src/renderer/src/components/Settings.tsx b/src/renderer/src/components/Settings.tsxnew file mode 100644index 0000000..2d30d03--- /dev/null+++ b/src/renderer/src/components/Settings.tsx@@ -0,0 +1,287 @@+import { useEffect, useState } from 'react'+import type { AppSettings, EngineStatus } from '../../../shared/types'+import { XIcon } from './Icons'++interface Props {+ settings: AppSettings+ gpu?: boolean+ onChange: (patch: Partial<AppSettings>) => void+ onClose: () => void+}++function Toggle({+ on,+ disabled,+ loading,+ onClick+}: {+ on: boolean+ disabled?: boolean+ loading?: boolean+ onClick: () => void+}): React.ReactElement {+ return (+ <button+ onClick={onClick}+ disabled={disabled}+ role="switch"+ aria-checked={on}+ className={`no-drag relative shrink-0 w-10 h-6 rounded-full transition-colors ${+ loading+ ? 'bg-white/10 cursor-wait'+ : on+ ? 'bg-violet-500'+ : 'bg-white/10 hover:bg-white/15'+ } ${disabled && !loading ? 'opacity-60 cursor-not-allowed hover:bg-white/10' : ''}`}+ >+ {loading ? (+ <span className="absolute inset-0 flex items-center justify-center">+ <span className="w-3 h-3 rounded-full border-2 border-white/25 border-t-white/80 animate-spin" />+ </span>+ ) : (+ <span+ className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${+ on ? 'translate-x-4' : 'translate-x-0'+ }`}+ />+ )}+ </button>+ )+}++function DownloadBar({+ pct,+ starting,+ error+}: {+ pct: number | null+ starting?: boolean+ error?: string | null+}): React.ReactElement | null {+ if (error) {+ return <p className="mt-1.5 text-[11px] text-rose-300">{error}</p>+ }+ if (starting) {+ return (+ <div className="mt-2">+ <div className="text-[11px] text-white/45 mb-1">Starting…</div>+ <div className="h-1 rounded-full bg-white/10 overflow-hidden">+ <div+ className="h-full w-full rounded-full bg-gradient-to-r from-violet-400 to-emerald-300 animate-pulse opacity-40"+ />+ </div>+ </div>+ )+ }+ if (pct === null || pct >= 100) return null+ return (+ <div className="mt-2">+ <div className="flex items-center justify-between text-[11px] text-white/45 mb-1">+ <span>Downloading…</span>+ <span className="font-mono">{pct}%</span>+ </div>+ <div className="h-1 rounded-full bg-white/10 overflow-hidden">+ <div+ className="h-full rounded-full bg-gradient-to-r from-violet-400 to-emerald-300 transition-all"+ style={{ width: `${pct}%` }}+ />+ </div>+ </div>+ )+}++function ConfirmButton({ label, onClick }: { label: string; onClick: () => void }): React.ReactElement {+ return (+ <button+ onClick={onClick}+ className="no-drag mt-2 px-3 py-1.5 rounded-lg bg-violet-500/90 hover:bg-violet-500 active:scale-[0.98] text-white text-[12px] font-semibold transition-colors"+ >+ {label}+ </button>+ )+}++export function Settings({ settings, gpu, onChange, onClose }: Props): React.ReactElement {+ const [engines, setEngines] = useState<EngineStatus | null>(null)+ const [vocalsPct, setVocalsPct] = useState<number | null>(null)+ const [ftPct, setFtPct] = useState<number | null>(null)+ const [vocalsError, setVocalsError] = useState<string | null>(null)+ const [ftError, setFtError] = useState<string | null>(null)+ const [vocalsStarting, setVocalsStarting] = useState(false)+ const [ftStarting, setFtStarting] = useState(false)++ useEffect(() => {+ const off = window.stemkit.onEnvEvent((e) => {+ const vocals = e.message.match(/vocals engine: (\d+)%/)+ if (vocals) {+ setVocalsPct(parseInt(vocals[1], 10))+ setVocalsError(null)+ }+ if (/Vocals engine ready/.test(e.message)) setVocalsPct(100)+ if (/Vocals engine download failed/.test(e.message)) setVocalsError(e.message)++ const ft = e.message.match(/fine-tuned engine: (\d+)%/)+ if (ft) {+ setFtPct(parseInt(ft[1], 10))+ setFtError(null)+ }+ if (/Fine-tuned engine ready/.test(e.message)) setFtPct(100)+ if (/Fine-tuned engine download failed/.test(e.message)) setFtError(e.message)+ })+ return off+ }, [])++ // poll engine state so the confirm button / spinner reflect reality even+ // for downloads started elsewhere (startup prefetch, a split in progress)+ useEffect(() => {+ let alive = true+ const tick = (): void => {+ void window.stemkit.enginesStatus().then((s) => {+ if (!alive) return+ setEngines(s)+ if (s.vocalsDownloading || s.vocalsReady) setVocalsStarting(false)+ if (s.ftDownloading || s.ftVerified) setFtStarting(false)+ })+ }+ tick()+ const id = setInterval(tick, 1000)+ return () => {+ alive = false+ clearInterval(id)+ }+ }, [])++ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => {+ if (e.key === 'Escape') onClose()+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [onClose])++ const gpuLine =+ gpu === true+ ? 'Uses your GPU — fast'+ : gpu === false+ ? 'No GPU found — expect ~20-35 min per song on CPU'+ : null++ const vocalsBusy = vocalsStarting || (engines?.vocalsDownloading ?? false)+ const ftBusy = ftStarting || (engines?.ftDownloading ?? false)+ const showVocalsConfirm =+ !!engines && settings.roformerVocals && !engines.vocalsReady && !vocalsBusy+ const showFtConfirm = !!engines && settings.htdemucsFt && !engines.ftVerified && !ftBusy++ const startVocals = (): void => {+ setVocalsStarting(true)+ setVocalsPct(null)+ setVocalsError(null)+ void window.stemkit.fetchEngine('vocals')+ }++ const startFt = (): void => {+ setFtStarting(true)+ setFtPct(null)+ setFtError(null)+ void window.stemkit.fetchEngine('ft')+ }++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"+ onClick={onClose}+ >+ <div+ className="glass rounded-2xl w-full max-w-md mx-4 shadow-2xl rise-in"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/[0.07]">+ <h2 className="text-[14px] font-semibold tracking-tight">Quality settings</h2>+ <button+ onClick={onClose}+ title="Close"+ className="no-drag w-7 h-7 rounded-lg hover:bg-white/10 text-white/50 hover:text-white flex items-center justify-center transition-colors"+ >+ <XIcon className="w-3.5 h-3.5" />+ </button>+ </div>++ <div className="px-5 py-4 space-y-5">+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-[13px] font-medium">Studio-quality vocals</p>+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">+ Cleaner, more natural vocal separation.+ </p>+ {gpuLine && <p className="text-[11px] text-white/30 mt-1">{gpuLine}</p>}+ <DownloadBar pct={vocalsPct} starting={vocalsBusy && vocalsPct === null} error={vocalsError} />+ {showVocalsConfirm && (+ <ConfirmButton label="Download now · 913 MB" onClick={startVocals} />+ )}+ </div>+ <Toggle+ on={settings.roformerVocals}+ disabled={vocalsBusy}+ loading={vocalsBusy}+ onClick={() => onChange({ roformerVocals: !settings.roformerVocals })}+ />+ </div>++ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-[13px] font-medium">Cleaner instruments</p>+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">+ Extra polish for drums, bass and other. Up to 4× slower.+ </p>+ <DownloadBar pct={ftPct} starting={ftBusy && ftPct === null} error={ftError} />+ {showFtConfirm && (+ <ConfirmButton label="Download now · ~320 MB" onClick={startFt} />+ )}+ </div>+ <Toggle+ on={settings.htdemucsFt}+ disabled={ftBusy}+ loading={ftBusy}+ onClick={() => onChange({ htdemucsFt: !settings.htdemucsFt })}+ />+ </div>++ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-[13px] font-medium">Extra quality pass</p>+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">+ Separates the song twice and blends the takes for cleaner results. Up to 3×+ slower.+ </p>+ </div>+ <div className="flex shrink-0 rounded-lg bg-white/[0.06] p-0.5 border border-white/[0.08]">+ {([+ { v: 1 as const, label: 'Fast' },+ { v: 2 as const, label: 'Best' }+ ]).map((opt) => (+ <button+ key={opt.v}+ onClick={() => onChange({ shifts: opt.v })}+ className={`no-drag px-2.5 h-6 rounded-md text-[12px] font-semibold transition-colors ${+ settings.shifts === opt.v+ ? 'bg-white text-black'+ : 'text-white/45 hover:text-white/80'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </div>+ </div>++ <div className="px-5 py-3 border-t border-white/[0.07]">+ <p className="text-[11px] text-white/30 leading-relaxed">+ Changes apply to future splits. Songs you already split keep their current sound —+ split them again to use the new settings.+ </p>+ </div>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/components/Setup.tsx b/src/renderer/src/components/Setup.tsxindex 8021725..5b8a788 100644--- a/src/renderer/src/components/Setup.tsx+++ b/src/renderer/src/components/Setup.tsx@@ -23,9 +23,7 @@ export function Setup({ status, logs, onInstall }: Props): React.ReactElement {<h1 className="text-xl font-bold tracking-tight">Welcome to StemKit</h1></div><p className="text-center text-white/45 text-sm mt-3 leading-relaxed">- One-time setup downloads the separation engine (~2 GB).- <br />- After that everything works offline, right on your machine.+ One-time setup — after this everything works offline, right on your machine.</p>{!status.bootstrapping && (@@ -33,7 +31,7 @@ export function Setup({ status, logs, onInstall }: Props): React.ReactElement {onClick={onInstall}className="mt-7 w-full py-3.5 rounded-xl bg-white text-black font-semibold text-sm hover:bg-white/90 active:scale-[0.99] transition-all">- Get started · ~2 GB, once+ Get started (~2 GB, one time)</button>)}diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsxindex c3eb0bb..3b4e6c1 100644--- a/src/renderer/src/components/Sidebar.tsx+++ b/src/renderer/src/components/Sidebar.tsx@@ -1,6 +1,6 @@import type { Song } from '../../../shared/types'import { fmtTime } from '../lib/format'-import { LogoMark, TrashIcon, PlusIcon } from './Icons'+import { LogoMark, TrashIcon, PlusIcon, GearIcon } from './Icons'interface Props {songs: Song[]@@ -12,6 +12,7 @@ interface Props {onDelete: (videoId: string) => voidonAdd: () => voidonInstallUpdate: () => void+ onOpenSettings: () => void}export function Sidebar({@@ -23,13 +24,21 @@ export function Sidebar({onSelect,onDelete,onAdd,- onInstallUpdate+ onInstallUpdate,+ onOpenSettings}: Props): React.ReactElement {return (<aside className="w-[264px] shrink-0 h-full flex flex-col border-r border-white/[0.07] bg-black/20"><div className="drag-region h-14 shrink-0 flex items-center gap-2.5 pl-[80px] pr-4"><LogoMark /><span className="font-semibold tracking-tight text-[15px]">StemKit</span>+ <button+ onClick={onOpenSettings}+ title="Quality settings"+ className="no-drag ml-auto w-7 h-7 rounded-lg bg-white/5 hover:bg-white/10 text-white/50 hover:text-white flex items-center justify-center transition-colors"+ >+ <GearIcon className="w-3.5 h-3.5" />+ </button></div><div className="px-5 pb-2 pt-1 flex items-center justify-between">diff --git a/src/shared/types.ts b/src/shared/types.tsindex 5eee530..819d970 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -16,12 +16,32 @@ export interface Song {took?: number}+export interface AppSettings {+ shifts: 1 | 2+ htdemucsFt: boolean+ roformerVocals: boolean+}++export const DEFAULT_SETTINGS: AppSettings = {+ shifts: 1,+ htdemucsFt: false,+ roformerVocals: false+}++export interface EngineStatus {+ vocalsDownloading: boolean+ vocalsReady: boolean+ ftDownloading: boolean+ ftVerified: boolean+}+export interface EnvStatus {python: { found: boolean; path?: string; version?: string }ffmpeg: { found: boolean; path?: string }ready: booleanbootstrapping: booleanupdating: boolean+ gpu?: boolean}export interface EnvEvent {@@ -83,7 +103,12 @@ export interface StemKitApi {openExternal(url: string): Promise<void>getAppVersion(): Promise<string>installUpdate(): void+ getSettings(): Promise<AppSettings>+ setSettings(patch: Partial<AppSettings>): Promise<AppSettings>+ enginesStatus(): Promise<EngineStatus>+ fetchEngine(which: 'vocals' | 'ft'): Promise<void>onUpdateEvent(cb: (ev: UpdateEvent) => void): () => voidonJobEvent(cb: (ev: JobEvent) => void): () => voidonEnvEvent(cb: (ev: EnvEvent) => void): () => void+ onSettingsChange(cb: (settings: AppSettings) => void): () => void}