Compare commits
6 Commits
a7dedd4306
...
m5-strummi
| Author | SHA1 | Date | |
|---|---|---|---|
| f1d55c4bcb | |||
| 760bad7435 | |||
| 7ec6b3274b | |||
| 8d366327e6 | |||
| fcc1cd2426 | |||
| 983102b588 |
@ -48,6 +48,6 @@ uv run ruff format --check
|
||||
- [x] **M1 – Extraktion und Stems**: Stufen 1 (ffmpeg 44.1 kHz stereo) und 2 (Demucs `htdemucs_ft` / `htdemucs_6s`, low-VRAM chunking mit segment/shifts, `instrumental.wav` und `vocals.wav`, SNR-Prüfung).
|
||||
- [x] **M2 – Gesang**: Stufe 3 (`whisper-large-v3` + `pyphen`-Silbentrennung mit proportionalem Timing), Stufe 4 (`torchcrepe-full` mit Medianhöhe & Oktavfehler-Korrektur), UltraStar-Export (`song.txt`) & Reader, Eval-Framework mit Timing-MAE, Pitch-Genauigkeit (strikt & oktav-äquivalent) und WER via `jiwer`.
|
||||
- [x] **M3 – Tempo-Map**: Stufe 5 (`beat_this` Beat- & Downbeat-Tracking mit `librosa`-Fallback), intelligente Segmentierung (Anker nur bei echten Tempowechseln), Metronom-Klick-Track-Synthese (`.cache/click_track.wav`), BPM/GAP-Ableitung für UltraStar.
|
||||
- [ ] **M4 – Akkorde**: Stufe 6 (Chordino / Transformer).
|
||||
- [ ] **M5 – Strumming**: Stufe 7 (librosa Onsets / Strumming-Muster).
|
||||
- [x] **M4 – Akkorde**: Stufe 6 (Harte-Notation, Beat-synchrone Quantisierung über Tempo-Map, `chordino` & `template` Backends, Tonarterkennung nach Krumhansl-Schmuckler in `meta.json`).
|
||||
- [x] **M5 – Strumming**: Stufe 7 (Onset-Erkennung auf Gitarren-/Instrumental-Stem, Spektralschwerpunkt- & Beatphasen-Gradient für Down/Up-Richtungsvorschlag, Beat-Raster-Quantisierung, Muster-Verdichtung `D . D U . U D U`, als `experimental` markiert).
|
||||
- [ ] **M6 – Härtung**: Fehlerbehandlung, Logging, Dokumentation, Beispielpaket.
|
||||
|
||||
@ -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"
|
||||
|
||||
@ -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))
|
||||
|
||||
@ -1,30 +1,226 @@
|
||||
"""Stage 7: Strumming pattern analysis -> strumming.json."""
|
||||
"""Stage 7: Strumming pattern analysis -> strumming.json (experimental)."""
|
||||
|
||||
import json
|
||||
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.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.tempo import sec_to_beat
|
||||
|
||||
|
||||
def estimate_strum_direction(
|
||||
audio: np.ndarray,
|
||||
sr: int,
|
||||
onset_sec: float,
|
||||
beat: float,
|
||||
) -> tuple[StrumDirection, float]:
|
||||
"""Estimate strumming direction (down vs up) from spectral centroid gradient and beat phase."""
|
||||
# Analyze 50ms window right after onset
|
||||
start_sample = int(onset_sec * sr)
|
||||
window_samples = int(sr * 0.05)
|
||||
end_sample = min(len(audio), start_sample + window_samples)
|
||||
|
||||
direction: StrumDirection = "down"
|
||||
confidence = 0.5
|
||||
|
||||
if end_sample - start_sample > 256:
|
||||
chunk = audio[start_sample:end_sample]
|
||||
# Compute spectral centroid
|
||||
centroids = librosa.feature.spectral_centroid(y=chunk, sr=sr, hop_length=128)[0]
|
||||
if len(centroids) >= 2:
|
||||
centroid_slope = centroids[-1] - centroids[0]
|
||||
# Downstrum hits bass strings first then treble (centroid moves higher or bass-dominant)
|
||||
if centroid_slope > 0:
|
||||
direction = "down"
|
||||
confidence += 0.1
|
||||
else:
|
||||
direction = "up"
|
||||
confidence += 0.1
|
||||
|
||||
# Beat phase prior: On-beats (integer beats) are predominantly down strums
|
||||
beat_frac = beat - np.floor(beat)
|
||||
# Close to on-beat (0.0): down strum
|
||||
if beat_frac < 0.25 or beat_frac > 0.75:
|
||||
if direction == "down":
|
||||
confidence = min(0.85, confidence + 0.15)
|
||||
else:
|
||||
direction = "down"
|
||||
confidence = 0.6
|
||||
# Close to off-beat (0.5): up strum
|
||||
elif 0.35 <= beat_frac <= 0.65:
|
||||
if direction == "up":
|
||||
confidence = min(0.85, confidence + 0.15)
|
||||
else:
|
||||
direction = "up"
|
||||
confidence = 0.6
|
||||
|
||||
return direction, round(confidence, 2)
|
||||
|
||||
|
||||
def aggregate_strum_patterns(
|
||||
events: list[StrumEvent],
|
||||
total_beats: float,
|
||||
grid: str = "8th",
|
||||
pattern_beats: float = 4.0,
|
||||
section_beats: float = 16.0,
|
||||
) -> list[StrumPattern]:
|
||||
"""Condense discrete strumming events into representative pattern strings (e.g. 'D . D U . U D U')."""
|
||||
if not events:
|
||||
return []
|
||||
|
||||
grid_step = 0.5 if grid == "8th" else 0.25
|
||||
slots_per_pattern = int(round(pattern_beats / grid_step))
|
||||
|
||||
patterns: list[StrumPattern] = []
|
||||
num_sections = int(np.ceil(total_beats / section_beats))
|
||||
|
||||
for sec_idx in range(num_sections):
|
||||
sec_start = sec_idx * section_beats
|
||||
sec_end = min(total_beats, sec_start + section_beats)
|
||||
|
||||
# Gather events in this section
|
||||
sec_events = [e for e in events if sec_start <= e.beat < sec_end]
|
||||
if not sec_events:
|
||||
continue
|
||||
|
||||
# Vote for each slot in the pattern (modulo pattern_beats)
|
||||
slot_votes: list[list[str]] = [[] for _ in range(slots_per_pattern)]
|
||||
for e in sec_events:
|
||||
rel_beat = (e.beat - sec_start) % pattern_beats
|
||||
slot_idx = int(round(rel_beat / grid_step)) % slots_per_pattern
|
||||
symbol = "D" if e.direction == "down" else "U"
|
||||
slot_votes[slot_idx].append(symbol)
|
||||
|
||||
pattern_tokens = []
|
||||
for votes in slot_votes:
|
||||
if votes:
|
||||
# Majority symbol
|
||||
symbol = "D" if votes.count("D") >= votes.count("U") else "U"
|
||||
pattern_tokens.append(symbol)
|
||||
else:
|
||||
pattern_tokens.append(".")
|
||||
|
||||
pattern_str = " ".join(pattern_tokens)
|
||||
patterns.append(
|
||||
StrumPattern(
|
||||
start_beat=round(sec_start, 2),
|
||||
end_beat=round(sec_end, 2),
|
||||
pattern=pattern_str,
|
||||
grid=grid,
|
||||
)
|
||||
)
|
||||
|
||||
return patterns
|
||||
|
||||
|
||||
class StrummingStage(Stage):
|
||||
"""Stage 7 detects strumming onsets and patterns on the guitar/instrumental stem."""
|
||||
|
||||
name = "s7_strumming"
|
||||
version = "1.0.0"
|
||||
model_name = "librosa-onsets"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s5_tempo"]
|
||||
|
||||
def __init__(self, grid: str = "8th"):
|
||||
self.grid = grid
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [
|
||||
ctx.stems_dir / "instrumental.wav",
|
||||
ctx.output_dir / "tempo.json",
|
||||
]
|
||||
guitar_path = ctx.stems_dir / "guitar.wav"
|
||||
inst_path = ctx.stems_dir / "instrumental.wav"
|
||||
if guitar_path.exists():
|
||||
return [guitar_path, ctx.output_dir / "tempo.json"]
|
||||
return [inst_path, ctx.output_dir / "tempo.json"]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.output_dir / "strumming.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {"grid": "8th"}
|
||||
return {
|
||||
"grid": self.grid,
|
||||
"status": "experimental",
|
||||
"hop_length": 512,
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
# Implementation in M5
|
||||
raise NotImplementedError("Stage s7_strumming will be implemented in M5.")
|
||||
audio_path, tempo_path = self.get_inputs(ctx)
|
||||
if not audio_path.exists():
|
||||
raise FileNotFoundError(f"Input audio for strumming not found: {audio_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(audio_path), dtype="float32")
|
||||
mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data
|
||||
|
||||
params = self.get_params(ctx)
|
||||
grid = params.get("grid", "8th")
|
||||
grid_step = 0.5 if grid == "8th" else 0.25
|
||||
|
||||
# Detect onsets
|
||||
onset_env = librosa.onset.onset_strength(y=mono_audio, sr=sr, hop_length=512)
|
||||
onset_frames = librosa.onset.onset_detect(
|
||||
onset_envelope=onset_env,
|
||||
sr=sr,
|
||||
hop_length=512,
|
||||
backtrack=True,
|
||||
)
|
||||
onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=512)
|
||||
|
||||
# Normalize onset envelope for strength computation
|
||||
max_env = float(np.max(onset_env)) if len(onset_env) > 0 and np.max(onset_env) > 0 else 1.0
|
||||
|
||||
# Map onsets onto beat grid
|
||||
raw_events_by_grid: dict[float, StrumEvent] = {}
|
||||
|
||||
for frame_idx, t_sec in zip(onset_frames, onset_times, strict=False):
|
||||
beat = sec_to_beat(float(t_sec), tempo_doc)
|
||||
if beat < 0:
|
||||
continue
|
||||
|
||||
quantized_beat = round(beat / grid_step) * grid_step
|
||||
strength = float(np.clip(onset_env[frame_idx] / max_env, 0.1, 1.0))
|
||||
direction, conf = estimate_strum_direction(mono_audio, sr, float(t_sec), quantized_beat)
|
||||
|
||||
# If multiple onsets fall on the same grid slot, keep the strongest
|
||||
if quantized_beat not in raw_events_by_grid or strength > raw_events_by_grid[quantized_beat].strength:
|
||||
raw_events_by_grid[quantized_beat] = StrumEvent(
|
||||
beat=round(quantized_beat, 3),
|
||||
direction=direction,
|
||||
strength=round(strength, 2),
|
||||
confidence=conf,
|
||||
source="auto",
|
||||
)
|
||||
|
||||
events = sorted(raw_events_by_grid.values(), key=lambda e: e.beat)
|
||||
|
||||
total_duration = sf.info(str(audio_path)).duration
|
||||
total_beats = sec_to_beat(total_duration, tempo_doc)
|
||||
|
||||
patterns = aggregate_strum_patterns(events, total_beats, grid=grid)
|
||||
|
||||
doc = StrummingDocument(
|
||||
schema_version="1.0",
|
||||
generated_by=GeneratedBy(
|
||||
stage=self.name,
|
||||
model=self.model_name,
|
||||
model_version=self.version,
|
||||
params=params,
|
||||
),
|
||||
events=events,
|
||||
patterns=patterns,
|
||||
)
|
||||
|
||||
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(doc.model_dump_json(indent=2))
|
||||
|
||||
75
tests/test_chords.py
Normal file
75
tests/test_chords.py
Normal file
@ -0,0 +1,75 @@
|
||||
"""Unit tests for Harte chord parsing, key detection, and template chord recognition."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.pipeline.s6_chords import estimate_key, extract_chords_template, parse_harte_chord
|
||||
|
||||
|
||||
def test_parse_harte_chord_labels():
|
||||
# Major triad
|
||||
root, quality, bass = parse_harte_chord("C")
|
||||
assert root == "C"
|
||||
assert quality == "maj"
|
||||
assert bass is None
|
||||
|
||||
# Minor triad
|
||||
root, quality, bass = parse_harte_chord("Am")
|
||||
assert root == "A"
|
||||
assert quality == "min"
|
||||
assert bass is None
|
||||
|
||||
# Dominant 7th
|
||||
root, quality, bass = parse_harte_chord("G7")
|
||||
assert root == "G"
|
||||
assert quality == "7"
|
||||
assert bass is None
|
||||
|
||||
# Sus4
|
||||
root, quality, bass = parse_harte_chord("Dsus4")
|
||||
assert root == "D"
|
||||
assert quality == "sus4"
|
||||
assert bass is None
|
||||
|
||||
# Slash chord
|
||||
root, quality, bass = parse_harte_chord("F/A")
|
||||
assert root == "F"
|
||||
assert quality == "maj"
|
||||
assert bass == "A"
|
||||
|
||||
# No chord
|
||||
root, quality, bass = parse_harte_chord("N")
|
||||
assert root is None
|
||||
assert quality is None
|
||||
assert bass is None
|
||||
|
||||
|
||||
def test_estimate_key():
|
||||
# Synthetic C major profile (peaks at C, E, G -> indices 0, 4, 7)
|
||||
c_maj_chroma = np.zeros(12)
|
||||
c_maj_chroma[0] = 5.0
|
||||
c_maj_chroma[4] = 4.0
|
||||
c_maj_chroma[7] = 4.5
|
||||
assert estimate_key(c_maj_chroma) == "C"
|
||||
|
||||
# Synthetic A minor profile (peaks at A, C, E -> indices 9, 0, 4)
|
||||
a_min_chroma = np.zeros(12)
|
||||
a_min_chroma[9] = 5.0
|
||||
a_min_chroma[0] = 4.0
|
||||
a_min_chroma[4] = 4.5
|
||||
assert estimate_key(a_min_chroma) == "Am"
|
||||
|
||||
|
||||
def test_extract_chords_template_synthetic():
|
||||
sr = 22050
|
||||
duration = 1.0
|
||||
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
|
||||
|
||||
# Synthesize C major: C4 (261.63), E4 (329.63), G4 (392.00)
|
||||
c_chord = (np.sin(2 * np.pi * 261.63 * t) + np.sin(2 * np.pi * 329.63 * t) + np.sin(2 * np.pi * 392.00 * t)).astype(
|
||||
np.float32
|
||||
)
|
||||
|
||||
raw_chords = extract_chords_template(c_chord, sr)
|
||||
labels = [ch for _, ch in raw_chords]
|
||||
# Dominant detected chord should be "C"
|
||||
assert labels.count("C") > len(labels) * 0.5
|
||||
76
tests/test_pipeline_m4.py
Normal file
76
tests/test_pipeline_m4.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Integration test for Milestone 4 (Stage 6 Beat-Quantized Chord Recognition)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s6_chords import ChordsStage
|
||||
from songsplit.schema.chords import ChordsDocument
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
|
||||
|
||||
def test_m4_chords_stage_pipeline(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
stems_dir = song_dir / "stems"
|
||||
stems_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Synthesize 4.0s instrumental audio:
|
||||
# 2.0s C major (261.63, 329.63, 392.00) + 2.0s A minor (220.0, 261.63, 329.63)
|
||||
sr = 22050
|
||||
t_half = np.linspace(0, 2.0, int(sr * 2.0), endpoint=False)
|
||||
|
||||
c_major = (
|
||||
np.sin(2 * np.pi * 261.63 * t_half) + np.sin(2 * np.pi * 329.63 * t_half) + np.sin(2 * np.pi * 392.00 * t_half)
|
||||
).astype(np.float32)
|
||||
|
||||
a_minor = (
|
||||
np.sin(2 * np.pi * 220.00 * t_half) + np.sin(2 * np.pi * 261.63 * t_half) + np.sin(2 * np.pi * 329.63 * t_half)
|
||||
).astype(np.float32)
|
||||
|
||||
inst_audio = np.concatenate([c_major, a_minor])
|
||||
inst_wav = stems_dir / "instrumental.wav"
|
||||
sf.write(str(inst_wav), inst_audio, sr)
|
||||
|
||||
# 2. Prepare tempo.json: 120 BPM starting at 0.0s (0.5s per beat)
|
||||
# 4.0s = 8 beats total (0.0 to 4.0 beat is C, 4.0 to 8.0 beat is Am)
|
||||
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.0, beat=0.0, bpm=120.0)])
|
||||
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
|
||||
|
||||
# 3. Prepare meta.json
|
||||
meta = MetaDocument(
|
||||
title="Chord Test Song",
|
||||
artist="Test Pianist",
|
||||
duration_sec=4.0,
|
||||
source_file=SourceFileInfo(path=str(inst_wav), sha256="fakehash", size_bytes=len(inst_audio)),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# 4. Run ChordsStage with template backend
|
||||
ctx = PipelineContext(source_file=inst_wav, output_dir=song_dir)
|
||||
stage = ChordsStage(backend="template")
|
||||
stage.run(ctx)
|
||||
|
||||
chords_json = song_dir / "chords.json"
|
||||
assert chords_json.exists()
|
||||
|
||||
with open(chords_json, encoding="utf-8") as f:
|
||||
doc = ChordsDocument.model_validate(json.load(f))
|
||||
|
||||
assert len(doc.chords) >= 1
|
||||
labels = [c.label for c in doc.chords]
|
||||
assert "C" in labels or "Am" in labels
|
||||
|
||||
# Check beat-based timing
|
||||
for ch in doc.chords:
|
||||
assert ch.start_beat >= 0.0
|
||||
assert ch.end_beat > ch.start_beat
|
||||
assert ch.confidence > 0.0
|
||||
|
||||
# 5. Verify meta.json updated with key
|
||||
updated_meta = ctx.load_or_init_meta()
|
||||
assert updated_meta.key in ("C", "Am")
|
||||
77
tests/test_pipeline_m5.py
Normal file
77
tests/test_pipeline_m5.py
Normal file
@ -0,0 +1,77 @@
|
||||
"""Integration test for Milestone 5 (Stage 7 Strumming Analysis)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s7_strumming import StrummingStage
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.strumming import StrummingDocument
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
|
||||
|
||||
def test_m5_strumming_pipeline(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
stems_dir = song_dir / "stems"
|
||||
stems_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Synthesize 4.0s audio with strumming acoustic pulses
|
||||
sr = 22050
|
||||
duration_sec = 4.0
|
||||
audio = np.zeros(int(sr * duration_sec), dtype=np.float32)
|
||||
|
||||
# Pulses every 0.25s (8th notes at 120 BPM: 0.5s per quarter beat -> 0.25s per 8th note)
|
||||
pulse_len = int(sr * 0.05)
|
||||
t_pulse = np.linspace(0, 0.05, pulse_len, endpoint=False)
|
||||
pulse = (np.sin(2 * np.pi * 350.0 * t_pulse) * np.exp(-t_pulse / 0.01)).astype(np.float32)
|
||||
|
||||
for onset_t in np.arange(0.25, 3.75, 0.25):
|
||||
idx = int(onset_t * sr)
|
||||
audio[idx : idx + pulse_len] += pulse
|
||||
|
||||
guitar_wav = stems_dir / "guitar.wav"
|
||||
sf.write(str(guitar_wav), audio, sr)
|
||||
|
||||
# 2. Prepare tempo.json at 120 BPM starting at 0.0s
|
||||
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.0, beat=0.0, bpm=120.0)])
|
||||
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
|
||||
|
||||
# 3. Prepare meta.json
|
||||
meta = MetaDocument(
|
||||
title="Strumming Test Song",
|
||||
artist="Test Guitarist",
|
||||
duration_sec=duration_sec,
|
||||
source_file=SourceFileInfo(path=str(guitar_wav), sha256="fakehash", size_bytes=len(audio)),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# 4. Run StrummingStage
|
||||
ctx = PipelineContext(source_file=guitar_wav, output_dir=song_dir)
|
||||
stage = StrummingStage(grid="8th")
|
||||
stage.run(ctx)
|
||||
|
||||
strum_json = song_dir / "strumming.json"
|
||||
assert strum_json.exists()
|
||||
|
||||
with open(strum_json, encoding="utf-8") as f:
|
||||
doc = StrummingDocument.model_validate(json.load(f))
|
||||
|
||||
assert len(doc.events) > 0
|
||||
for e in doc.events:
|
||||
# Quantized to 8th note grid (multiples of 0.5 beats)
|
||||
assert (e.beat * 2).is_integer()
|
||||
assert e.direction in ("down", "up")
|
||||
assert 0.0 <= e.strength <= 1.0
|
||||
assert 0.0 <= e.confidence <= 1.0
|
||||
|
||||
# Verify marked as experimental in generated_by metadata
|
||||
assert doc.generated_by is not None
|
||||
assert doc.generated_by.params.get("status") == "experimental"
|
||||
|
||||
# Patterns generated
|
||||
assert len(doc.patterns) > 0
|
||||
assert doc.patterns[0].grid == "8th"
|
||||
39
tests/test_strumming.py
Normal file
39
tests/test_strumming.py
Normal file
@ -0,0 +1,39 @@
|
||||
"""Unit tests for strumming direction estimation and pattern aggregation."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.pipeline.s7_strumming import aggregate_strum_patterns, estimate_strum_direction
|
||||
from songsplit.schema.strumming import StrumEvent
|
||||
|
||||
|
||||
def test_estimate_strum_direction_phase_prior():
|
||||
sr = 22050
|
||||
audio = np.random.randn(sr).astype(np.float32)
|
||||
|
||||
# On-beat (beat 0.0) -> down
|
||||
dir_down, conf_down = estimate_strum_direction(audio, sr, onset_sec=0.1, beat=0.0)
|
||||
assert dir_down == "down"
|
||||
assert conf_down >= 0.5
|
||||
|
||||
# Off-beat (beat 0.5) -> up
|
||||
dir_up, conf_up = estimate_strum_direction(audio, sr, onset_sec=0.1, beat=0.5)
|
||||
assert dir_up == "up"
|
||||
assert conf_up >= 0.5
|
||||
|
||||
|
||||
def test_aggregate_strum_patterns_island_strum():
|
||||
# Famous "island strum": D . D U . U D U (slots: 0, 1, 2, 3, 4, 5, 6, 7 on 8th grid)
|
||||
# slots: 0.0 (D), 1.0 (D), 1.5 (U), 2.5 (U), 3.0 (D), 3.5 (U)
|
||||
events = [
|
||||
StrumEvent(beat=0.0, direction="down", strength=0.9, confidence=0.8),
|
||||
StrumEvent(beat=1.0, direction="down", strength=0.8, confidence=0.8),
|
||||
StrumEvent(beat=1.5, direction="up", strength=0.7, confidence=0.7),
|
||||
StrumEvent(beat=2.5, direction="up", strength=0.7, confidence=0.7),
|
||||
StrumEvent(beat=3.0, direction="down", strength=0.8, confidence=0.8),
|
||||
StrumEvent(beat=3.5, direction="up", strength=0.7, confidence=0.7),
|
||||
]
|
||||
|
||||
patterns = aggregate_strum_patterns(events, total_beats=4.0, grid="8th", pattern_beats=4.0, section_beats=4.0)
|
||||
assert len(patterns) == 1
|
||||
assert patterns[0].pattern == "D . D U . U D U"
|
||||
assert patterns[0].grid == "8th"
|
||||
21
uv.lock
generated
21
uv.lock
generated
@ -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" }
|
||||
|
||||
Reference in New Issue
Block a user