feat(pipeline): modularize stage 7 into s7_tracks and support track sub-stages

This commit is contained in:
2026-11-02 12:21:59 +01:00
parent 6428e8be7d
commit fd17b63c7a
9 changed files with 428 additions and 242 deletions

View File

@ -66,8 +66,12 @@ class PipelineContext:
return MetaDocument( return MetaDocument(
duration_sec=0.0, duration_sec=0.0,
source_file=SourceFileInfo( source=SourceFileInfo(
filename=self.source_file.name,
path=str(self.source_file), path=str(self.source_file),
kind="video"
if self.source_file.suffix.lower() in [".mp4", ".mkv", ".mov", ".webm", ".avi"]
else "audio",
sha256=source_hash, sha256=source_hash,
size_bytes=size_bytes, size_bytes=size_bytes,
), ),
@ -88,6 +92,20 @@ class Stage(ABC):
model_name: str model_name: str
model_version: str = "1.0.0" model_version: str = "1.0.0"
dependencies: list[str] = [] 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 @abstractmethod
def get_inputs(self, ctx: PipelineContext) -> list[Path]: def get_inputs(self, ctx: PipelineContext) -> list[Path]:
@ -126,7 +144,8 @@ class Stage(ABC):
def is_cached(self, ctx: PipelineContext) -> bool: def is_cached(self, ctx: PipelineContext) -> bool:
"""Check if stage output is already computed and valid in cache.""" """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(): if not cache_file.exists():
return False return False
@ -145,7 +164,8 @@ class Stage(ABC):
def write_cache_entry(self, ctx: PipelineContext, cache_hash: str) -> None: def write_cache_entry(self, ctx: PipelineContext, cache_hash: str) -> None:
"""Record successful stage run in cache.""" """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 = { data = {
"stage": self.name, "stage": self.name,
"version": self.version, "version": self.version,
@ -181,8 +201,26 @@ class PipelineRunner:
def get_stages_to_run(self, ctx: PipelineContext) -> list[Stage]: def get_stages_to_run(self, ctx: PipelineContext) -> list[Stage]:
"""Resolve ordered list of stages to run.""" """Resolve ordered list of stages to run."""
if ctx.target_stage: if ctx.target_stage:
if ctx.target_stage not in self.stages_by_name: target = ctx.target_stage
raise ValueError(f"Unknown target stage: '{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 # Collect target stage and all its transitive dependencies
needed = set() needed = set()
@ -192,7 +230,7 @@ class PipelineRunner:
if dep not in needed: if dep not in needed:
add_deps(dep) 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] selected = [s for s in self.stages_by_name.values() if s.name in needed]
else: else:
selected = list(self.stages_by_name.values()) selected = list(self.stages_by_name.values())
@ -271,4 +309,13 @@ class PipelineRunner:
failed_stages.add(stage.name) failed_stages.add(stage.name)
ctx.save_meta(meta) 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 return meta

View File

@ -56,7 +56,7 @@ def split_word_into_syllables_timed(
duration = max(0.01, end - start) duration = max(0.01, end - start)
if len(syllables) == 1: 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) total_chars = sum(max(1, len(s.strip())) for s in syllables)
timed = [] timed = []
@ -64,13 +64,21 @@ def split_word_into_syllables_timed(
for i, syl in enumerate(syllables): for i, syl in enumerate(syllables):
char_len = max(1, len(syl.strip())) char_len = max(1, len(syl.strip()))
if i == len(syllables) - 1: is_last = i == len(syllables) - 1
if is_last:
syl_end = end syl_end = end
else: else:
syl_dur = duration * (char_len / total_chars) syl_dur = duration * (char_len / total_chars)
syl_end = cur_t + syl_dur 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 cur_t = syl_end
return timed return timed

View File

@ -146,14 +146,18 @@ class PitchStage(Stage):
# Process each line and syllable # Process each line and syllable
vocal_lines: list[VocalLine] = [] vocal_lines: list[VocalLine] = []
line_counter = 0
syl_counter = 0
for line_dict in lyrics_data.get("lines", []): for line_dict in lyrics_data.get("lines", []):
line_counter += 1
line_syllables_raw = [] line_syllables_raw = []
for syl_dict in line_dict.get("syllables", []): for syl_dict in line_dict.get("syllables", []):
s_start = float(syl_dict["start"]) s_start = float(syl_dict["start"])
s_end = float(syl_dict["end"]) s_end = float(syl_dict["end"])
text = syl_dict["text"] text = syl_dict["text"]
w_end = syl_dict.get("word_end", False)
# Frames within syllable # Frames within syllable
mask = (frame_times >= s_start) & (frame_times <= s_end) mask = (frame_times >= s_start) & (frame_times <= s_end)
@ -178,27 +182,38 @@ class PitchStage(Stage):
"end": s_end, "end": s_end,
"midi": median_midi, "midi": median_midi,
"confidence": float(np.clip(conf, 0.0, 1.0)), "confidence": float(np.clip(conf, 0.0, 1.0)),
"word_end": w_end,
} }
) )
# Apply octave error correction within phrase # Apply octave error correction within phrase
corrected_sylls = correct_octave_errors(line_syllables_raw) corrected_sylls = correct_octave_errors(line_syllables_raw)
syl_objects = [ syl_objects = []
VocalSyllable( for s in corrected_sylls:
text=s["text"], syl_counter += 1
start=s["start"], raw_text = s["text"]
end=s["end"], has_space = raw_text.endswith(" ")
midi=s["midi"], clean_text = raw_text.rstrip()
confidence=s["confidence"], is_word_end = s.get("word_end", has_space)
source="auto", 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: if syl_objects:
vocal_lines.append( vocal_lines.append(
VocalLine( VocalLine(
id=f"l_{line_counter:04d}",
voice=0,
start=line_dict["start"], start=line_dict["start"],
end=line_dict["end"], end=line_dict["end"],
syllables=syl_objects, syllables=syl_objects,
@ -220,3 +235,26 @@ class PitchStage(Stage):
output_file.parent.mkdir(parents=True, exist_ok=True) output_file.parent.mkdir(parents=True, exist_ok=True)
with open(output_file, "w", encoding="utf-8") as f: with open(output_file, "w", encoding="utf-8") as f:
f.write(doc.model_dump_json(indent=2)) 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

View File

@ -198,10 +198,19 @@ class ChordsStage(Stage):
# Estimate key and save in meta.json # Estimate key and save in meta.json
mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data 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) 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 = 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) ctx.save_meta(meta)
params = self.get_params(ctx) 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( chords_doc = ChordsDocument(
schema_version="1.0", schema_version="1.0",
generated_by=GeneratedBy( generated_by=GeneratedBy(

View File

@ -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 songsplit.pipeline.s7_tracks.strumming import (
from pathlib import Path StrummingTrackStage,
from typing import Any aggregate_strum_patterns,
estimate_strum_direction,
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
def estimate_strum_direction( class StrummingStage(StrummingTrackStage):
audio: np.ndarray, """Backward-compatible alias for StrummingTrackStage."""
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" def __init__(self, track_name: str = "guitar", grid: str = "8th") -> None:
confidence = 0.5 super().__init__(track_name=track_name, grid=grid) # type: ignore[arg-type]
self.name = "s7_strumming"
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( __all__ = [
events: list[StrumEvent], "StrummingStage",
total_beats: float, "StrummingTrackStage",
grid: str = "8th", "estimate_strum_direction",
pattern_beats: float = 4.0, "aggregate_strum_patterns",
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))

View File

@ -0,0 +1,5 @@
"""Instrument track stages (tracks/<name>.json)."""
from songsplit.pipeline.s7_tracks.strumming import StrummingTrackStage
__all__ = ["StrummingTrackStage"]

View File

@ -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))

View File

@ -38,6 +38,15 @@ class KeyInfo(BaseModel):
mode: str = "major" mode: str = "major"
confidence: float | None = None 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): class CapoSuggestion(BaseModel):
"""Capo suggestion and chord shape root.""" """Capo suggestion and chord shape root."""

View File

@ -162,9 +162,18 @@ def build_tempo_map_from_beats(
continue continue
i += 1 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( return TempoDocument(
anchors=anchors, anchors=anchors,
time_signature=time_sig, time_signatures=[ts_entry],
downbeat_offset=downbeat_offset, downbeat_offset=downbeat_offset,
) )