feat(tempo): implement tempo map building from beats and click track generator

This commit is contained in:
2026-11-02 10:53:19 +01:00
parent 6eb02fe576
commit cc5e2fe628
2 changed files with 210 additions and 2 deletions

View File

@ -1,4 +1,4 @@
"""Tempo-Map conversion between seconds and musical beats. """Tempo-Map conversion between seconds and musical beats and click track generation.
As defined in the concept: As defined in the concept:
- Vocals are in seconds - Vocals are in seconds
@ -8,7 +8,9 @@ As defined in the concept:
from bisect import bisect_right from bisect import bisect_right
from songsplit.schema.tempo import TempoAnchor, TempoDocument import numpy as np
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]: def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]:
@ -62,3 +64,146 @@ def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float:
anchor = anchors[idx] anchor = anchors[idx]
delta_beat = beat - anchor.beat delta_beat = beat - anchor.beat
return anchor.sec + delta_beat * (60.0 / anchor.bpm) return anchor.sec + delta_beat * (60.0 / anchor.bpm)
def build_tempo_map_from_beats(
beat_times: list[float] | np.ndarray,
downbeat_times: list[float] | np.ndarray | None = None,
min_tempo_change_bpm: float = 4.0,
min_beats_for_change: int = 6,
) -> TempoDocument:
"""Construct a clean TempoDocument from raw detected beat and downbeat timestamps.
Only inserts new anchors for true persistent tempo changes, keeping single-anchor
representation for songs with steady tempo.
"""
beats = np.sort(np.asarray(beat_times, dtype=np.float64))
if len(beats) < 2:
# Fallback default 120 BPM
return TempoDocument(
anchors=[TempoAnchor(sec=float(beats[0]) if len(beats) == 1 else 0.0, beat=0.0, bpm=120.0)],
time_signature=TimeSignature(numerator=4, denominator=4),
downbeat_offset=0,
)
# Determine time signature and downbeat offset
time_sig = TimeSignature(numerator=4, denominator=4)
downbeat_offset = 0
if downbeat_times is not None and len(downbeat_times) >= 2:
downbeats = np.sort(np.asarray(downbeat_times, dtype=np.float64))
# Match downbeats to nearest beat indices
downbeat_indices = []
for db in downbeats:
nearest_idx = int(np.argmin(np.abs(beats - db)))
if np.abs(beats[nearest_idx] - db) < 0.2: # within 200ms
downbeat_indices.append(nearest_idx)
if len(downbeat_indices) >= 2:
intervals = np.diff(downbeat_indices)
median_num = int(round(float(np.median(intervals))))
if median_num in (3, 4, 6):
time_sig = TimeSignature(numerator=median_num, denominator=4)
downbeat_offset = downbeat_indices[0] % time_sig.numerator
# Calculate initial tempo from the beginning of the song
ibis = np.diff(beats) # Inter-beat intervals in seconds
valid_mask = (ibis > 0.15) & (ibis < 2.0) # 30 to 400 BPM
clean_ibis = ibis[valid_mask]
if len(clean_ibis) == 0:
base_bpm = 120.0
else:
init_window = clean_ibis[: max(4, min_beats_for_change)]
base_bpm = float(np.median(60.0 / init_window))
# Segment into anchors if persistent tempo shifts occur
anchors = []
current_sec = float(beats[0])
current_beat = 0.0
current_bpm = base_bpm
anchors.append(
TempoAnchor(
sec=round(current_sec, 3),
beat=round(current_beat, 3),
bpm=round(current_bpm, 2),
)
)
# Detect sustained tempo changes across window
i = 0
while i <= len(ibis) - min_beats_for_change:
win_ibis = ibis[i : i + min_beats_for_change]
# Check all intervals are valid
if np.all((win_ibis > 0.15) & (win_ibis < 2.0)):
win_bpms = 60.0 / win_ibis
win_bpm = float(np.median(win_bpms))
win_std = float(np.std(win_bpms))
# Trigger change only when the new section is stable and genuinely different
if abs(win_bpm - current_bpm) >= min_tempo_change_bpm and win_std < (min_tempo_change_bpm * 0.75):
new_sec = float(beats[i])
# Calculate beat position from previous anchor
elapsed_sec = new_sec - current_sec
new_beat = current_beat + elapsed_sec * (current_bpm / 60.0)
current_sec = new_sec
current_beat = new_beat
current_bpm = win_bpm
anchors.append(
TempoAnchor(
sec=round(current_sec, 3),
beat=round(current_beat, 3),
bpm=round(current_bpm, 2),
)
)
i += min_beats_for_change
continue
i += 1
return TempoDocument(
anchors=anchors,
time_signature=time_sig,
downbeat_offset=downbeat_offset,
)
def generate_click_track(
tempo_map: TempoDocument,
duration_sec: float,
sr: int = 44100,
) -> np.ndarray:
"""Generate a click track waveform aligned to the TempoDocument.
Downbeats receive a distinct high click (1600 Hz), regular beats a low click (800 Hz).
"""
total_samples = int(duration_sec * sr)
click_audio = np.zeros(total_samples, dtype=np.float32)
click_len = int(sr * 0.02) # 20 ms
t_click = np.linspace(0, 0.02, click_len, endpoint=False)
envelope = np.exp(-t_click / 0.005).astype(np.float32)
high_click = (0.7 * np.sin(2 * np.pi * 1600.0 * t_click) * envelope).astype(np.float32)
low_click = (0.5 * np.sin(2 * np.pi * 800.0 * t_click) * envelope).astype(np.float32)
# Step through beats from 0 until duration_sec
num = tempo_map.time_signature.numerator
offset = tempo_map.downbeat_offset
beat = 0.0
while True:
sec = beat_to_sec(beat, tempo_map)
if sec > duration_sec:
break
if sec >= 0:
idx = int(sec * sr)
if idx + click_len <= total_samples:
# Check if this beat is a downbeat
is_downbeat = (int(round(beat)) % num) == (offset % num)
sample_click = high_click if is_downbeat else low_click
click_audio[idx : idx + click_len] += sample_click
beat += 1.0
return click_audio

View File

@ -0,0 +1,63 @@
"""Unit tests for tempo map builder and click track generator."""
import numpy as np
import pytest
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
from songsplit.tempo import build_tempo_map_from_beats, generate_click_track
def test_build_tempo_map_constant_tempo():
# 120 BPM = 0.5s per beat, 16 beats = 8.0s
beat_times = np.arange(0.5, 8.5, 0.5)
# Downbeats every 4 beats (indices 0, 4, 8, 12 -> 0.5, 2.5, 4.5, 6.5)
downbeat_times = beat_times[::4]
tempo_doc = build_tempo_map_from_beats(beat_times, downbeat_times)
# Should only create 1 anchor for steady tempo
assert len(tempo_doc.anchors) == 1
anchor = tempo_doc.anchors[0]
assert anchor.bpm == pytest.approx(120.0, abs=0.5)
assert anchor.sec == pytest.approx(0.5, abs=0.01)
assert tempo_doc.time_signature.numerator == 4
assert tempo_doc.downbeat_offset == 0
def test_build_tempo_map_3_4_time_signature():
# 3/4 time signature: downbeats every 3 beats
beat_times = np.arange(0.0, 9.0, 0.5) # 120 BPM
downbeat_times = beat_times[::3]
tempo_doc = build_tempo_map_from_beats(beat_times, downbeat_times)
assert tempo_doc.time_signature.numerator == 3
def test_build_tempo_map_sustained_tempo_change():
# Section 1: 120 BPM (0.5s per beat) for 16 beats -> 8.0s
sec1 = np.arange(0.0, 8.0, 0.5)
# Section 2: 150 BPM (0.4s per beat) for 16 beats -> 6.4s
sec2 = 8.0 + np.arange(0.0, 6.4, 0.4)
all_beats = np.concatenate([sec1, sec2])
tempo_doc = build_tempo_map_from_beats(all_beats, min_tempo_change_bpm=3.0, min_beats_for_change=6)
# Should detect 2 anchors: one around 120 BPM, one around 150 BPM
assert len(tempo_doc.anchors) >= 2
assert tempo_doc.anchors[0].bpm == pytest.approx(120.0, abs=1.0)
assert tempo_doc.anchors[1].bpm == pytest.approx(150.0, abs=2.0)
def test_generate_click_track():
tempo_doc = TempoDocument(
anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)],
time_signature=TimeSignature(numerator=4, denominator=4),
downbeat_offset=0,
)
sr = 44100
duration_sec = 4.0
clicks = generate_click_track(tempo_doc, duration_sec=duration_sec, sr=sr)
assert len(clicks) == int(duration_sec * sr)
# At sec=0.5, there should be non-zero audio (first beat click)
click_idx = int(0.5 * sr)
assert np.max(np.abs(clicks[click_idx : click_idx + 100])) > 0.1