feat(strumming): implement stage 7 onset detection, direction estimation, and pattern aggregation

This commit is contained in:
2026-11-02 11:20:33 +01:00
parent 8d366327e6
commit 7ec6b3274b

View File

@ -1,30 +1,226 @@
"""Stage 7: Strumming pattern analysis -> strumming.json.""" """Stage 7: Strumming pattern analysis -> strumming.json (experimental)."""
import json
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import librosa
import numpy as np
import soundfile as sf
from songsplit.pipeline.runner import PipelineContext, Stage from songsplit.pipeline.runner import PipelineContext, Stage
from songsplit.schema.base import GeneratedBy
from songsplit.schema.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
from songsplit.schema.tempo import TempoDocument
from songsplit.tempo import sec_to_beat
def estimate_strum_direction(
audio: np.ndarray,
sr: int,
onset_sec: float,
beat: float,
) -> tuple[StrumDirection, float]:
"""Estimate strumming direction (down vs up) from spectral centroid gradient and beat phase."""
# Analyze 50ms window right after onset
start_sample = int(onset_sec * sr)
window_samples = int(sr * 0.05)
end_sample = min(len(audio), start_sample + window_samples)
direction: StrumDirection = "down"
confidence = 0.5
if end_sample - start_sample > 256:
chunk = audio[start_sample:end_sample]
# Compute spectral centroid
centroids = librosa.feature.spectral_centroid(y=chunk, sr=sr, hop_length=128)[0]
if len(centroids) >= 2:
centroid_slope = centroids[-1] - centroids[0]
# Downstrum hits bass strings first then treble (centroid moves higher or bass-dominant)
if centroid_slope > 0:
direction = "down"
confidence += 0.1
else:
direction = "up"
confidence += 0.1
# Beat phase prior: On-beats (integer beats) are predominantly down strums
beat_frac = beat - np.floor(beat)
# Close to on-beat (0.0): down strum
if beat_frac < 0.25 or beat_frac > 0.75:
if direction == "down":
confidence = min(0.85, confidence + 0.15)
else:
direction = "down"
confidence = 0.6
# Close to off-beat (0.5): up strum
elif 0.35 <= beat_frac <= 0.65:
if direction == "up":
confidence = min(0.85, confidence + 0.15)
else:
direction = "up"
confidence = 0.6
return direction, round(confidence, 2)
def aggregate_strum_patterns(
events: list[StrumEvent],
total_beats: float,
grid: str = "8th",
pattern_beats: float = 4.0,
section_beats: float = 16.0,
) -> list[StrumPattern]:
"""Condense discrete strumming events into representative pattern strings (e.g. 'D . D U . U D U')."""
if not events:
return []
grid_step = 0.5 if grid == "8th" else 0.25
slots_per_pattern = int(round(pattern_beats / grid_step))
patterns: list[StrumPattern] = []
num_sections = int(np.ceil(total_beats / section_beats))
for sec_idx in range(num_sections):
sec_start = sec_idx * section_beats
sec_end = min(total_beats, sec_start + section_beats)
# Gather events in this section
sec_events = [e for e in events if sec_start <= e.beat < sec_end]
if not sec_events:
continue
# Vote for each slot in the pattern (modulo pattern_beats)
slot_votes: list[list[str]] = [[] for _ in range(slots_per_pattern)]
for e in sec_events:
rel_beat = (e.beat - sec_start) % pattern_beats
slot_idx = int(round(rel_beat / grid_step)) % slots_per_pattern
symbol = "D" if e.direction == "down" else "U"
slot_votes[slot_idx].append(symbol)
pattern_tokens = []
for votes in slot_votes:
if votes:
# Majority symbol
symbol = "D" if votes.count("D") >= votes.count("U") else "U"
pattern_tokens.append(symbol)
else:
pattern_tokens.append(".")
pattern_str = " ".join(pattern_tokens)
patterns.append(
StrumPattern(
start_beat=round(sec_start, 2),
end_beat=round(sec_end, 2),
pattern=pattern_str,
grid=grid,
)
)
return patterns
class StrummingStage(Stage): class StrummingStage(Stage):
"""Stage 7 detects strumming onsets and patterns on the guitar/instrumental stem."""
name = "s7_strumming" name = "s7_strumming"
version = "1.0.0" version = "1.0.0"
model_name = "librosa-onsets" model_name = "librosa-onsets"
model_version = "1.0.0" model_version = "1.0.0"
dependencies = ["s5_tempo"] dependencies = ["s5_tempo"]
def __init__(self, grid: str = "8th"):
self.grid = grid
def get_inputs(self, ctx: PipelineContext) -> list[Path]: def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ guitar_path = ctx.stems_dir / "guitar.wav"
ctx.stems_dir / "instrumental.wav", inst_path = ctx.stems_dir / "instrumental.wav"
ctx.output_dir / "tempo.json", if guitar_path.exists():
] return [guitar_path, ctx.output_dir / "tempo.json"]
return [inst_path, ctx.output_dir / "tempo.json"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]: def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "strumming.json"] return [ctx.output_dir / "strumming.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]: def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"grid": "8th"} return {
"grid": self.grid,
"status": "experimental",
"hop_length": 512,
}
def run(self, ctx: PipelineContext) -> None: def run(self, ctx: PipelineContext) -> None:
# Implementation in M5 audio_path, tempo_path = self.get_inputs(ctx)
raise NotImplementedError("Stage s7_strumming will be implemented in M5.") if not audio_path.exists():
raise FileNotFoundError(f"Input audio for strumming not found: {audio_path}")
if not tempo_path.exists():
raise FileNotFoundError(f"tempo.json not found: {tempo_path}")
with open(tempo_path, encoding="utf-8") as f:
tempo_doc = TempoDocument.model_validate(json.load(f))
audio_data, sr = sf.read(str(audio_path), dtype="float32")
mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data
params = self.get_params(ctx)
grid = params.get("grid", "8th")
grid_step = 0.5 if grid == "8th" else 0.25
# Detect onsets
onset_env = librosa.onset.onset_strength(y=mono_audio, sr=sr, hop_length=512)
onset_frames = librosa.onset.onset_detect(
onset_envelope=onset_env,
sr=sr,
hop_length=512,
backtrack=True,
)
onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=512)
# Normalize onset envelope for strength computation
max_env = float(np.max(onset_env)) if len(onset_env) > 0 and np.max(onset_env) > 0 else 1.0
# Map onsets onto beat grid
raw_events_by_grid: dict[float, StrumEvent] = {}
for frame_idx, t_sec in zip(onset_frames, onset_times, strict=False):
beat = sec_to_beat(float(t_sec), tempo_doc)
if beat < 0:
continue
quantized_beat = round(beat / grid_step) * grid_step
strength = float(np.clip(onset_env[frame_idx] / max_env, 0.1, 1.0))
direction, conf = estimate_strum_direction(mono_audio, sr, float(t_sec), quantized_beat)
# If multiple onsets fall on the same grid slot, keep the strongest
if quantized_beat not in raw_events_by_grid or strength > raw_events_by_grid[quantized_beat].strength:
raw_events_by_grid[quantized_beat] = StrumEvent(
beat=round(quantized_beat, 3),
direction=direction,
strength=round(strength, 2),
confidence=conf,
source="auto",
)
events = sorted(raw_events_by_grid.values(), key=lambda e: e.beat)
total_duration = sf.info(str(audio_path)).duration
total_beats = sec_to_beat(total_duration, tempo_doc)
patterns = aggregate_strum_patterns(events, total_beats, grid=grid)
doc = StrummingDocument(
schema_version="1.0",
generated_by=GeneratedBy(
stage=self.name,
model=self.model_name,
model_version=self.version,
params=params,
),
events=events,
patterns=patterns,
)
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(doc.model_dump_json(indent=2))