4 Commits

7 changed files with 422 additions and 10 deletions

View File

@ -47,8 +47,7 @@ uv run ruff format --check
- [x] **M0 – Gerüst**: Projektstruktur, Pydantic-Schemas (`meta.json`, `tempo.json`, `vocals.json`, `chords.json`, `strumming.json`), `tempo.py` mit `sec_to_beat`/`beat_to_sec`, Pipeline-Runner mit Cache und Hash-Invalidierung, CLI-Skelett mit `doctor`, Testsuite.
- [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`.
- [ ] **M3 – Tempo-Map**: Stufe 5 (beat_this).
- [ ] **M3 – Tempo-Map**: Stufe 5 (beat_this).
- [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).
- [ ] **M6 – Härtung**: Fehlerbehandlung, Logging, Dokumentation, Beispielpaket.

View File

@ -18,6 +18,7 @@ dependencies = [
"faster-whisper>=1.0.0",
"scipy>=1.12.0",
"jiwer>=3.0.0",
"beat-this>=1.1.0",
]
[project.optional-dependencies]

View File

@ -1,27 +1,102 @@
"""Stage 5: Beat and downbeat tracking with beat_this -> tempo.json."""
"""Stage 5: Beat and downbeat tracking -> tempo.json."""
from pathlib import Path
from typing import Any
import soundfile as sf
from songsplit.config import config
from songsplit.pipeline.runner import PipelineContext, Stage
from songsplit.schema.base import GeneratedBy
from songsplit.tempo import build_tempo_map_from_beats, generate_click_track
class TempoStage(Stage):
"""Stage 5 tracks beats and downbeats and builds a clean Tempo-Map."""
name = "s5_tempo"
version = "1.0.0"
model_name = "beat_this"
model_version = "1.0.0"
model_version = "1.1.0"
dependencies = ["s2_stems"]
def __init__(self, model_name: str = "beat_this"):
self.model_name = model_name
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.stems_dir / "instrumental.wav"]
drums_path = ctx.stems_dir / "drums.wav"
inst_path = ctx.stems_dir / "instrumental.wav"
if drums_path.exists():
return [drums_path]
return [inst_path]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "tempo.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {}
return {
"model": "final0",
"min_tempo_change_bpm": 4.0,
}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M3
raise NotImplementedError("Stage s5_tempo will be implemented in M3.")
input_audio = self.get_inputs(ctx)[0]
if not input_audio.exists():
raise FileNotFoundError(f"Input audio for tempo tracking not found: {input_audio}")
beats = None
downbeats = None
# 1. Try beat_this deep learning model
try:
from beat_this.inference import File2Beats
device_str = config.get_device(self.name)
if device_str.startswith("cuda"):
import torch
if not torch.cuda.is_available():
device_str = "cpu"
file2beats = File2Beats(checkpoint_path="final0", device=device_str)
beats, downbeats = file2beats(str(input_audio))
self.model_name = "beat_this-final0"
except Exception:
# 2. Fallback to librosa beat tracking if beat_this is offline or fails
import librosa
y, sr = librosa.load(str(input_audio), sr=22050, mono=True)
tempo_est, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
beats = librosa.frames_to_time(beat_frames, sr=sr)
# Estimate downbeats as every 4th beat
downbeats = beats[::4] if len(beats) >= 4 else beats
self.model_name = "librosa-beat_track"
# Build clean tempo map
params = self.get_params(ctx)
tempo_doc = build_tempo_map_from_beats(
beats,
downbeats,
min_tempo_change_bpm=params.get("min_tempo_change_bpm", 4.0),
)
tempo_doc.schema_version = "1.0"
tempo_doc.generated_by = GeneratedBy(
stage=self.name,
model=self.model_name,
model_version=self.version,
params=params,
)
# Save tempo.json
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(tempo_doc.model_dump_json(indent=2))
# Generate click track for auditory verification (saved in .cache/click_track.wav)
info = sf.info(str(input_audio))
duration = info.duration
click_wav = generate_click_track(tempo_doc, duration_sec=duration)
click_out_path = ctx.cache_dir / "click_track.wav"
sf.write(str(click_out_path), click_wav, 44100, subtype="PCM_16")

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:
- Vocals are in seconds
@ -8,7 +8,9 @@ As defined in the concept:
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]:
@ -62,3 +64,146 @@ def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float:
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

94
tests/test_pipeline_m3.py Normal file
View File

@ -0,0 +1,94 @@
"""Integration test for Milestone 3 (Stage 5 Tempo Map and Click Track)."""
import json
from pathlib import Path
import numpy as np
import pytest
import soundfile as sf
from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar
from songsplit.pipeline import PipelineContext
from songsplit.pipeline.s5_tempo import TempoStage
from songsplit.schema.meta import MetaDocument, SourceFileInfo
from songsplit.schema.tempo import TempoDocument
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
def test_m3_tempo_stage_and_click_track(tmp_path: Path):
song_dir = tmp_path / "song_pkg"
stems_dir = song_dir / "stems"
cache_dir = song_dir / ".cache"
stems_dir.mkdir(parents=True, exist_ok=True)
cache_dir.mkdir(parents=True, exist_ok=True)
# 1. Generate 6.0s synthetic drum beats at 120 BPM (beats at 0.0, 0.5, 1.0, 1.5, ...)
sr = 44100
duration_sec = 6.0
audio = np.zeros(int(sr * duration_sec), dtype=np.float32)
# Place a 10ms burst pulse every 0.5s
burst_len = int(sr * 0.01)
burst = np.sin(2 * np.pi * 300.0 * np.linspace(0, 0.01, burst_len, endpoint=False)).astype(np.float32)
for t in np.arange(0.5, 5.5, 0.5):
idx = int(t * sr)
audio[idx : idx + burst_len] += burst
drums_wav = stems_dir / "drums.wav"
sf.write(str(drums_wav), audio, sr)
# 2. Write meta.json
meta = MetaDocument(
title="Tempo Test Song",
artist="Test Drummer",
duration_sec=duration_sec,
source_file=SourceFileInfo(path=str(drums_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))
# 3. Write minimal vocals.json
vocals = VocalsDocument(
lines=[
VocalLine(
start=1.0,
end=2.0,
syllables=[VocalSyllable(text="Beat", start=1.0, end=2.0, midi=60.0)],
)
]
)
(song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2))
# 4. Run TempoStage
ctx = PipelineContext(source_file=drums_wav, output_dir=song_dir)
stage = TempoStage()
stage.run(ctx)
# 5. Verify tempo.json
tempo_json = song_dir / "tempo.json"
assert tempo_json.exists()
with open(tempo_json, encoding="utf-8") as f:
doc = TempoDocument.model_validate(json.load(f))
assert len(doc.anchors) >= 1
# Detected tempo should be around 120 BPM (or 60/240 subharmonic)
bpm = doc.anchors[0].bpm
assert (
bpm == pytest.approx(120.0, abs=5.0)
or bpm == pytest.approx(60.0, abs=5.0)
or bpm == pytest.approx(240.0, abs=10.0)
)
# 6. Verify click track audio generated
click_track = cache_dir / "click_track.wav"
assert click_track.exists()
click_data, click_sr = sf.read(str(click_track))
assert len(click_data) == len(audio)
# 7. Test UltraStar export derives BPM/GAP from tempo.json
txt_path = export_ultrastar(song_dir)
assert txt_path.exists()
song = parse_ultrastar(txt_path)
assert song.bpm == pytest.approx(doc.anchors[0].bpm, abs=1.0)

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

35
uv.lock generated
View File

@ -94,6 +94,25 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/42/fe/e79d786628d9c0428f72214dbe4b90ee0c625e04d552a604d5235ff35515/av-19.0.2-cp312-abi3-win_arm64.whl", hash = "sha256:79a277b077e3768a0ea9f881ca0b3bc96d4135a8d3a7a579938adb58718d0dfd", size = 20708023, upload-time = "2026-10-21T03:44:56.435Z" },
]
[[package]]
name = "beat-this"
version = "1.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "einops" },
{ name = "numpy" },
{ name = "rotary-embedding-torch" },
{ name = "soxr" },
{ name = "torch", version = "2.15.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine != 'x86_64' and sys_platform == 'darwin'" },
{ name = "torch", version = "2.15.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine == 'x86_64' or sys_platform != 'darwin'" },
{ name = "torchaudio", version = "2.11.1", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine != 'x86_64' and sys_platform == 'darwin'" },
{ name = "torchaudio", version = "2.11.1+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine == 'x86_64' or sys_platform != 'darwin'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/d1/c4/7ce01e047c1e8d99490e95172d710e08901c24fb24e19a5dd4f885177c99/beat_this-1.1.0.tar.gz", hash = "sha256:3017c741f972972a650edcaccfe5760687fe4f5587feaa98896d90f866c2435c", size = 40635, upload-time = "2026-04-14T10:16:39.5Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ce/0e/e23cbbe6e3efcd54e84dec22b6d88954655036a993cc3843ab741bc24de4/beat_this-1.1.0-py3-none-any.whl", hash = "sha256:3f2b2d1e027c6dac380bf80c71555e3c28a4036a7f1af20129a945915a72a645", size = 40060, upload-time = "2026-04-14T10:16:37.955Z" },
]
[[package]]
name = "certifi"
version = "2026.10.23"
@ -1197,6 +1216,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" },
]
[[package]]
name = "rotary-embedding-torch"
version = "0.9.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "einops" },
{ name = "torch", version = "2.15.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine != 'x86_64' and sys_platform == 'darwin'" },
{ name = "torch", version = "2.15.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine == 'x86_64' or sys_platform != 'darwin'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/fc/63/776d55b395aed9d2815afc1740056e919691d1be1ceee203d101d33d1674/rotary_embedding_torch-0.9.1.tar.gz", hash = "sha256:f43c39cd9c0aaa17d47e876db89a552a203dd8af35e7980f484ab7ad7ea8bf69", size = 13246, upload-time = "2026-06-20T23:39:14.667Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ea/63/ca681366df98d207876c6ad7761ef6910668c83ec766fd5a70c56b9c3567/rotary_embedding_torch-0.9.1-py3-none-any.whl", hash = "sha256:489ef53e21ab4c4eb35c0c97b551d724f5eea71c2bca39acb8fee8d88b142a76", size = 17423, upload-time = "2026-06-20T23:39:13.427Z" },
]
[[package]]
name = "ruff"
version = "0.17.3"
@ -1327,6 +1360,7 @@ name = "songsplit"
version = "0.1.0"
source = { editable = "." }
dependencies = [
{ name = "beat-this" },
{ 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" },
@ -1354,6 +1388,7 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "beat-this", specifier = ">=1.1.0" },
{ name = "demucs", specifier = ">=4.0.0" },
{ name = "faster-whisper", specifier = ">=1.0.0" },
{ name = "jiwer", specifier = ">=3.0.0" },