Skip to content

Split any YouTube song into stems

TypeScript

feat: add numpy-only key detection script

David Navia477c0a74a88f
diff --git a/python/key.py b/python/key.py
new file mode 100644
index 0000000..85f7166
--- /dev/null
+++ b/python/key.py
@@ -0,0 +1,109 @@
+"""numpy-only musical key detection (Krumhansl-Kessler profiles).
+
+CLI: key.py --input A.wav [--input B.wav ...]
+prints one json line: {"type":"key","tonic":0-11 (C=0),"mode":"major"|"minor","confidence":0-1}
+"""
+import argparse
+import struct
+
+import numpy as np
+
+from separate import emit, fail, load_wav
+
+MAX_SECONDS = 240
+FRAME = 8192
+HOP = 4096
+MIN_HZ = 55.0
+MAX_HZ = 2000.0
+
+MAJOR = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
+MINOR = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
+
+
+def read_wav(path):
+ """load_wav (stdlib wave) rejects float32 wavs (fmt tag 3), which is what
+ separate.py writes for stems, so parse those here and delegate the rest"""
+ try:
+ with open(path, "rb") as f:
+ head = f.read(12)
+ fmt = data = None
+ while head[:4] == b"RIFF" and (chunk := f.read(8)) and len(chunk) == 8:
+ cid, size = struct.unpack("<4sI", chunk)
+ if cid == b"fmt ":
+ fmt = struct.unpack("<HHIIHH", f.read(16))
+ f.seek(size - 16 + (size & 1), 1)
+ elif cid == b"data":
+ data = f.read(size)
+ break
+ else:
+ f.seek(size + (size & 1), 1)
+ except OSError:
+ return load_wav(path)
+ if fmt is None or data is None or fmt[0] != 3 or fmt[5] != 32:
+ return load_wav(path)
+ channels = fmt[1]
+ if channels == 0:
+ fail("empty wav")
+ usable = len(data) // (4 * channels) * 4 * channels
+ audio = np.frombuffer(data[:usable], dtype="<f4").reshape(-1, channels).T
+ return audio.astype(np.float32), fmt[2]
+
+
+def chroma(mono, sr):
+ mono = np.asarray(mono, dtype=np.float32)[: int(MAX_SECONDS * sr)]
+ if mono.size < FRAME:
+ mono = np.pad(mono, (0, FRAME - mono.size))
+ window = np.hanning(FRAME).astype(np.float32)
+ freqs = np.fft.rfftfreq(FRAME, 1.0 / sr)
+ bins = np.nonzero((freqs >= MIN_HZ) & (freqs <= MAX_HZ))[0]
+ # pitch class per bin, A = 9
+ pcs = (np.round(12 * np.log2(freqs[bins] / 440.0)).astype(int) + 9) % 12
+ vec = np.zeros(12)
+ for start in range(0, mono.size - FRAME + 1, HOP):
+ mag = np.abs(np.fft.rfft(mono[start : start + FRAME] * window))[bins]
+ vec += np.bincount(pcs, weights=np.log1p(mag), minlength=12)
+ return vec
+
+
+def detect_key(mono, sr):
+ vec = chroma(mono, sr)
+ if float(vec.sum()) < 1e-6:
+ fail("no tonal content")
+ scores = []
+ for mode, profile in (("major", MAJOR), ("minor", MINOR)):
+ for tonic in range(12):
+ r = np.corrcoef(vec, np.roll(profile, tonic))[0, 1]
+ scores.append((0.0 if np.isnan(r) else float(r), tonic, mode))
+ scores.sort(key=lambda s: s[0], reverse=True)
+ confidence = float(np.clip((scores[0][0] - scores[1][0]) / 0.2, 0, 1))
+ return scores[0][1], scores[0][2], confidence
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", action="append", required=True)
+ args = ap.parse_args()
+ mixes = []
+ sr = None
+ for path in args.input:
+ audio, file_sr = read_wav(path)
+ if sr is None:
+ sr = file_sr
+ elif file_sr != sr:
+ fail(f"sample rate mismatch: {file_sr} vs {sr}")
+ mixes.append(audio.mean(axis=0))
+ n = min(m.size for m in mixes)
+ if n == 0:
+ fail("empty wav")
+ mono = np.sum([m[:n] for m in mixes], axis=0)
+ tonic, mode, confidence = detect_key(mono, sr)
+ emit(type="key", tonic=tonic, mode=mode, confidence=confidence)
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except SystemExit:
+ raise
+ except Exception as e:
+ fail(e)
diff --git a/python/tests/test_key.py b/python/tests/test_key.py
new file mode 100644
index 0000000..46183b7
--- /dev/null
+++ b/python/tests/test_key.py
@@ -0,0 +1,108 @@
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+import wave
+from pathlib import Path
+
+import numpy as np
+
+PYTHON_DIR = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(PYTHON_DIR))
+
+from separate import save_wav_f32 # noqa: E402
+
+SR = 44100
+
+
+def note_freq(midi):
+ return 440.0 * 2 ** ((midi - 69) / 12)
+
+
+def tone(midi, dur):
+ # fundamental + octave only: higher partials (3rd = a fifth above) would smear
+ # extra pitch classes and make the test signals key-ambiguous
+ t = np.arange(int(SR * dur)) / SR
+ f = note_freq(midi)
+ return np.sin(2 * np.pi * f * t) + 0.5 * np.sin(2 * np.pi * 2 * f * t)
+
+
+def chord(midis, dur):
+ return sum(tone(m, dur) for m in midis)
+
+
+def a_minor_signal():
+ # Am (A3 C4 E4) alternating with Dm/E context, plus the A natural minor scale
+ am = chord([57, 60, 64], 1.0)
+ dm = chord([62, 65, 69], 1.0)
+ em = chord([64, 67, 71], 1.0)
+ scale = np.concatenate([tone(m, 0.25) for m in [57, 59, 60, 62, 64, 65, 67, 69]])
+ return np.concatenate([am, dm, am, em, am, dm, am, am, scale]).astype(np.float32)
+
+
+def g_major_signal():
+ # sustained G triad over a G bass, framed by the G major scale and a G-C-D-G
+ # cadence so the tonic outweighs the dominant (D) that the triad's 5th suggests
+ g = chord([43, 55, 59, 62], 3.0)
+ c = chord([48, 55, 60, 64], 1.0)
+ d = chord([50, 57, 62, 66], 1.0)
+ scale = np.concatenate([tone(m, 0.25) for m in [55, 57, 59, 60, 62, 64, 66, 67]])
+ return np.concatenate([g, scale, c, d, g]).astype(np.float32)
+
+
+def write_wav16(path, mono):
+ pcm = (np.clip(mono / np.max(np.abs(mono)), -1, 1) * 0.5 * 32767).astype("<i2")
+ with wave.open(str(path), "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(SR)
+ w.writeframes(pcm.tobytes())
+
+
+def run_cli(*inputs):
+ cmd = [sys.executable, str(PYTHON_DIR / "key.py")]
+ for p in inputs:
+ cmd += ["--input", str(p)]
+ return subprocess.run(cmd, capture_output=True, text=True)
+
+
+class KeyDetectionTest(unittest.TestCase):
+ def test_a_minor_chord_progression(self):
+ from key import detect_key
+
+ tonic, mode, conf = detect_key(a_minor_signal(), SR)
+ self.assertEqual((tonic, mode), (9, "minor"))
+ self.assertTrue(0 <= conf <= 1)
+
+ def test_g_major_triad(self):
+ from key import detect_key
+
+ tonic, mode, conf = detect_key(g_major_signal(), SR)
+ self.assertEqual((tonic, mode), (7, "major"))
+ self.assertTrue(0 <= conf <= 1)
+
+ def test_silence_fails(self):
+ with tempfile.TemporaryDirectory() as d:
+ p = Path(d) / "silence.wav"
+ save_wav_f32(str(p), np.zeros((1, SR * 2), dtype=np.float32), SR)
+ r = run_cli(p)
+ self.assertEqual(r.returncode, 1)
+ self.assertEqual(json.loads(r.stdout.strip().splitlines()[-1])["type"], "error")
+
+ def test_mixed_widths(self):
+ sig = g_major_signal()
+ with tempfile.TemporaryDirectory() as d:
+ a = Path(d) / "a16.wav"
+ b = Path(d) / "b32.wav"
+ write_wav16(a, sig)
+ save_wav_f32(str(b), (sig / np.max(np.abs(sig)) * 0.5)[None, :], SR)
+ r = run_cli(a, b)
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+ out = json.loads(r.stdout.strip().splitlines()[-1])
+ self.assertEqual(out["type"], "key")
+ self.assertEqual((out["tonic"], out["mode"]), (7, "major"))
+
+
+if __name__ == "__main__":
+ unittest.main()