Split any YouTube song into stems
TypeScript
fix: address final key-detection review findings
David Navia2940e3280794
diff --git a/electron-builder.yml b/electron-builder.ymlindex 3cfda9f..22d1112 100644--- a/electron-builder.yml+++ b/electron-builder.yml@@ -14,6 +14,7 @@ publish:extraResources:- from: pythonto: python+ filter: ["**/*", "!tests/**"]mac:category: public.app-category.musicicon: build/icon.pngdiff --git a/package.json b/package.jsonindex ac9b949..7f38a34 100644--- a/package.json+++ b/package.json@@ -16,6 +16,7 @@"typecheck:web": "node scripts/run.cjs typecheck:web","typecheck": "node scripts/run.cjs typecheck","test:audio": "node scripts/run.cjs test:audio",+ "test:py": "node scripts/run.cjs test:py","dist": "node scripts/run.cjs dist","dist:win": "node scripts/run.cjs dist:win","dist:linux": "node scripts/run.cjs dist:linux",diff --git a/scripts/run.cjs b/scripts/run.cjsindex 28a1b9a..9a3e0e4 100644--- a/scripts/run.cjs+++ b/scripts/run.cjs@@ -74,6 +74,8 @@ function findNode(requiredMajor) {const STEPS = {'test:audio': [['node', '--experimental-strip-types', '--test', 'tests/engine.test.mjs', 'tests/pan-storage.test.mjs', 'tests/keys.test.mjs', 'tests/key-storage.test.mjs']],+ // STEMKIT_PY points at an interpreter that has numpy (e.g. the dev venv)+ 'test:py': [[process.env.STEMKIT_PY || (IS_WIN ? 'python' : 'python3'), '-m', 'unittest', 'discover', '-s', 'python/tests', '-v']],dev: [['electron-vite', 'dev']],build: [['electron-vite', 'build']],typecheck: [@@ -122,6 +124,7 @@ function ensureFfmpeg() {}function resolveBin(name) {+ if (path.isAbsolute(name) && fs.existsSync(name)) return nameconst ext = IS_WIN ? '.cmd' : ''const local = path.join(ROOT, 'node_modules', '.bin', name + ext)if (fs.existsSync(local)) return localdiff --git a/src/main/keydetect.ts b/src/main/keydetect.tsindex 25b7249..7d1f4b0 100644--- a/src/main/keydetect.ts+++ b/src/main/keydetect.ts@@ -53,9 +53,10 @@ export function runKeyScript(inputs: string[]): Promise<SongKey> {Number.isInteger(msg.tonic) &&(msg.mode === 'major' || msg.mode === 'minor')) {+ const confidence = Number(msg.confidence)return done({detected: keyName(msg.tonic, msg.mode as KeyMode),- confidence: Number(msg.confidence)+ ...(Number.isFinite(confidence) ? { confidence } : {})})}} catch {@@ -67,6 +68,11 @@ export function runKeyScript(inputs: string[]): Promise<SongKey> {})}+// a fresh detection must not drop the user's manual correction+export function withOverride(key: SongKey, previous: SongKey | undefined): SongKey {+ return previous?.override ? { ...key, override: previous.override } : key+}+const inflight = new Map<string, Promise<SongKey>>()export function detectOnce(videoId: string, run = runKeyScript): Promise<SongKey> {@@ -84,7 +90,7 @@ export function detectOnce(videoId: string, run = runKeyScript): Promise<SongKey// keep a user override that was set before detection finished; a// failure is stored too so it is not retriedconst current = loadSongs().find((s) => s.videoId === videoId)?.key- const key: SongKey = current?.override ? { ...result, override: current.override } : result+ const key = withOverride(result, current)patchSongKey(videoId, key)return key} finally {diff --git a/src/main/pipeline.ts b/src/main/pipeline.tsindex d22a54c..ce466ec 100644--- a/src/main/pipeline.ts+++ b/src/main/pipeline.ts@@ -36,7 +36,7 @@ import { parseVideoId } from '../shared/url'import { AUDIO_EXTENSIONS, audioExtension, localSongId } from '../shared/local'import { cacheThumbnail } from './thumbs'import { acquireSeparation } from './separation-slots'-import { keyInputs, runKeyScript } from './keydetect'+import { keyInputs, runKeyScript, withOverride } from './keydetect'interface ActiveJob {videoId: string@@ -187,6 +187,8 @@ function finalizeJob(): void {progress(job, 'finalize', 100, 'Adding to library')const took = Math.round((Date.now() - info.startedAt) / 1000)+ // re-splitting must not lose a key the user corrected by hand+ const previousKey = loadSongs().find((s) => s.videoId === job.videoId)?.keyconst songs = upsertSong({videoId: job.videoId,title: info.title,@@ -196,7 +198,7 @@ function finalizeJob(stems: producedStems,took,source: info.source,- key+ key: withOverride(key, previousKey)})send({ kind: 'done', data: { videoId: job.videoId, song: songs[0] } })diff --git a/src/renderer/src/components/KeyControl.tsx b/src/renderer/src/components/KeyControl.tsxindex 092122c..1770022 100644--- a/src/renderer/src/components/KeyControl.tsx+++ b/src/renderer/src/components/KeyControl.tsx@@ -5,14 +5,12 @@ import { KEY_NAMES } from '../../../shared/keys'interface Props {songKey: SongKey | undefinedonOverride: (key: string | null) => void- // second line, rendered under the label (transpose controls arrive in a later PR)- children?: React.ReactNode}const MAJORS = KEY_NAMES.slice(0, 12)const MINORS = KEY_NAMES.slice(12)-export function KeyControl({ songKey, onOverride, children }: Props): React.ReactElement {+export function KeyControl({ songKey, onOverride }: Props): React.ReactElement {const [open, setOpen] = useState(false)const rootRef = useRef<HTMLDivElement>(null)@@ -67,21 +65,20 @@ export function KeyControl({ songKey, onOverride, children }: Props): React.Reac<span title="Set manually" className="w-1.5 h-1.5 rounded-full bg-violet-400" />)}</button>- {children}{open && (<divrole="dialog"aria-label="Original key"className="no-drag absolute bottom-full right-0 mb-2 z-50 w-64 p-2 rounded-xl bg-[#16151d] border border-white/[0.08] shadow-2xl">- {songKey?.detected && (+ {(songKey?.detected || override) && (<buttononClick={() => choose(null)}className={`w-full text-left px-2 py-1 mb-1 rounded-md text-[12px] transition-colors ${!override ? 'text-white bg-white/10' : 'text-white/70 hover:bg-white/10 hover:text-white'}`}>- Auto ({songKey.detected})+ Auto ({songKey?.detected ?? '?'})</button>)}<div className="grid grid-cols-6 gap-0.5">{MAJORS.map(keyButton)}</div>diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsxindex 1fed00c..370b784 100644--- a/src/renderer/src/components/Player.tsx+++ b/src/renderer/src/components/Player.tsx@@ -128,17 +128,20 @@ export function Player({ song, settings }: Props): React.ReactElement {let cancelled = falsesetSongKey(song.key)- if (song.key === undefined) {- window.stemkit- .detectKey(song.videoId)- .then((k) => {- if (!cancelled) setSongKey(k)- })- .catch(() => {- // detection is best-effort: show '?' rather than analysing forever- if (!cancelled) setSongKey({ detected: null })- })- }+ // the songs list is not reloaded after detection or an override, so+ // song.key can be stale: detectKey returns the stored key cheaply and+ // only detects when none exists+ const hadKey = song.key !== undefined+ window.stemkit+ .detectKey(song.videoId)+ .then((k) => {+ if (!cancelled) setSongKey(k)+ })+ .catch(() => {+ // detection is best-effort: show '?' rather than analysing forever,+ // but keep a key we already had+ if (!cancelled && !hadKey) setSongKey({ detected: null })+ })const flushPan = (): void => {if (panSaveTimer.current !== null) clearTimeout(panSaveTimer.current)panSaveTimer.current = nulldiff --git a/src/shared/keys.ts b/src/shared/keys.tsindex df63e9b..36d7c86 100644--- a/src/shared/keys.ts+++ b/src/shared/keys.ts@@ -1,7 +1,6 @@export type KeyMode = 'major' | 'minor'-// Index = pitch class (C = 0). Flats for major, sharps for minor except the-// conventional E♭m / B♭m, so each pitch class has exactly one display name.+// Index = pitch class (C = 0). One fixed spelling per pitch class, the most common one for each key.const MAJOR = ['C', 'D♭', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B']const MINOR = ['Cm', 'C♯m', 'Dm', 'E♭m', 'Em', 'Fm', 'F♯m', 'Gm', 'G♯m', 'Am', 'B♭m', 'Bm']@@ -18,15 +17,3 @@ export function parseKey(name: string): { tonic: number; mode: KeyMode } | nullif (i < 0) return nullreturn i < 12 ? { tonic: i, mode: 'major' } : { tonic: i - 12, mode: 'minor' }}--export function transposeKey(name: string, semitones: number): string | null {- const key = parseKey(name)- if (!key) return null- return keyName(key.tonic + semitones, key.mode)-}--export function formatShift(semitones: number): string {- if (semitones > 0) return `+${semitones}`- if (semitones < 0) return `−${-semitones}`- return '0'-}diff --git a/tests/key-storage.test.mjs b/tests/key-storage.test.mjsindex 0af782d..af4bef1 100644--- a/tests/key-storage.test.mjs+++ b/tests/key-storage.test.mjs@@ -33,7 +33,7 @@ const hooks = registerHooks({}})const { saveSongs, loadSongs, patchSongKey, setKeyOverride } = await import(src('library.ts'))-const { keyInputs, detectOnce } = await import(src('keydetect.ts'))+const { keyInputs, detectOnce, withOverride } = await import(src('keydetect.ts'))hooks.deregister()const mk = (id) => ({ videoId: id, stems: ['vocals', 'drums', 'bass'], title: id, duration: 10, addedAt: 1 })@@ -113,3 +113,9 @@ test('an override on a keyless song marks it attempted', async () => {await detectOnce('g', async () => (calls++, { detected: 'C' }))assert.equal(calls, 0)})++test('withOverride carries a previous override onto a fresh detection', () => {+ assert.deepEqual(withOverride({ detected: 'C' }, { detected: 'G', override: 'Am' }), { detected: 'C', override: 'Am' })+ assert.deepEqual(withOverride({ detected: 'C' }, { detected: 'G' }), { detected: 'C' })+ assert.deepEqual(withOverride({ detected: 'C' }, undefined), { detected: 'C' })+})diff --git a/tests/keys.test.mjs b/tests/keys.test.mjsindex e377ab0..47421b5 100644--- a/tests/keys.test.mjs+++ b/tests/keys.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test'import assert from 'node:assert/strict'-import { KEY_NAMES, keyName, parseKey, transposeKey, formatShift } from '../src/shared/keys.ts'+import { KEY_NAMES, keyName, parseKey } from '../src/shared/keys.ts'test('keyName maps tonic and mode to the display name', () => {assert.equal(keyName(9, 'minor'), 'Am')@@ -12,19 +12,6 @@ test('parseKey accepts only the 24 table names', () => {assert.equal(parseKey('H'), null)})-test('transposeKey wraps modulo 12', () => {- assert.equal(transposeKey('Am', -3), 'F♯m')- assert.equal(transposeKey('C', 14), 'D')- assert.equal(transposeKey('Am', 0), 'Am')- assert.equal(transposeKey('nope', 1), null)-})--test('formatShift uses a real minus sign', () => {- assert.equal(formatShift(-3), '−3')- assert.equal(formatShift(2), '+2')- assert.equal(formatShift(0), '0')-})-test('KEY_NAMES has 24 unique names', () => {assert.equal(KEY_NAMES.length, 24)assert.equal(new Set(KEY_NAMES).size, 24)