"""Tempo-Map conversion between seconds and musical beats and click track generation. As defined in the concept: - Vocals are in seconds - Chords and strumming are in beats - Conversion ONLY through sec_to_beat() and beat_to_sec(). """ from bisect import bisect_right import numpy as np from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]: """Return anchors sorted by time/beat, raising ValueError if empty.""" if not tempo_map.anchors: raise ValueError("Tempo map has no anchors defined.") return sorted(tempo_map.anchors, key=lambda a: a.sec) def sec_to_beat(sec: float, tempo_map: TempoDocument) -> float: """Convert time in seconds to musical beat (float quarter notes). Constant tempo is assumed between consecutive anchors. The last anchor applies until the end of the song. Extrapolation is used before the first anchor. """ anchors = _get_sorted_anchors(tempo_map) sec_points = [a.sec for a in anchors] idx = bisect_right(sec_points, sec) - 1 if idx < 0: # Before the first anchor -> extrapolate using the first anchor's tempo anchor = anchors[0] delta_sec = sec - anchor.sec return anchor.beat + delta_sec * (anchor.bpm / 60.0) anchor = anchors[idx] delta_sec = sec - anchor.sec return anchor.beat + delta_sec * (anchor.bpm / 60.0) def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float: """Convert musical beat (float quarter notes) to time in seconds. Constant tempo is assumed between consecutive anchors. The last anchor applies until the end of the song. Extrapolation is used before the first anchor. """ anchors = _get_sorted_anchors(tempo_map) beat_points = [a.beat for a in anchors] idx = bisect_right(beat_points, beat) - 1 if idx < 0: # Before the first anchor -> extrapolate using the first anchor's tempo anchor = anchors[0] delta_beat = beat - anchor.beat return anchor.sec + delta_beat * (60.0 / anchor.bpm) anchor = anchors[idx] delta_beat = beat - anchor.beat 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