feat(chords): implement stage 6 beat-synchronous chord recognition and key detection

This commit is contained in:
2026-11-02 11:00:06 +01:00
parent a7dedd4306
commit 983102b588
3 changed files with 304 additions and 4 deletions

View File

@ -19,6 +19,7 @@ dependencies = [
"scipy>=1.12.0",
"jiwer>=3.0.0",
"beat-this>=1.1.0",
"chord-extractor>=0.1.3",
]
[project.optional-dependencies]
@ -54,6 +55,9 @@ explicit = true
torch = { index = "pytorch-cpu" }
torchaudio = { index = "pytorch-cpu" }
[tool.uv.extra-build-dependencies]
vamp = ["numpy"]
[tool.ruff]
line-length = 120
target-version = "py312"

View File

@ -1,18 +1,173 @@
"""Stage 6: Chord recognition -> chords.json."""
"""Stage 6: Chord recognition -> chords.json with beat-synchronous quantization."""
import json
import re
from pathlib import Path
from typing import Any
import librosa
import numpy as np
import soundfile as sf
from songsplit.pipeline.runner import PipelineContext, Stage
from songsplit.schema.base import GeneratedBy
from songsplit.schema.chords import ChordEvent, ChordsDocument
from songsplit.schema.tempo import TempoDocument
from songsplit.tempo import beat_to_sec, sec_to_beat
PITCH_CLASSES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def parse_harte_chord(label: str) -> tuple[str | None, str | None, str | None]:
"""Parse Harte chord label into (root, quality, bass).
Examples:
- 'C' -> ('C', 'maj', None)
- 'Am' -> ('A', 'min', None)
- 'G7' -> ('G', '7', None)
- 'Dsus4' -> ('D', 'sus4', None)
- 'F/A' -> ('F', 'maj', 'A')
- 'N' -> (None, None, None)
"""
clean = label.strip()
if not clean or clean.upper() in ("N", "NONE", "NO CHORD"):
return None, None, None
# Check for bass note (slash chord): F/A
bass = None
if "/" in clean:
parts = clean.split("/", 1)
clean = parts[0]
bass = parts[1].strip()
# Match Root (e.g. C, C#, Db, Eb, etc.)
match = re.match(r"^([A-G][#b]?)(.*)$", clean)
if not match:
return clean, None, bass
root, rest = match.groups()
# Determine quality
rest = rest.strip()
if not rest or rest == "maj":
quality = "maj"
elif rest in ("m", "min"):
quality = "min"
elif rest in ("7", "dom7"):
quality = "7"
elif rest in ("m7", "min7"):
quality = "min7"
elif rest in ("maj7", "M7"):
quality = "maj7"
elif "sus4" in rest:
quality = "sus4"
elif "sus2" in rest:
quality = "sus2"
elif "dim" in rest:
quality = "dim"
elif "aug" in rest:
quality = "aug"
else:
quality = rest
return root, quality, bass
# Krumhansl-Schmuckler Key Profiles for key detection
MAJOR_PROFILE = 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_PROFILE = 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 estimate_key(chroma_mean: np.ndarray) -> str:
"""Estimate musical key from mean chromagram profile."""
best_key = "C"
best_corr = -1.0
chroma_norm = chroma_mean - np.mean(chroma_mean)
for i, pc in enumerate(PITCH_CLASSES):
# Major correlation
maj_roll = np.roll(MAJOR_PROFILE, i)
maj_norm = maj_roll - np.mean(maj_roll)
corr_maj = float(np.corrcoef(chroma_norm, maj_norm)[0, 1])
if corr_maj > best_corr:
best_corr = corr_maj
best_key = f"{pc}"
# Minor correlation
min_roll = np.roll(MINOR_PROFILE, i)
min_norm = min_roll - np.mean(min_roll)
corr_min = float(np.corrcoef(chroma_norm, min_norm)[0, 1])
if corr_min > best_corr:
best_corr = corr_min
best_key = f"{pc}m"
return best_key
def extract_chords_template(audio_data: np.ndarray, sr: int) -> list[tuple[float, str]]:
"""Chroma-based chord template recognition as baseline/comparison."""
if audio_data.ndim > 1:
audio_data = audio_data.mean(axis=-1)
# Compute Chroma CQT
hop_length = 2048
chroma = librosa.feature.chroma_cqt(y=audio_data, sr=sr, hop_length=hop_length)
times = librosa.frames_to_time(np.arange(chroma.shape[1]), sr=sr, hop_length=hop_length)
# 12 Major and 12 Minor chord templates
templates: list[tuple[str, np.ndarray]] = []
for i, root in enumerate(PITCH_CLASSES):
# Major triad: root, +4, +7
maj = np.zeros(12)
maj[i] = 1.0
maj[(i + 4) % 12] = 1.0
maj[(i + 7) % 12] = 1.0
templates.append((root, maj / np.linalg.norm(maj)))
# Minor triad: root, +3, +7
min_t = np.zeros(12)
min_t[i] = 1.0
min_t[(i + 3) % 12] = 1.0
min_t[(i + 7) % 12] = 1.0
templates.append((f"{root}m", min_t / np.linalg.norm(min_t)))
raw_chords: list[tuple[float, str]] = []
for t_idx, t_sec in enumerate(times):
frame = chroma[:, t_idx]
norm = np.linalg.norm(frame)
if norm < 1e-4:
raw_chords.append((float(t_sec), "N"))
continue
frame_norm = frame / norm
best_chord = "N"
best_sim = -1.0
for chord_name, template in templates:
sim = float(np.dot(frame_norm, template))
if sim > best_sim:
best_sim = sim
best_chord = chord_name
raw_chords.append((float(t_sec), best_chord))
return raw_chords
class ChordsStage(Stage):
"""Stage 6 recognizes musical chords and quantizes them onto the beat grid."""
name = "s6_chords"
version = "1.0.0"
model_name = "chordino"
model_version = "1.0.0"
dependencies = ["s5_tempo"]
def __init__(self, backend: str = "chordino"):
self.backend = backend
self.model_name = backend
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "instrumental.wav",
@ -23,8 +178,128 @@ class ChordsStage(Stage):
return [ctx.output_dir / "chords.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"backend": "chordino"}
return {
"backend": self.backend,
"quantization": "beat",
}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M4
raise NotImplementedError("Stage s6_chords will be implemented in M4.")
inst_path, tempo_path = self.get_inputs(ctx)
if not inst_path.exists():
raise FileNotFoundError(f"Instrumental stem not found: {inst_path}")
if not tempo_path.exists():
raise FileNotFoundError(f"tempo.json not found: {tempo_path}")
with open(tempo_path, encoding="utf-8") as f:
tempo_doc = TempoDocument.model_validate(json.load(f))
audio_data, sr = sf.read(str(inst_path), dtype="float32")
# Estimate key and save in meta.json
mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data
chroma = librosa.feature.chroma_cqt(y=mono_audio, sr=sr)
detected_key = estimate_key(chroma.mean(axis=1))
meta = ctx.load_or_init_meta()
meta.key = detected_key
ctx.save_meta(meta)
params = self.get_params(ctx)
backend = params.get("backend", "chordino")
time_chord_pairs: list[tuple[float, str]] = []
if backend == "chordino":
try:
from chord_extractor import ChordExtractor
extractor = ChordExtractor()
chord_changes = extractor.extract(str(inst_path))
for change in chord_changes:
time_chord_pairs.append((float(change.timestamp), str(change.chord)))
except Exception:
# Fallback to template if chordino vamp is unavailable
time_chord_pairs = extract_chords_template(audio_data, sr)
self.model_name = "chroma-template"
else:
time_chord_pairs = extract_chords_template(audio_data, sr)
self.model_name = "chroma-template"
# Beat-synchronous quantization
info = sf.info(str(inst_path))
total_duration_sec = info.duration
total_beats = int(np.ceil(sec_to_beat(total_duration_sec, tempo_doc)))
total_beats = max(1, total_beats)
# Sample dominant chord per beat
beat_chords: list[str] = []
for b in range(total_beats):
b_start_sec = beat_to_sec(float(b), tempo_doc)
b_end_sec = beat_to_sec(float(b + 1), tempo_doc)
# Find chords active in this beat interval
active = [ch for t, ch in time_chord_pairs if b_start_sec <= t < b_end_sec]
if active:
# Most frequent chord in this beat
dom = max(set(active), key=active.count)
else:
# Chord active before b_start_sec
prior = [ch for t, ch in time_chord_pairs if t <= b_start_sec]
dom = prior[-1] if prior else "N"
beat_chords.append(dom)
# Merge consecutive identical beat chords into ChordEvent segments
chord_events: list[ChordEvent] = []
cur_chord = beat_chords[0]
cur_start_beat = 0.0
for b_idx in range(1, len(beat_chords)):
ch = beat_chords[b_idx]
if ch != cur_chord:
root, quality, bass = parse_harte_chord(cur_chord)
chord_events.append(
ChordEvent(
start_beat=cur_start_beat,
end_beat=float(b_idx),
label=cur_chord,
root=root,
quality=quality,
bass=bass,
confidence=0.85 if cur_chord != "N" else 0.5,
source="auto",
)
)
cur_chord = ch
cur_start_beat = float(b_idx)
# Final segment
root, quality, bass = parse_harte_chord(cur_chord)
chord_events.append(
ChordEvent(
start_beat=cur_start_beat,
end_beat=float(len(beat_chords)),
label=cur_chord,
root=root,
quality=quality,
bass=bass,
confidence=0.85 if cur_chord != "N" else 0.5,
source="auto",
)
)
chords_doc = ChordsDocument(
schema_version="1.0",
generated_by=GeneratedBy(
stage=self.name,
model=self.model_name,
model_version=self.version,
params=params,
),
chords=chord_events,
)
output_file = self.get_outputs(ctx)[0]
output_file.parent.mkdir(parents=True, exist_ok=True)
with open(output_file, "w", encoding="utf-8") as f:
f.write(chords_doc.model_dump_json(indent=2))

21
uv.lock generated
View File

@ -215,6 +215,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" },
]
[[package]]
name = "chord-extractor"
version = "0.1.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "librosa" },
{ name = "vamp" },
]
sdist = { url = "https://files.pythonhosted.org/packages/6b/5b/b17c85556c6c3dc28397de7a01b0af9b36fdfa13ffcaa21650da103fa795/chord-extractor-0.1.3.tar.gz", hash = "sha256:84ad0aaf3921f623b699332cb5dd0f509ade49dc46d3d08fdd981335173e52c3", size = 357948, upload-time = "2025-08-14T21:03:59.926Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ad/07/718ec09dd81e0734f85643e5d078a78386e38a0f353e57f622d267eb7563/chord_extractor-0.1.3-py3-none-any.whl", hash = "sha256:70313ad9668abd9fbd36aa4c182426264ceb563cf407b92b5842638d93a90607", size = 362699, upload-time = "2025-08-14T21:03:58.743Z" },
]
[[package]]
name = "click"
version = "8.5.0"
@ -1361,6 +1374,7 @@ version = "0.1.0"
source = { editable = "." }
dependencies = [
{ name = "beat-this" },
{ name = "chord-extractor" },
{ name = "demucs", version = "4.0.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'" },
{ name = "demucs", version = "4.1.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
{ name = "faster-whisper" },
@ -1389,6 +1403,7 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "beat-this", specifier = ">=1.1.0" },
{ name = "chord-extractor", specifier = ">=0.1.3" },
{ name = "demucs", specifier = ">=4.0.0" },
{ name = "faster-whisper", specifier = ">=1.0.0" },
{ name = "jiwer", specifier = ">=3.0.0" },
@ -1708,3 +1723,9 @@ sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909
wheels = [
{ url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" },
]
[[package]]
name = "vamp"
version = "1.1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/66/65/a54958777fa667ef881ceec18dd0b423b2ba2c77543060b21aff0e1dbcb6/vamp-1.1.0.tar.gz", hash = "sha256:d40e0916e958e2806d37920f903c2518cc46959a4f21e020737b6a48f6e7e82d", size = 107848, upload-time = "2015-07-08T19:14:21.005Z" }