feat(pipeline): implement stage 5 beat and downbeat tracking via beat_this

This commit is contained in:
2026-11-02 10:53:19 +01:00
parent cc5e2fe628
commit 887bd4a3e9
3 changed files with 117 additions and 6 deletions

View File

@ -18,6 +18,7 @@ dependencies = [
"faster-whisper>=1.0.0", "faster-whisper>=1.0.0",
"scipy>=1.12.0", "scipy>=1.12.0",
"jiwer>=3.0.0", "jiwer>=3.0.0",
"beat-this>=1.1.0",
] ]
[project.optional-dependencies] [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 pathlib import Path
from typing import Any from typing import Any
import soundfile as sf
from songsplit.config import config
from songsplit.pipeline.runner import PipelineContext, Stage 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): class TempoStage(Stage):
"""Stage 5 tracks beats and downbeats and builds a clean Tempo-Map."""
name = "s5_tempo" name = "s5_tempo"
version = "1.0.0" version = "1.0.0"
model_name = "beat_this" model_name = "beat_this"
model_version = "1.0.0" model_version = "1.1.0"
dependencies = ["s2_stems"] dependencies = ["s2_stems"]
def __init__(self, model_name: str = "beat_this"):
self.model_name = model_name
def get_inputs(self, ctx: PipelineContext) -> list[Path]: 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]: def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "tempo.json"] return [ctx.output_dir / "tempo.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]: 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: def run(self, ctx: PipelineContext) -> None:
# Implementation in M3 input_audio = self.get_inputs(ctx)[0]
raise NotImplementedError("Stage s5_tempo will be implemented in M3.") 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")

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" }, { 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]] [[package]]
name = "certifi" name = "certifi"
version = "2026.10.23" 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" }, { 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]] [[package]]
name = "ruff" name = "ruff"
version = "0.17.3" version = "0.17.3"
@ -1327,6 +1360,7 @@ name = "songsplit"
version = "0.1.0" version = "0.1.0"
source = { editable = "." } source = { editable = "." }
dependencies = [ 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.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 = "demucs", version = "4.1.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
{ name = "faster-whisper" }, { name = "faster-whisper" },
@ -1354,6 +1388,7 @@ dev = [
[package.metadata] [package.metadata]
requires-dist = [ requires-dist = [
{ name = "beat-this", specifier = ">=1.1.0" },
{ name = "demucs", specifier = ">=4.0.0" }, { name = "demucs", specifier = ">=4.0.0" },
{ name = "faster-whisper", specifier = ">=1.0.0" }, { name = "faster-whisper", specifier = ">=1.0.0" },
{ name = "jiwer", specifier = ">=3.0.0" }, { name = "jiwer", specifier = ">=3.0.0" },