feat(pipeline): implement stage 5 beat and downbeat tracking via beat_this
This commit is contained in:
@ -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")
|
||||
|
||||
Reference in New Issue
Block a user