mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented key analysis system
This commit is contained in:
1 parent
4e9472c14a
commit
b5b3dd04c3
7 files changed
+673
-1
No files matched your search
@@ -0,0 +1,182 @@
|
||||
"""Benchmark key detection (`core/key_detect.py`).
|
||||
|
||||
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
|
||||
compare rather than a pass/fail.
|
||||
|
||||
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
|
||||
python bench_key_detect.py ~/Music # files with a key TAG
|
||||
|
||||
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
|
||||
and the number to quote; the model never trained on it (see
|
||||
`train_key_model.py`). A folder's key tags were written by some other
|
||||
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
|
||||
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
|
||||
source) count once, by title.
|
||||
|
||||
Errors are classed the MIREX way, because they are not equally wrong for a
|
||||
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
|
||||
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
|
||||
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import warnings
|
||||
from collections import Counter
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from konduktor.adapters.rekordbox.projection import parse_key as parse_named # noqa: E402
|
||||
from konduktor.adapters.traktor.projection import parse_key as parse_wheel # noqa: E402
|
||||
from konduktor.core import key_detect # noqa: E402
|
||||
|
||||
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
|
||||
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
|
||||
|
||||
|
||||
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
|
||||
"""How a detected (wheel, mode) relates to the reference."""
|
||||
(dw, dm), (rw, rm) = det, ref
|
||||
if (dw, dm) == (rw, rm):
|
||||
return "exact"
|
||||
if dw == rw:
|
||||
return "relative"
|
||||
if dm == rm and (dw - rw) % 12 in (1, 11):
|
||||
return "fifth"
|
||||
if dm != rm:
|
||||
major, minor = (dw, rw) if dm == "major" else (rw, dw)
|
||||
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
|
||||
return "parallel"
|
||||
return "other"
|
||||
|
||||
|
||||
def parse_any(text: str) -> tuple[int, str] | None:
|
||||
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
|
||||
s = text.strip()
|
||||
w, m = parse_wheel(s)
|
||||
if w:
|
||||
return w, m
|
||||
s = re.sub(r"\s*(minor|min)$", "m", s, flags=re.I)
|
||||
s = re.sub(r"\s*(major|maj)$", "", s, flags=re.I)
|
||||
w, m = parse_named(s)
|
||||
return (w, m) if w else None
|
||||
|
||||
|
||||
def _tag_key(path: Path) -> tuple[str, str] | None:
|
||||
import mutagen
|
||||
|
||||
try:
|
||||
f = mutagen.File(path)
|
||||
except Exception:
|
||||
return None
|
||||
if not f or not f.tags:
|
||||
return None
|
||||
t = f.tags
|
||||
|
||||
def has(name: str) -> bool:
|
||||
try:
|
||||
return name in t
|
||||
except ValueError: # a Vorbis comment refuses an MP4-style atom name
|
||||
return False
|
||||
|
||||
key = title = None
|
||||
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
|
||||
if has(name):
|
||||
v = t[name]
|
||||
v = v.text[0] if hasattr(v, "text") else v[0]
|
||||
key = v.decode() if isinstance(v, bytes) else str(v)
|
||||
break
|
||||
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
|
||||
if has(name):
|
||||
v = t[name]
|
||||
title = str(v.text[0] if hasattr(v, "text") else v[0])
|
||||
break
|
||||
return (key, title or path.stem) if key else None
|
||||
|
||||
|
||||
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
seen, out = set(), []
|
||||
for root in roots:
|
||||
for dp, dirs, files in os.walk(root):
|
||||
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
|
||||
for name in sorted(files):
|
||||
p = Path(dp) / name
|
||||
if p.suffix.lower() not in AUDIO or name.startswith("."):
|
||||
continue
|
||||
tagged = _tag_key(p)
|
||||
if not tagged or not (ref := parse_any(tagged[0])):
|
||||
continue
|
||||
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
|
||||
if title not in seen:
|
||||
seen.add(title)
|
||||
out.append((p, ref, tagged[1]))
|
||||
return out
|
||||
|
||||
|
||||
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
out = []
|
||||
for f in sorted((gs / "annotations/key").glob("*.key")):
|
||||
name, mode = f.read_text().split()
|
||||
pc = key_detect.PITCH_NAMES.index({"C#": "C#", "Db": "C#", "D#": "Eb", "Gb": "F#",
|
||||
"G#": "Ab", "A#": "Bb"}.get(name, name))
|
||||
audio = gs / "audio" / f"{f.stem}.mp3"
|
||||
if audio.exists():
|
||||
out.append((audio, (key_detect.camelot_wheel(pc, mode), mode), f.stem))
|
||||
return out
|
||||
|
||||
|
||||
def _detect(path: Path):
|
||||
warnings.filterwarnings("ignore")
|
||||
try:
|
||||
r = key_detect.detect_key(str(path))
|
||||
except Exception as ex: # an undecodable file is reported, not fatal
|
||||
return None, str(ex)
|
||||
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
|
||||
|
||||
|
||||
def run(refs, label: str, verbose: bool) -> None:
|
||||
with ProcessPoolExecutor() as ex:
|
||||
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
|
||||
rels, misses = [], []
|
||||
for (path, ref, title), (det, err) in zip(refs, results):
|
||||
if det is None:
|
||||
print(f" could not analyse {title}: {err or 'silent / too short'}")
|
||||
continue
|
||||
rel = relation(det[:2], ref)
|
||||
rels.append(rel)
|
||||
if rel != "exact":
|
||||
misses.append((title, ref, det, rel))
|
||||
n = len(rels)
|
||||
if not n:
|
||||
print(f"{label}: nothing to score")
|
||||
return
|
||||
c = Counter(rels)
|
||||
print(f"\n{label}: {n} tracks")
|
||||
for k in WEIGHT:
|
||||
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
|
||||
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
|
||||
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
|
||||
if verbose:
|
||||
for title, ref, det, rel in misses:
|
||||
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
|
||||
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
|
||||
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
|
||||
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
|
||||
a = ap.parse_args()
|
||||
if not a.folders and not a.giantsteps:
|
||||
ap.error("give --giantsteps and/or folders")
|
||||
if a.giantsteps:
|
||||
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
|
||||
if a.folders:
|
||||
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
|
||||
sys.exit(0)
|
||||
@@ -54,6 +54,8 @@ datas += [
|
||||
("konduktor/stems/engine.json", "konduktor/stems"),
|
||||
("konduktor/stems/weights.json", "konduktor/stems"),
|
||||
]
|
||||
# The key-detection network's weights (konduktor/core/key_detect.py).
|
||||
datas += [("konduktor/core/key_model.npz", "konduktor/core")]
|
||||
|
||||
a = Analysis(
|
||||
["sidecar.py"],
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Musical key detection: a small convolutional network, run in numpy.
|
||||
|
||||
Why a network and not key profiles. The classic method — fold the spectrum
|
||||
into a 12-bin chroma vector and correlate it with a major / minor template —
|
||||
was benchmarked first on GiantSteps (604 Beatport previews, keys corrected by
|
||||
hand), over Krumhansl, Temperley, Sha'ath (KeyFinder) and Faraldo's EDM
|
||||
templates and every combination of octave range, compression and harmonic
|
||||
filtering tried: the best got 49.5% exactly right. A template sees only how
|
||||
much of each pitch class there is; a network also sees WHERE in pitch it is
|
||||
(the bass line, the pad, the lead) and learns from data what states a key.
|
||||
|
||||
The model follows Korzeniowski & Widmer, "End-to-end musical key estimation
|
||||
using a convolutional neural network" (EUSIPCO 2017): five 5x5 convolutions,
|
||||
then a per-frame dense layer over the whole pitch axis — a key is NOT
|
||||
pitch-invariant, so nothing pools over frequency — then 24 logits averaged
|
||||
over the track. ~76 k weights per network; `key_model.npz` holds an ensemble
|
||||
of three (logits averaged), trained by `backend/train_key_model.py` on the
|
||||
SEPARATE GiantSteps MTG dataset. torch is used only to train: the backend
|
||||
never imports it.
|
||||
|
||||
Measured (`bench_key_detect.py`, 2026-10-04): GiantSteps 69.4% exact, 83.4%
|
||||
harmonically mixable (exact, a fifth, or the relative key), MIREX 0.758 —
|
||||
about the published figure for this design. Against the key tags of 47 local
|
||||
files (Traktor's analysis, not ground truth) it agrees on 62%, 77% mixable.
|
||||
`confidence` tracks correctness (82% exact above 0.7, ~40% below 0.4) but even
|
||||
a low one is ten times better than chance, so a key is always returned for
|
||||
music; only silence and clips under 5 s get None.
|
||||
|
||||
Cost on a 6.7-minute track: CQT 0.1 s, the three networks 0.5 s — beside the
|
||||
decode, which the grid analysis shares.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
|
||||
SR = 22050
|
||||
HOP = 4096 # ~5.4 frames/s: key is a slow property
|
||||
BINS_PER_OCTAVE = 36 # three per semitone, so a detuned track still lands in one
|
||||
FMIN_NOTE = "C1"
|
||||
OCTAVES = 7 # C1..C8: the input window plus room to pitch-shift it
|
||||
# The network's input: C2..C7 (65 Hz - 2.1 kHz), where bass lines, pads and
|
||||
# leads state the key. The octave either side is only there so training can
|
||||
# shift the window by up to six semitones.
|
||||
WINDOW = (36, 216)
|
||||
|
||||
_MODEL = Path(__file__).with_name("key_model.npz")
|
||||
_TIME_CHUNK = 256 # frames per im2col block: bounds memory to tens of MB
|
||||
|
||||
PITCH_NAMES = ("C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KeyResult:
|
||||
pitch_class: int # tonic, 0 = C
|
||||
mode: Literal["major", "minor"]
|
||||
wheel: int # Camelot position 1-12, the generic model's key
|
||||
confidence: float # the network's probability for this key, 0-1
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return PITCH_NAMES[self.pitch_class] + ("m" if self.mode == "minor" else "")
|
||||
|
||||
|
||||
def camelot_wheel(pitch_class: int, mode: str) -> int:
|
||||
"""Camelot position: C major = 8B, A minor = 8A; one step = a fifth."""
|
||||
return (((7 * pitch_class) % 12 + (7 if mode == "major" else 4)) % 12) + 1
|
||||
|
||||
|
||||
def features(y: np.ndarray, sr: int = SR) -> np.ndarray:
|
||||
"""Log-magnitude constant-Q spectrogram, (OCTAVES * 36, frames), float32.
|
||||
|
||||
Normalised to the track's own loudest bin, so a quiet master and a loud
|
||||
one give the same picture. Training calls this same function."""
|
||||
import librosa
|
||||
|
||||
if sr != SR:
|
||||
y = librosa.resample(y, orig_sr=sr, target_sr=SR)
|
||||
C = np.abs(librosa.cqt(
|
||||
y, sr=SR, hop_length=HOP, fmin=librosa.note_to_hz(FMIN_NOTE),
|
||||
n_bins=OCTAVES * BINS_PER_OCTAVE, bins_per_octave=BINS_PER_OCTAVE, tuning=0.0,
|
||||
))
|
||||
peak = float(C.max()) or 1.0
|
||||
return np.log1p(1000.0 * C / peak).astype(np.float32)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _members() -> list[dict[str, np.ndarray]]:
|
||||
"""The ensemble: `key_model.npz` holds N networks as `m<i>.<param>`, plus
|
||||
`pool` (frequency bins averaged before the dense layer; 1 = none)."""
|
||||
with np.load(_MODEL) as z:
|
||||
flat = {k: z[k] for k in z.files}
|
||||
pool = int(flat.pop("pool"))
|
||||
members: dict[int, dict[str, np.ndarray]] = {}
|
||||
for k, v in flat.items():
|
||||
i, name = k.split(".", 1)
|
||||
members.setdefault(int(i[1:]), {})[name] = v.astype(np.float32)
|
||||
for m in members.values():
|
||||
m["pool"] = np.array(pool)
|
||||
return [members[i] for i in sorted(members)]
|
||||
|
||||
|
||||
def _elu(x: np.ndarray) -> np.ndarray:
|
||||
return np.where(x > 0, x, np.expm1(np.minimum(x, 0)))
|
||||
|
||||
|
||||
def _conv5(x: np.ndarray, w: np.ndarray, b: np.ndarray) -> np.ndarray:
|
||||
"""'same' 5x5 convolution (cross-correlation, as torch's Conv2d).
|
||||
x: (cin, F, T), w: (cout, cin, 5, 5) -> (cout, F, T)."""
|
||||
cin, f, t = x.shape
|
||||
xp = np.pad(x, ((0, 0), (2, 2), (2, 2)))
|
||||
out = np.empty((w.shape[0], f, t), np.float32)
|
||||
for t0 in range(0, t, _TIME_CHUNK):
|
||||
t1 = min(t, t0 + _TIME_CHUNK)
|
||||
view = np.lib.stride_tricks.sliding_window_view(xp[:, :, t0:t1 + 4], (5, 5), axis=(1, 2))
|
||||
out[:, :, t0:t1] = np.tensordot(w, view, axes=([1, 2, 3], [0, 3, 4]))
|
||||
return out + b[:, None, None]
|
||||
|
||||
|
||||
def _network(x: np.ndarray, w: dict[str, np.ndarray]) -> np.ndarray:
|
||||
"""One member's 24 logits, averaged over time. x: (1, F, T)."""
|
||||
n = sum(1 for k in w if k.startswith("conv") and k.endswith(".weight"))
|
||||
for i in range(n):
|
||||
x = _elu(_conv5(x, w[f"conv{i}.weight"], w[f"conv{i}.bias"]))
|
||||
pool = int(w["pool"]) # average within a semitone
|
||||
if pool > 1:
|
||||
f = x.shape[1] // pool * pool
|
||||
x = x[:, :f].reshape(x.shape[0], f // pool, pool, -1).mean(axis=2)
|
||||
dw = w["dense.weight"][..., 0] # (hid, ch, F)
|
||||
h = _elu(np.tensordot(dw, x, axes=([1, 2], [0, 1])) + w["dense.bias"][:, None])
|
||||
out = w["out.weight"][:, :, 0, 0] @ h + w["out.bias"][:, None] # (24, T)
|
||||
return out.mean(axis=1)
|
||||
|
||||
|
||||
def logits(spec: np.ndarray) -> np.ndarray:
|
||||
"""The ensemble's 24 logits — major C..B, then minor C..B — for a
|
||||
`features()` spectrogram: each member's, averaged."""
|
||||
x = spec[WINDOW[0]:WINDOW[1]][None]
|
||||
return np.mean([_network(x, w) for w in _members()], axis=0)
|
||||
|
||||
|
||||
def detect_key_samples(y: np.ndarray, sr: int) -> KeyResult | None:
|
||||
"""The key of decoded mono audio, or None for silence / too short to say."""
|
||||
if y.size < sr * 5 or not np.any(y):
|
||||
return None
|
||||
z = logits(features(y, sr)).astype(np.float64)
|
||||
p = np.exp(z - z.max())
|
||||
p /= p.sum()
|
||||
k = int(np.argmax(p))
|
||||
pc, mode = k % 12, ("minor" if k >= 12 else "major")
|
||||
return KeyResult(pc, mode, camelot_wheel(pc, mode), float(p[k]))
|
||||
|
||||
|
||||
def detect_key(audio_path: str) -> KeyResult | None:
|
||||
import librosa
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=SR, mono=True)
|
||||
return detect_key_samples(y, sr)
|
||||
Binary file not shown.
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Tests for key detection (`core/key_detect.py`) on synthetic audio.
|
||||
|
||||
Needs no audio files: every track is generated, so its key is KNOWN. These
|
||||
pin what `bench_key_detect.py` (real music) cannot: that all 24 keys come out
|
||||
— a wrong label order or wheel mapping would get exactly some of them wrong —
|
||||
that loudness and sample rate do not change the answer, that silence gives no
|
||||
key rather than a made-up one, and that the numpy network computes what was
|
||||
trained (the convolution against a direct reference implementation).
|
||||
|
||||
The progressions are cadences that state their key unambiguously (I-IV-V-I;
|
||||
i-iv-V-i with the raised leading tone). A pop I-V-vi-IV is deliberately NOT
|
||||
used: it spends a quarter of its time on the relative minor, and a model
|
||||
trained on dance music — 85% minor — fairly calls some of those minor.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from konduktor.core import key_detect # noqa: E402
|
||||
|
||||
SR = 22050
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
def tone(midi: int, dur: float, amp: float, harmonics: int = 6, sr: int = SR) -> np.ndarray:
|
||||
t = np.arange(int(dur * sr)) / sr
|
||||
f = 440.0 * 2 ** ((midi - 69) / 12)
|
||||
x = sum(np.sin(2 * np.pi * f * h * t) / h for h in range(1, harmonics + 1) if f * h < sr / 2)
|
||||
env = np.minimum(1, t / 0.01) * np.minimum(1, (dur - t) / 0.05)
|
||||
return amp * x * env
|
||||
|
||||
|
||||
MAJOR = [(0, "M"), (5, "M"), (7, "M"), (0, "M")] # I IV V I
|
||||
MINOR = [(0, "m"), (5, "m"), (7, "M"), (0, "m")] # i iv V i
|
||||
|
||||
|
||||
def song(tonic: int, mode: str, bars: int = 16, bpm: float = 124.0, sr: int = SR) -> np.ndarray:
|
||||
beat = 60.0 / bpm
|
||||
prog = MAJOR if mode == "major" else MINOR
|
||||
out = []
|
||||
for b in range(bars):
|
||||
root, q = prog[b % len(prog)]
|
||||
r = 48 + (tonic + root) % 12
|
||||
chord = sum(tone(r + 12 + i, 4 * beat, 0.12, sr=sr) for i in (0, 4 if q == "M" else 3, 7))
|
||||
bass = np.concatenate([tone(r - 12, beat, 0.3, 3, sr=sr) for _ in range(4)])
|
||||
n = min(len(chord), len(bass))
|
||||
out.append(chord[:n] + bass[:n])
|
||||
y = np.concatenate(out)
|
||||
return (y / np.abs(y).max() * 0.8).astype(np.float32)
|
||||
|
||||
|
||||
def name(pc: int, mode: str) -> str:
|
||||
return key_detect.PITCH_NAMES[pc] + ("m" if mode == "minor" else "")
|
||||
|
||||
|
||||
print("all 24 keys")
|
||||
for mode in ("major", "minor"):
|
||||
for pc in range(12):
|
||||
r = key_detect.detect_key_samples(song(pc, mode), SR)
|
||||
check(f"{name(pc, mode):4s} -> {r.name if r else None}",
|
||||
r is not None and (r.pitch_class, r.mode) == (pc, mode))
|
||||
if r:
|
||||
check(f"{name(pc, mode):4s} wheel {r.wheel}", r.wheel == key_detect.camelot_wheel(pc, mode))
|
||||
|
||||
print("the Camelot mapping")
|
||||
check("C major = 8B", key_detect.camelot_wheel(0, "major") == 8)
|
||||
check("A minor = 8A", key_detect.camelot_wheel(9, "minor") == 8)
|
||||
check("G major = 9B (a fifth up = one step)", key_detect.camelot_wheel(7, "major") == 9)
|
||||
check("F minor = 4A", key_detect.camelot_wheel(5, "minor") == 4)
|
||||
|
||||
print("invariance")
|
||||
y = song(2, "minor")
|
||||
base = key_detect.detect_key_samples(y, SR)
|
||||
quiet = key_detect.detect_key_samples(y * 0.05, SR)
|
||||
check("a quiet master gives the same key", quiet and quiet.name == base.name)
|
||||
check("...and the same confidence", quiet and abs(quiet.confidence - base.confidence) < 0.02,
|
||||
f"{base.confidence:.3f} vs {quiet and quiet.confidence:.3f}")
|
||||
hi = key_detect.detect_key_samples(song(2, "minor", sr=44100), 44100)
|
||||
check("44.1 kHz input gives the same key", hi and hi.name == base.name)
|
||||
check("confidence is a probability", 0.0 < base.confidence <= 1.0)
|
||||
|
||||
print("nothing to say")
|
||||
check("silence -> None", key_detect.detect_key_samples(np.zeros(SR * 30, np.float32), SR) is None)
|
||||
check("under 5 s -> None", key_detect.detect_key_samples(song(0, "major")[: SR * 3], SR) is None)
|
||||
|
||||
print("the numpy network")
|
||||
rng = np.random.default_rng(1)
|
||||
x = rng.standard_normal((3, 20, 300)).astype(np.float32) # > one time chunk, odd sizes
|
||||
w = rng.standard_normal((4, 3, 5, 5)).astype(np.float32)
|
||||
b = rng.standard_normal(4).astype(np.float32)
|
||||
got = key_detect._conv5(x, w, b)
|
||||
xp = np.pad(x, ((0, 0), (2, 2), (2, 2)))
|
||||
ref = np.zeros_like(got)
|
||||
for o in range(4):
|
||||
for i in range(3):
|
||||
for di in range(5):
|
||||
for dj in range(5):
|
||||
ref[o] += w[o, i, di, dj] * xp[i, di:di + 20, dj:dj + 300]
|
||||
ref[o] += b[o]
|
||||
check("5x5 'same' conv == direct cross-correlation", np.allclose(got, ref, atol=1e-3),
|
||||
f"max diff {np.abs(got - ref).max():.2e}")
|
||||
members = key_detect._members()
|
||||
check("the shipped model is an ensemble of >= 1 network", len(members) >= 1)
|
||||
spec = key_detect.features(y, SR)
|
||||
check("24 logits", key_detect.logits(spec).shape == (24,))
|
||||
|
||||
print("\nFAILED" if failed else "\nall key-detection tests passed")
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Train the key-detection network shipped as `konduktor/core/key_model.npz`.
|
||||
|
||||
NOT part of the app or of `run_tests.sh`: a dev tool, run when the model
|
||||
changes. Two steps in two environments, because the backend never imports
|
||||
torch and torch is only installed in the stem engine's venv:
|
||||
|
||||
# 0. the data (Beatport EDM previews, hand-annotated keys — ~2.9 GB):
|
||||
git clone https://github.com/GiantSteps/giantsteps-mtg-key-dataset DATA/mtg
|
||||
git clone https://github.com/GiantSteps/giantsteps-key-dataset DATA/gs
|
||||
(cd DATA/mtg && bash audio_dl.sh); (cd DATA/gs && bash audio_dl.sh)
|
||||
|
||||
# 1. features, with the app's own `key_detect.features` (backend venv)
|
||||
python train_key_model.py features DATA
|
||||
|
||||
# 2. train + export (engine venv: torch)
|
||||
../engine/.venv/bin/python train_key_model.py train DATA
|
||||
|
||||
The protocol is the literature's (Korzeniowski & Widmer 2017): TRAIN on
|
||||
GiantSteps MTG (1,159 tracks with one confident key), TEST on the separate
|
||||
GiantSteps key dataset (604) — `bench_key_detect.py` scores it. Choices made
|
||||
on a held-out 20% of MTG, three seeds each (2026-10-04):
|
||||
- the per-frame dense layer over the full pitch axis beat averaging each
|
||||
semitone's three bins before it (68.1% vs 66.9% on GiantSteps, val equal);
|
||||
- a fixed 30-epoch cosine schedule, keeping the LAST epoch: validation on
|
||||
~230 tracks is too noisy to pick an epoch from;
|
||||
- weight decay made no difference and is off.
|
||||
The shipped file is an ENSEMBLE of three seeds trained on all of MTG, their
|
||||
logits averaged — each costs ~0.2 s per six-minute track.
|
||||
|
||||
Augmentation: the input window (C2..C7) is shifted by up to six semitones
|
||||
inside the 7-octave spectrogram, and the label rotated with it, so every
|
||||
tonic is seen in every position; plus random 128-frame (~24 s) crops.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PC = {"C": 0, "C#": 1, "Db": 1, "D": 2, "D#": 3, "Eb": 3, "E": 4, "F": 5, "F#": 6,
|
||||
"Gb": 6, "G": 7, "G#": 8, "Ab": 8, "A": 9, "A#": 10, "Bb": 10, "B": 11}
|
||||
LO, HI, MAX_SHIFT = 36, 216, 6 # must match key_detect.WINDOW
|
||||
CROP, BATCH, EPOCHS, LR = 128, 16, 30, 1e-3
|
||||
SEEDS = (11, 12, 13)
|
||||
OUT = Path(__file__).parent / "konduktor" / "core" / "key_model.npz"
|
||||
|
||||
|
||||
def label(name: str, mode: str) -> int:
|
||||
"""Class index: major C..B = 0..11, minor C..B = 12..23 (key_detect's order)."""
|
||||
return PC[name] + (12 if mode == "minor" else 0)
|
||||
|
||||
|
||||
def mtg_labels(data: Path) -> dict[str, int]:
|
||||
"""MTG ids with ONE key annotated at the dataset's top confidence (2)."""
|
||||
out = {}
|
||||
for line in (data / "mtg/annotations/annotations.txt").read_text().splitlines()[1:]:
|
||||
parts = line.split("\t")
|
||||
if len(parts) < 3:
|
||||
continue
|
||||
m = re.fullmatch(r"([A-G][#b]?) (major|minor)", parts[1].strip())
|
||||
if m and parts[2].strip() == "2":
|
||||
out[f"{parts[0]}.LOFI"] = label(*m.groups())
|
||||
return out
|
||||
|
||||
|
||||
def gs_labels(data: Path) -> dict[str, int]:
|
||||
out = {}
|
||||
for f in (data / "gs/annotations/key").glob("*.key"):
|
||||
name, mode = f.read_text().split()
|
||||
out[f.stem] = label(name, mode)
|
||||
return out
|
||||
|
||||
|
||||
# ---- step 1: features (backend venv) ---------------------------------------
|
||||
|
||||
|
||||
def _feature_job(args):
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
import librosa
|
||||
import numpy as np
|
||||
from konduktor.core import key_detect
|
||||
|
||||
src, dst, md5 = args
|
||||
if dst.exists():
|
||||
return "cached"
|
||||
if not src.exists():
|
||||
return "missing"
|
||||
if hashlib.md5(src.read_bytes()).hexdigest() != md5:
|
||||
return "bad md5"
|
||||
y, sr = librosa.load(str(src), sr=key_detect.SR, mono=True)
|
||||
np.save(dst, key_detect.features(y, sr))
|
||||
return "ok"
|
||||
|
||||
|
||||
def features(data: Path) -> None:
|
||||
from collections import Counter
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
|
||||
for which in ("mtg", "gs"):
|
||||
out = data / "features" / which
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
jobs = [
|
||||
(data / which / "audio" / f"{m.stem}.mp3", out / f"{m.stem}.npy", m.read_text().split()[0])
|
||||
for m in sorted((data / which / "md5").iterdir())
|
||||
]
|
||||
with ProcessPoolExecutor() as ex:
|
||||
print(which, dict(Counter(ex.map(_feature_job, jobs, chunksize=4))), flush=True)
|
||||
|
||||
|
||||
# ---- step 2: train + export (engine venv) ----------------------------------
|
||||
|
||||
|
||||
def _net(torch):
|
||||
nn, F = torch.nn, torch.nn.functional
|
||||
|
||||
class Net(nn.Module):
|
||||
"""Five 5x5 convs (8 ch, ELU), a dense layer per frame over the whole
|
||||
pitch axis (48, ELU, dropout), 24 logits averaged over time.
|
||||
`key_detect._network` is this, in numpy."""
|
||||
|
||||
def __init__(self, ch=8, layers=5, hid=48):
|
||||
super().__init__()
|
||||
self.convs = nn.ModuleList(
|
||||
[nn.Conv2d(1 if i == 0 else ch, ch, 5, padding=2) for i in range(layers)])
|
||||
self.dense = nn.Conv2d(ch, hid, (HI - LO, 1))
|
||||
self.out = nn.Conv2d(hid, 24, 1)
|
||||
self.drop = nn.Dropout(0.3)
|
||||
|
||||
def forward(self, x): # (B, 1, F, T)
|
||||
for c in self.convs:
|
||||
x = F.elu(c(x))
|
||||
x = self.drop(F.elu(self.dense(x)))
|
||||
return self.out(x).mean((2, 3))
|
||||
|
||||
return Net
|
||||
|
||||
|
||||
def train(data: Path, seeds=SEEDS, out: Path = OUT) -> None:
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
Net = _net(torch)
|
||||
labels = mtg_labels(data)
|
||||
X, Y = [], []
|
||||
for stem, y in sorted(labels.items()):
|
||||
f = data / "features/mtg" / f"{stem}.npy"
|
||||
if f.exists():
|
||||
X.append(np.load(f))
|
||||
Y.append(y)
|
||||
print(f"training on {len(X)} tracks", flush=True)
|
||||
dev = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
arrays: dict[str, np.ndarray] = {"pool": np.array(1)}
|
||||
for m, seed in enumerate(seeds):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
net = Net().to(dev)
|
||||
opt = torch.optim.Adam(net.parameters(), LR)
|
||||
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, EPOCHS)
|
||||
order = list(range(len(X)))
|
||||
for ep in range(EPOCHS):
|
||||
net.train()
|
||||
random.shuffle(order)
|
||||
total = 0.0
|
||||
for i in range(0, len(order), BATCH):
|
||||
xb, yb = [], []
|
||||
for j in order[i:i + BATCH]:
|
||||
s = random.randint(-MAX_SHIFT, MAX_SHIFT)
|
||||
x = X[j][LO + 3 * s:HI + 3 * s]
|
||||
if x.shape[1] > CROP:
|
||||
o = random.randint(0, x.shape[1] - CROP)
|
||||
x = x[:, o:o + CROP]
|
||||
else:
|
||||
x = np.pad(x, ((0, 0), (0, CROP - x.shape[1])))
|
||||
xb.append(x)
|
||||
# The window moved UP s semitones, so the music moved DOWN.
|
||||
yb.append((Y[j] % 12 - s) % 12 + Y[j] // 12 * 12)
|
||||
xt = torch.from_numpy(np.stack(xb))[:, None].to(dev)
|
||||
loss = F.cross_entropy(net(xt), torch.tensor(yb).to(dev))
|
||||
opt.zero_grad()
|
||||
loss.backward()
|
||||
opt.step()
|
||||
total += loss.item()
|
||||
sched.step()
|
||||
print(f" seed {seed} epoch {ep + 1}/{EPOCHS} loss {total / (len(order) / BATCH):.3f}", flush=True)
|
||||
for k, v in net.state_dict().items():
|
||||
arrays[f"m{m}." + k.replace("convs.", "conv")] = v.detach().cpu().numpy().astype(np.float32)
|
||||
np.savez_compressed(out, **arrays)
|
||||
print(f"wrote {out} ({out.stat().st_size // 1024} KB, {len(seeds)} members)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("step", choices=("features", "train"))
|
||||
ap.add_argument("data", type=Path)
|
||||
a = ap.parse_args()
|
||||
if a.step == "features":
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
features(a.data)
|
||||
else:
|
||||
train(a.data)
|
||||
Reference in new issue
Block a user