From fd17b63c7ab4d463a0e341a68b8ad4868a4b4c1c Mon Sep 17 00:00:00 2001 From: wlkns-dev Date: Mon, 2 Nov 2026 12:21:59 +0100 Subject: [PATCH] feat(pipeline): modularize stage 7 into s7_tracks and support track sub-stages --- src/songsplit/pipeline/runner.py | 59 +++- src/songsplit/pipeline/s3_lyrics.py | 14 +- src/songsplit/pipeline/s4_pitch.py | 58 +++- src/songsplit/pipeline/s6_chords.py | 16 +- src/songsplit/pipeline/s7_strumming.py | 237 ++-------------- src/songsplit/pipeline/s7_tracks/__init__.py | 5 + src/songsplit/pipeline/s7_tracks/strumming.py | 261 ++++++++++++++++++ src/songsplit/schema/meta.py | 9 + src/songsplit/tempo.py | 11 +- 9 files changed, 428 insertions(+), 242 deletions(-) create mode 100644 src/songsplit/pipeline/s7_tracks/__init__.py create mode 100644 src/songsplit/pipeline/s7_tracks/strumming.py diff --git a/src/songsplit/pipeline/runner.py b/src/songsplit/pipeline/runner.py index b11c12f..7c49456 100644 --- a/src/songsplit/pipeline/runner.py +++ b/src/songsplit/pipeline/runner.py @@ -66,8 +66,12 @@ class PipelineContext: return MetaDocument( duration_sec=0.0, - source_file=SourceFileInfo( + source=SourceFileInfo( + filename=self.source_file.name, path=str(self.source_file), + kind="video" + if self.source_file.suffix.lower() in [".mp4", ".mkv", ".mov", ".webm", ".avi"] + else "audio", sha256=source_hash, size_bytes=size_bytes, ), @@ -88,6 +92,20 @@ class Stage(ABC): model_name: str model_version: str = "1.0.0" dependencies: list[str] = [] + aliases: list[str] = [] + + def __init__( + self, + name: str = "", + version: str = "1.0.0", + dependencies: list[str] | None = None, + aliases: list[str] | None = None, + ): + if name: + self.name = name + self.version = version + self.dependencies = dependencies if dependencies is not None else list(getattr(self, "dependencies", [])) + self.aliases = aliases if aliases is not None else list(getattr(self, "aliases", [])) @abstractmethod def get_inputs(self, ctx: PipelineContext) -> list[Path]: @@ -126,7 +144,8 @@ class Stage(ABC): def is_cached(self, ctx: PipelineContext) -> bool: """Check if stage output is already computed and valid in cache.""" - cache_file = ctx.cache_dir / f"{self.name}.json" + safe_name = self.name.replace(":", "_") + cache_file = ctx.cache_dir / f"{safe_name}.json" if not cache_file.exists(): return False @@ -145,7 +164,8 @@ class Stage(ABC): def write_cache_entry(self, ctx: PipelineContext, cache_hash: str) -> None: """Record successful stage run in cache.""" - cache_file = ctx.cache_dir / f"{self.name}.json" + safe_name = self.name.replace(":", "_") + cache_file = ctx.cache_dir / f"{safe_name}.json" data = { "stage": self.name, "version": self.version, @@ -181,8 +201,26 @@ class PipelineRunner: def get_stages_to_run(self, ctx: PipelineContext) -> list[Stage]: """Resolve ordered list of stages to run.""" if ctx.target_stage: - if ctx.target_stage not in self.stages_by_name: - raise ValueError(f"Unknown target stage: '{ctx.target_stage}'") + target = ctx.target_stage + if target not in self.stages_by_name: + # Check aliases + found = None + for s in self.stages_by_name.values(): + if target in s.aliases: + found = s.name + break + if found: + target = found + elif target == "tracks": + # Match all track stages + track_stages = [s for s in self.stages_by_name.values() if s.name.startswith("tracks:")] + if track_stages: + target = track_stages[-1].name + else: + raise ValueError(f"Unknown target stage: '{ctx.target_stage}'") + else: + raise ValueError(f"Unknown target stage: '{ctx.target_stage}'") + # Collect target stage and all its transitive dependencies needed = set() @@ -192,7 +230,7 @@ class PipelineRunner: if dep not in needed: add_deps(dep) - add_deps(ctx.target_stage) + add_deps(target) selected = [s for s in self.stages_by_name.values() if s.name in needed] else: selected = list(self.stages_by_name.values()) @@ -271,4 +309,13 @@ class PipelineRunner: failed_stages.add(stage.name) ctx.save_meta(meta) + + try: + from songsplit.container import build_manifest_for_dir + + manifest = build_manifest_for_dir(ctx.output_dir) + (ctx.output_dir / "manifest.json").write_text(manifest.model_dump_json(indent=2), encoding="utf-8") + except Exception as e: + logger.warning("Could not update manifest.json: %s", e) + return meta diff --git a/src/songsplit/pipeline/s3_lyrics.py b/src/songsplit/pipeline/s3_lyrics.py index 7c4e229..46fd917 100644 --- a/src/songsplit/pipeline/s3_lyrics.py +++ b/src/songsplit/pipeline/s3_lyrics.py @@ -56,7 +56,7 @@ def split_word_into_syllables_timed( duration = max(0.01, end - start) if len(syllables) == 1: - return [{"text": syllables[0], "start": start, "end": end}] + return [{"text": syllables[0], "start": start, "end": end, "word_end": True}] total_chars = sum(max(1, len(s.strip())) for s in syllables) timed = [] @@ -64,13 +64,21 @@ def split_word_into_syllables_timed( for i, syl in enumerate(syllables): char_len = max(1, len(syl.strip())) - if i == len(syllables) - 1: + is_last = i == len(syllables) - 1 + if is_last: syl_end = end else: syl_dur = duration * (char_len / total_chars) syl_end = cur_t + syl_dur - timed.append({"text": syl, "start": cur_t, "end": syl_end}) + timed.append( + { + "text": syl, + "start": cur_t, + "end": syl_end, + "word_end": is_last, + } + ) cur_t = syl_end return timed diff --git a/src/songsplit/pipeline/s4_pitch.py b/src/songsplit/pipeline/s4_pitch.py index e96b878..f0159a3 100644 --- a/src/songsplit/pipeline/s4_pitch.py +++ b/src/songsplit/pipeline/s4_pitch.py @@ -146,14 +146,18 @@ class PitchStage(Stage): # Process each line and syllable vocal_lines: list[VocalLine] = [] + line_counter = 0 + syl_counter = 0 for line_dict in lyrics_data.get("lines", []): + line_counter += 1 line_syllables_raw = [] for syl_dict in line_dict.get("syllables", []): s_start = float(syl_dict["start"]) s_end = float(syl_dict["end"]) text = syl_dict["text"] + w_end = syl_dict.get("word_end", False) # Frames within syllable mask = (frame_times >= s_start) & (frame_times <= s_end) @@ -178,27 +182,38 @@ class PitchStage(Stage): "end": s_end, "midi": median_midi, "confidence": float(np.clip(conf, 0.0, 1.0)), + "word_end": w_end, } ) # Apply octave error correction within phrase corrected_sylls = correct_octave_errors(line_syllables_raw) - syl_objects = [ - VocalSyllable( - text=s["text"], - start=s["start"], - end=s["end"], - midi=s["midi"], - confidence=s["confidence"], - source="auto", + syl_objects = [] + for s in corrected_sylls: + syl_counter += 1 + raw_text = s["text"] + has_space = raw_text.endswith(" ") + clean_text = raw_text.rstrip() + is_word_end = s.get("word_end", has_space) + syl_objects.append( + VocalSyllable( + id=f"s_{syl_counter:04d}", + text=clean_text, + start=s["start"], + end=s["end"], + midi=s["midi"], + confidence=s["confidence"], + word_end=is_word_end, + source="auto", + ) ) - for s in corrected_sylls - ] if syl_objects: vocal_lines.append( VocalLine( + id=f"l_{line_counter:04d}", + voice=0, start=line_dict["start"], end=line_dict["end"], syllables=syl_objects, @@ -220,3 +235,26 @@ class PitchStage(Stage): 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)) + + # Write optional vocals_f0.json per Section 6 + try: + from songsplit.schema.vocals_f0 import VocalsF0Document + + hop_sec = hop_length / crepe_sr + f0_hz: list[float | None] = [ + round(float(h), 2) if p >= voicing_thresh and h > 50 else None + for h, p in zip(pitch_hz, periodicity, strict=False) + ] + f0_conf = [round(float(p), 2) for p in periodicity] + f0_doc = VocalsF0Document( + schema_version="1.0", + hop_sec=round(hop_sec, 4), + start_sec=0.0, + hz=f0_hz, + confidence=f0_conf, + ) + f0_path = ctx.output_dir / "vocals_f0.json" + with open(f0_path, "w", encoding="utf-8") as f: + f.write(f0_doc.model_dump_json()) + except Exception: + pass diff --git a/src/songsplit/pipeline/s6_chords.py b/src/songsplit/pipeline/s6_chords.py index 824eba5..fb909c1 100644 --- a/src/songsplit/pipeline/s6_chords.py +++ b/src/songsplit/pipeline/s6_chords.py @@ -198,10 +198,19 @@ class ChordsStage(Stage): # Estimate key and save in meta.json mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data chroma = librosa.feature.chroma_cqt(y=mono_audio, sr=sr) - detected_key = estimate_key(chroma.mean(axis=1)) + detected_key_str = estimate_key(chroma.mean(axis=1)) + + from songsplit.schema.meta import KeyInfo + + if detected_key_str.endswith("m"): + key_tonic = detected_key_str[:-1] + key_mode = "minor" + else: + key_tonic = detected_key_str + key_mode = "major" meta = ctx.load_or_init_meta() - meta.key = detected_key + meta.key = KeyInfo(tonic=key_tonic, mode=key_mode, confidence=0.8) ctx.save_meta(meta) params = self.get_params(ctx) @@ -288,6 +297,9 @@ class ChordsStage(Stage): ) ) + for idx, ev in enumerate(chord_events): + ev.id = f"c_{idx + 1:04d}" + chords_doc = ChordsDocument( schema_version="1.0", generated_by=GeneratedBy( diff --git a/src/songsplit/pipeline/s7_strumming.py b/src/songsplit/pipeline/s7_strumming.py index ad36780..da883ee 100644 --- a/src/songsplit/pipeline/s7_strumming.py +++ b/src/songsplit/pipeline/s7_strumming.py @@ -1,226 +1,23 @@ -"""Stage 7: Strumming pattern analysis -> strumming.json (experimental).""" +"""Stage 7: Strumming pattern analysis -> tracks/guitar.json (wrapper for s7_tracks/strumming).""" -import json -from pathlib import Path -from typing import Any - -import librosa -import numpy as np -import soundfile as sf - -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 +from songsplit.pipeline.s7_tracks.strumming import ( + StrummingTrackStage, + aggregate_strum_patterns, + estimate_strum_direction, +) -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) +class StrummingStage(StrummingTrackStage): + """Backward-compatible alias for StrummingTrackStage.""" - 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 __init__(self, track_name: str = "guitar", grid: str = "8th") -> None: + super().__init__(track_name=track_name, grid=grid) # type: ignore[arg-type] + self.name = "s7_strumming" -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): - """Stage 7 detects strumming onsets and patterns on the guitar/instrumental stem.""" - - name = "s7_strumming" - version = "1.0.0" - model_name = "librosa-onsets" - model_version = "1.0.0" - dependencies = ["s5_tempo"] - - def __init__(self, grid: str = "8th"): - self.grid = grid - - def get_inputs(self, ctx: PipelineContext) -> list[Path]: - guitar_path = ctx.stems_dir / "guitar.wav" - inst_path = ctx.stems_dir / "instrumental.wav" - 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]: - return [ctx.output_dir / "strumming.json"] - - def get_params(self, ctx: PipelineContext) -> dict[str, Any]: - return { - "grid": self.grid, - "status": "experimental", - "hop_length": 512, - } - - def run(self, ctx: PipelineContext) -> None: - audio_path, tempo_path = self.get_inputs(ctx) - 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)) +__all__ = [ + "StrummingStage", + "StrummingTrackStage", + "estimate_strum_direction", + "aggregate_strum_patterns", +] diff --git a/src/songsplit/pipeline/s7_tracks/__init__.py b/src/songsplit/pipeline/s7_tracks/__init__.py new file mode 100644 index 0000000..906f75c --- /dev/null +++ b/src/songsplit/pipeline/s7_tracks/__init__.py @@ -0,0 +1,5 @@ +"""Instrument track stages (tracks/.json).""" + +from songsplit.pipeline.s7_tracks.strumming import StrummingTrackStage + +__all__ = ["StrummingTrackStage"] diff --git a/src/songsplit/pipeline/s7_tracks/strumming.py b/src/songsplit/pipeline/s7_tracks/strumming.py new file mode 100644 index 0000000..1f6c671 --- /dev/null +++ b/src/songsplit/pipeline/s7_tracks/strumming.py @@ -0,0 +1,261 @@ +"""Stage 7 sub-stage: Strumming track analysis -> tracks/guitar.json (experimental).""" + +import json +from pathlib import Path +from typing import Any + +import librosa +import numpy as np +import soundfile as sf + +from songsplit.pipeline.runner import PipelineContext, Stage +from songsplit.schema.base import GeneratedBy +from songsplit.schema.tempo import TempoDocument +from songsplit.schema.tracks import StrumDirection, StrumEvent, StrumGrid, StrumPattern, TrackDocument +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.""" + 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] + centroids = librosa.feature.spectral_centroid(y=chunk, sr=sr, hop_length=128)[0] + if len(centroids) >= 2: + centroid_slope = centroids[-1] - centroids[0] + if centroid_slope > 0: + direction = "down" + confidence += 0.1 + else: + direction = "up" + confidence += 0.1 + + beat_frac = beat - np.floor(beat) + 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 + 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: StrumGrid = "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) + + sec_events = [e for e in events if sec_start <= e.beat < sec_end] + if not sec_events: + continue + + 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_chars: list[str] = [] + for votes in slot_votes: + if not votes: + pattern_chars.append(".") + else: + d_count = votes.count("D") + u_count = votes.count("U") + pattern_chars.append("D" if d_count >= u_count else "U") + + pattern_str = " ".join(pattern_chars) + patterns.append( + StrumPattern( + id=f"p_{len(patterns) + 1:04d}", + start_beat=round(sec_start, 3), + end_beat=round(sec_end, 3), + grid=grid, + pattern=pattern_str, + confidence=0.5, + source="auto", + locked=False, + ) + ) + + return patterns + + +class StrummingTrackStage(Stage): + """Stage 7: Track: Strumming -> tracks/guitar.json (experimental).""" + + def __init__(self, track_name: str = "guitar", grid: StrumGrid = "8th"): + super().__init__( + name="tracks:strumming", + version="1.0.0", + dependencies=["s2_stems", "s5_tempo"], + aliases=["strumming", "s7_strumming", "s7", "guitar", "tracks"], + ) + self.track_name = track_name + self.grid = grid + self.model_name = "librosa-onset+spectral-gradient" + + def get_inputs(self, ctx: PipelineContext) -> list[Path]: + guitar_stem = ctx.output_dir / "stems" / "guitar.wav" + inst_stem = ctx.output_dir / "stems" / "instrumental.wav" + audio_stem = guitar_stem if guitar_stem.exists() else inst_stem + return [audio_stem, ctx.output_dir / "tempo.json"] + + def get_outputs(self, ctx: PipelineContext) -> list[Path]: + return [ + ctx.output_dir / "tracks" / f"{self.track_name}.json", + # backward compatibility for legacy readers + ctx.output_dir / "strumming.json", + ] + + def get_params(self, ctx: PipelineContext) -> dict[str, Any]: + return { + "track_name": self.track_name, + "grid": self.grid, + "pattern_beats": 4.0, + "section_beats": 16.0, + "status": "experimental", + } + + def run(self, ctx: PipelineContext) -> None: + audio_path, tempo_path = self.get_inputs(ctx) + 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: StrumGrid = 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) + + max_env = float(np.max(onset_env)) if len(onset_env) > 0 and np.max(onset_env) > 0 else 1.0 + + # Preserve locked events if existing track file exists (Section 9) + track_output = ctx.output_dir / "tracks" / f"{self.track_name}.json" + locked_events: list[StrumEvent] = [] + if track_output.exists(): + try: + with open(track_output, encoding="utf-8") as f: + old_doc = TrackDocument.model_validate(json.load(f)) + locked_events = [ + StrumEvent.model_validate(e) + for e in old_doc.events + if getattr(e, "locked", False) or getattr(e, "source", "") == "manual" + ] + except Exception: + pass + + raw_events_by_grid: dict[float, StrumEvent] = {round(e.beat, 3): e for e in locked_events} + + 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 + q_key = round(quantized_beat, 3) + if q_key in raw_events_by_grid and raw_events_by_grid[q_key].locked: + # Locked item takes precedence + continue + + 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 q_key not in raw_events_by_grid or strength > raw_events_by_grid[q_key].strength: + raw_events_by_grid[q_key] = StrumEvent( + id=f"e_{len(raw_events_by_grid) + 1:04d}", + beat=q_key, + direction=direction, + strength=round(strength, 2), + confidence=conf, + source="auto", + locked=False, + ) + + sorted_events = sorted(raw_events_by_grid.values(), key=lambda e: e.beat) + for idx, ev in enumerate(sorted_events): + if not ev.id or ev.id == "e_0001": + ev.id = f"e_{idx + 1:04d}" + + total_duration = sf.info(str(audio_path)).duration + total_beats = sec_to_beat(total_duration, tempo_doc) + + patterns = aggregate_strum_patterns(sorted_events, total_beats, grid=grid) + + stem_used = "guitar" if (ctx.output_dir / "stems" / "guitar.wav").exists() else "instrumental" + doc = TrackDocument( + schema_version="1.0", + name=self.track_name, + instrument="guitar", + kind="strumming", + stem=stem_used, + generated_by=GeneratedBy( + stage=self.name, + model=self.model_name, + model_version=self.version, + params=params, + ), + events=sorted_events, + patterns=patterns, + ) + + # Write tracks/guitar.json + track_output.parent.mkdir(parents=True, exist_ok=True) + with open(track_output, "w", encoding="utf-8") as f: + f.write(doc.model_dump_json(indent=2)) + + # Also write legacy strumming.json for compatibility + legacy_output = ctx.output_dir / "strumming.json" + with open(legacy_output, "w", encoding="utf-8") as f: + f.write(doc.model_dump_json(indent=2)) diff --git a/src/songsplit/schema/meta.py b/src/songsplit/schema/meta.py index 317d919..e7a18a3 100644 --- a/src/songsplit/schema/meta.py +++ b/src/songsplit/schema/meta.py @@ -38,6 +38,15 @@ class KeyInfo(BaseModel): mode: str = "major" confidence: float | None = None + def __eq__(self, other: object) -> bool: + if isinstance(other, str): + short = f"{self.tonic}m" if self.mode == "minor" else self.tonic + return other in (short, self.tonic) + return super().__eq__(other) + + def __str__(self) -> str: + return f"{self.tonic}m" if self.mode == "minor" else self.tonic + class CapoSuggestion(BaseModel): """Capo suggestion and chord shape root.""" diff --git a/src/songsplit/tempo.py b/src/songsplit/tempo.py index 995e0f4..6bb699f 100644 --- a/src/songsplit/tempo.py +++ b/src/songsplit/tempo.py @@ -162,9 +162,18 @@ def build_tempo_map_from_beats( continue i += 1 + ts_entry = TimeSignature( + id="ts_0001", + beat=0.0, + numerator=time_sig.numerator, + denominator=time_sig.denominator, + ) + for idx, a in enumerate(anchors): + a.id = f"t_{idx + 1:04d}" + return TempoDocument( anchors=anchors, - time_signature=time_sig, + time_signatures=[ts_entry], downbeat_offset=downbeat_offset, )