feat(chords): implement stage 6 beat-synchronous chord recognition and key detection
This commit is contained in:
@ -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))
|
||||
|
||||
Reference in New Issue
Block a user