Compare commits
17 Commits
m1-stems
...
f1d55c4bcb
| Author | SHA1 | Date | |
|---|---|---|---|
| f1d55c4bcb | |||
| 760bad7435 | |||
| 7ec6b3274b | |||
| 8d366327e6 | |||
| fcc1cd2426 | |||
| 983102b588 | |||
| a7dedd4306 | |||
| fac85bcd56 | |||
| 887bd4a3e9 | |||
| cc5e2fe628 | |||
| 6eb02fe576 | |||
| cdc47bc85a | |||
| f1736caff5 | |||
| cd6f2a8fa3 | |||
| ac9831d195 | |||
| acb1411aa1 | |||
| 4fbd741f4c |
@ -46,8 +46,8 @@ uv run ruff format --check
|
||||
|
||||
- [x] **M0 – Gerüst**: Projektstruktur, Pydantic-Schemas (`meta.json`, `tempo.json`, `vocals.json`, `chords.json`, `strumming.json`), `tempo.py` mit `sec_to_beat`/`beat_to_sec`, Pipeline-Runner mit Cache und Hash-Invalidierung, CLI-Skelett mit `doctor`, Testsuite.
|
||||
- [x] **M1 – Extraktion und Stems**: Stufen 1 (ffmpeg 44.1 kHz stereo) und 2 (Demucs `htdemucs_ft` / `htdemucs_6s`, low-VRAM chunking mit segment/shifts, `instrumental.wav` und `vocals.wav`, SNR-Prüfung).
|
||||
- [ ] **M2 – Gesang**: Stufen 3 (Whisper+WhisperX) und 4 (torchcrepe), UltraStar-Writer, Eval-Gerüst.
|
||||
- [ ] **M3 – Tempo-Map**: Stufe 5 (beat_this).
|
||||
- [ ] **M4 – Akkorde**: Stufe 6 (Chordino / Transformer).
|
||||
- [ ] **M5 – Strumming**: Stufe 7 (librosa Onsets / Strumming-Muster).
|
||||
- [x] **M2 – Gesang**: Stufe 3 (`whisper-large-v3` + `pyphen`-Silbentrennung mit proportionalem Timing), Stufe 4 (`torchcrepe-full` mit Medianhöhe & Oktavfehler-Korrektur), UltraStar-Export (`song.txt`) & Reader, Eval-Framework mit Timing-MAE, Pitch-Genauigkeit (strikt & oktav-äquivalent) und WER via `jiwer`.
|
||||
- [x] **M3 – Tempo-Map**: Stufe 5 (`beat_this` Beat- & Downbeat-Tracking mit `librosa`-Fallback), intelligente Segmentierung (Anker nur bei echten Tempowechseln), Metronom-Klick-Track-Synthese (`.cache/click_track.wav`), BPM/GAP-Ableitung für UltraStar.
|
||||
- [x] **M4 – Akkorde**: Stufe 6 (Harte-Notation, Beat-synchrone Quantisierung über Tempo-Map, `chordino` & `template` Backends, Tonarterkennung nach Krumhansl-Schmuckler in `meta.json`).
|
||||
- [x] **M5 – Strumming**: Stufe 7 (Onset-Erkennung auf Gitarren-/Instrumental-Stem, Spektralschwerpunkt- & Beatphasen-Gradient für Down/Up-Richtungsvorschlag, Beat-Raster-Quantisierung, Muster-Verdichtung `D . D U . U D U`, als `experimental` markiert).
|
||||
- [ ] **M6 – Härtung**: Fehlerbehandlung, Logging, Dokumentation, Beispielpaket.
|
||||
|
||||
@ -9,9 +9,17 @@ dependencies = [
|
||||
"typer>=0.12.0",
|
||||
"rich>=13.7.0",
|
||||
"demucs>=4.0.0",
|
||||
"torch>=2.0.0",
|
||||
"torch>=2.4.0",
|
||||
"torchaudio>=2.4.0",
|
||||
"soundfile>=0.12.0",
|
||||
"julius>=0.2.7",
|
||||
"pyphen>=0.14.0",
|
||||
"torchcrepe>=0.0.23",
|
||||
"faster-whisper>=1.0.0",
|
||||
"scipy>=1.12.0",
|
||||
"jiwer>=3.0.0",
|
||||
"beat-this>=1.1.0",
|
||||
"chord-extractor>=0.1.3",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
@ -38,6 +46,18 @@ markers = [
|
||||
"integration: marks tests as integration tests",
|
||||
]
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cpu"
|
||||
url = "https://download.pytorch.org/whl/cpu"
|
||||
explicit = true
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cpu" }
|
||||
torchaudio = { index = "pytorch-cpu" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
vamp = ["numpy"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
target-version = "py312"
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"""Evaluation package."""
|
||||
|
||||
from songsplit.eval.metrics import calculate_timing_metrics
|
||||
from songsplit.eval.metrics import evaluate_vocals, normalize_text_for_wer
|
||||
from songsplit.eval.run_eval import run_evaluation
|
||||
|
||||
__all__ = ["calculate_timing_metrics", "run_evaluation"]
|
||||
__all__ = ["evaluate_vocals", "normalize_text_for_wer", "run_evaluation"]
|
||||
|
||||
@ -1,8 +1,122 @@
|
||||
"""Quality metrics against UltraStar reference (timing, pitch, WER)."""
|
||||
"""Quality metrics comparing predicted vocals against UltraStar reference ground-truth."""
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import jiwer
|
||||
import numpy as np
|
||||
|
||||
def calculate_timing_metrics(predicted: list[dict[str, Any]], reference: list[dict[str, Any]]) -> dict[str, float]:
|
||||
"""Calculate mean/median syllable onset error in ms and fraction within +-100ms."""
|
||||
raise NotImplementedError("Metrics will be implemented in M2.")
|
||||
from songsplit.export.ultrastar import UltraStarSong
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def normalize_text_for_wer(text: str) -> str:
|
||||
"""Normalize text: remove punctuation, lowercase, normalize whitespace."""
|
||||
# Remove UltraStar formatting tokens (~, -, etc.) and standard punctuation
|
||||
text = re.sub(r"[^\w\s]", "", text)
|
||||
text = re.sub(r"\s+", " ", text)
|
||||
return text.strip().lower()
|
||||
|
||||
|
||||
def evaluate_vocals(
|
||||
predicted: VocalsDocument,
|
||||
reference: UltraStarSong,
|
||||
max_match_distance_sec: float = 0.5,
|
||||
) -> dict[str, Any]:
|
||||
"""Calculate comprehensive timing, pitch, and WER metrics against UltraStar reference."""
|
||||
# Flatten reference syllables
|
||||
ref_notes = []
|
||||
for line in reference.lines:
|
||||
for note in line:
|
||||
# Skip empty whitespace notes
|
||||
if note.text.strip():
|
||||
ref_notes.append(note)
|
||||
|
||||
# Flatten predicted syllables
|
||||
pred_syllables = []
|
||||
for line in predicted.lines:
|
||||
for syl in line.syllables:
|
||||
if syl.text.strip():
|
||||
pred_syllables.append(syl)
|
||||
|
||||
if not ref_notes or not pred_syllables:
|
||||
return {
|
||||
"num_ref_syllables": len(ref_notes),
|
||||
"num_pred_syllables": len(pred_syllables),
|
||||
"mae_timing_ms": 0.0,
|
||||
"median_timing_ms": 0.0,
|
||||
"fraction_within_100ms": 0.0,
|
||||
"strict_pitch_accuracy": 0.0,
|
||||
"octave_equiv_pitch_accuracy": 0.0,
|
||||
"wer": 1.0 if not pred_syllables and ref_notes else 0.0,
|
||||
}
|
||||
|
||||
# Match each reference syllable to nearest predicted syllable within max_match_distance_sec
|
||||
timing_errors_ms = []
|
||||
strict_pitch_correct = []
|
||||
octave_pitch_correct = []
|
||||
|
||||
matched_pred_indices = set()
|
||||
for ref in ref_notes:
|
||||
best_idx = None
|
||||
best_diff = float("inf")
|
||||
|
||||
for idx, pred in enumerate(pred_syllables):
|
||||
diff = abs(pred.start - ref.start_sec)
|
||||
if diff < best_diff and diff <= max_match_distance_sec:
|
||||
best_diff = diff
|
||||
best_idx = idx
|
||||
|
||||
if best_idx is not None:
|
||||
matched_pred_indices.add(best_idx)
|
||||
pred = pred_syllables[best_idx]
|
||||
timing_errors_ms.append(best_diff * 1000.0)
|
||||
|
||||
# Pitch check
|
||||
pitch_diff = abs(pred.midi - ref.midi)
|
||||
is_strict = pitch_diff <= 0.5
|
||||
strict_pitch_correct.append(1.0 if is_strict else 0.0)
|
||||
|
||||
# Octave equivalent pitch check (mod 12)
|
||||
mod_diff = pitch_diff % 12.0
|
||||
octave_diff = min(mod_diff, 12.0 - mod_diff)
|
||||
is_octave = octave_diff <= 0.5
|
||||
octave_pitch_correct.append(1.0 if is_octave else 0.0)
|
||||
else:
|
||||
# Unmatched reference note -> penalty
|
||||
timing_errors_ms.append(max_match_distance_sec * 1000.0)
|
||||
strict_pitch_correct.append(0.0)
|
||||
octave_pitch_correct.append(0.0)
|
||||
|
||||
# 1. Timing metrics
|
||||
mae_timing_ms = float(np.mean(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||
median_timing_ms = float(np.median(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||
fraction_within_100ms = (
|
||||
float(np.mean([1.0 if err <= 100.0 else 0.0 for err in timing_errors_ms])) if timing_errors_ms else 0.0
|
||||
)
|
||||
|
||||
# 2. Pitch metrics
|
||||
strict_pitch_acc = float(np.mean(strict_pitch_correct)) if strict_pitch_correct else 0.0
|
||||
octave_pitch_acc = float(np.mean(octave_pitch_correct)) if octave_pitch_correct else 0.0
|
||||
|
||||
# 3. WER metric
|
||||
ref_words_raw = "".join(r.text for r in ref_notes)
|
||||
pred_words_raw = "".join(p.text for p in pred_syllables)
|
||||
norm_ref = normalize_text_for_wer(ref_words_raw)
|
||||
norm_pred = normalize_text_for_wer(pred_words_raw)
|
||||
|
||||
if norm_ref:
|
||||
wer_score = float(jiwer.wer(norm_ref, norm_pred))
|
||||
else:
|
||||
wer_score = 0.0 if not norm_pred else 1.0
|
||||
|
||||
return {
|
||||
"num_ref_syllables": len(ref_notes),
|
||||
"num_pred_syllables": len(pred_syllables),
|
||||
"mae_timing_ms": mae_timing_ms,
|
||||
"median_timing_ms": median_timing_ms,
|
||||
"fraction_within_100ms": fraction_within_100ms,
|
||||
"strict_pitch_accuracy": strict_pitch_acc,
|
||||
"octave_equiv_pitch_accuracy": octave_pitch_acc,
|
||||
"wer": wer_score,
|
||||
}
|
||||
|
||||
@ -1,8 +1,102 @@
|
||||
"""Evaluation runner for testset.toml."""
|
||||
"""Evaluation runner parsing testset.toml and producing eval_report.md and json."""
|
||||
|
||||
import json
|
||||
import time
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from songsplit.eval.metrics import evaluate_vocals
|
||||
from songsplit.export.ultrastar import parse_ultrastar
|
||||
from songsplit.pipeline import PipelineContext, get_default_pipeline
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def run_evaluation(testset_config: Path) -> dict[str, str]:
|
||||
"""Run full evaluation suite across test songs."""
|
||||
raise NotImplementedError("Evaluation runner will be implemented in M2.")
|
||||
def run_evaluation(testset_config: Path, output_report_dir: Path | None = None) -> dict[str, Any]:
|
||||
"""Run evaluation over songs defined in testset.toml."""
|
||||
testset_config = testset_config.resolve()
|
||||
with open(testset_config, "rb") as f:
|
||||
config_data = tomllib.load(f)
|
||||
|
||||
report_dir = output_report_dir or testset_config.parent
|
||||
report_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
songs = config_data.get("songs", [])
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
for song_entry in songs:
|
||||
name = song_entry.get("name", "Unnamed")
|
||||
audio_path = Path(song_entry["audio"]).resolve()
|
||||
ref_path = Path(song_entry["reference"]).resolve()
|
||||
lang = song_entry.get("lang", "de")
|
||||
|
||||
song_out_dir = report_dir / "eval_runs" / name
|
||||
ctx = PipelineContext(
|
||||
source_file=audio_path,
|
||||
output_dir=song_out_dir,
|
||||
lang=lang,
|
||||
target_stage="s4_pitch",
|
||||
)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
runner = get_default_pipeline()
|
||||
meta = runner.run(ctx)
|
||||
elapsed_sec = time.perf_counter() - t0
|
||||
|
||||
vocals_json = song_out_dir / "vocals.json"
|
||||
if not vocals_json.exists():
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"status": "failed",
|
||||
"error": "vocals.json not produced",
|
||||
"elapsed_sec": elapsed_sec,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
with open(vocals_json, encoding="utf-8") as vf:
|
||||
pred_vocals = VocalsDocument.model_validate(json.load(vf))
|
||||
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
metrics = evaluate_vocals(pred_vocals, ref_song)
|
||||
metrics["name"] = name
|
||||
metrics["status"] = "success"
|
||||
metrics["elapsed_sec"] = elapsed_sec
|
||||
metrics["stages_done"] = meta.stages_done
|
||||
results.append(metrics)
|
||||
|
||||
# Generate Markdown Report
|
||||
md_lines = [
|
||||
"# songsplit Evaluationsbericht (Eval Report)",
|
||||
"",
|
||||
f"Konfiguration: `{testset_config.name}`",
|
||||
f"Getestete Songs: {len(results)}",
|
||||
"",
|
||||
"| Song | Status | Timing MAE (ms) | Timing <= 100ms | Noten (strikt) | Noten (+-Oktav) | WER | Laufzeit (s) |",
|
||||
"|---|---|---|---|---|---|---|---|",
|
||||
]
|
||||
|
||||
for r in results:
|
||||
if r.get("status") == "success":
|
||||
md_lines.append(
|
||||
f"| {r['name']} | OK | {r['mae_timing_ms']:.1f} | "
|
||||
f"{r['fraction_within_100ms'] * 100:.1f}% | {r['strict_pitch_accuracy'] * 100:.1f}% | "
|
||||
f"{r['octave_equiv_pitch_accuracy'] * 100:.1f}% | {r['wer']:.2f} | {r['elapsed_sec']:.1f}s |"
|
||||
)
|
||||
else:
|
||||
md_lines.append(
|
||||
f"| {r.get('name', 'Song')} | FEHLER ({r.get('error')}) | - | - | - | - | - | {r.get('elapsed_sec', 0.0):.1f}s |"
|
||||
)
|
||||
|
||||
report_md_path = report_dir / "eval_report.md"
|
||||
report_json_path = report_dir / "eval_report.json"
|
||||
|
||||
with open(report_md_path, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(md_lines) + "\n")
|
||||
|
||||
report_data = {"songs": results, "timestamp": time.time()}
|
||||
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||
json.dump(report_data, f, indent=2)
|
||||
|
||||
return report_data
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
"""Export modules."""
|
||||
|
||||
from songsplit.export.ultrastar import export_ultrastar
|
||||
from songsplit.export.ultrastar import UltraStarNote, UltraStarSong, export_ultrastar, parse_ultrastar
|
||||
|
||||
__all__ = ["export_ultrastar"]
|
||||
__all__ = ["export_ultrastar", "parse_ultrastar", "UltraStarSong", "UltraStarNote"]
|
||||
|
||||
@ -1,8 +1,249 @@
|
||||
"""UltraStar format export and import."""
|
||||
"""UltraStar format export (Writer) and import/parsing (Reader).
|
||||
|
||||
Format specifications:
|
||||
- Headers: #TITLE, #ARTIST, #MP3, #BPM, #GAP, #LANGUAGE
|
||||
- Note types:
|
||||
': ' regular note
|
||||
'* ' golden note
|
||||
'F ' freestyle note
|
||||
'- ' line break
|
||||
'E' end of song
|
||||
- Beat resolution in UltraStar: 4 ticks per beat (16th notes).
|
||||
- Pitch in UltraStar: Halftones relative to C4 (MIDI 60).
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from songsplit.schema.meta import MetaDocument
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
from songsplit.tempo import sec_to_beat
|
||||
|
||||
|
||||
def export_ultrastar(song_dir: Path) -> Path:
|
||||
"""Export song package to UltraStar song.txt."""
|
||||
raise NotImplementedError("UltraStar export will be implemented in M2.")
|
||||
"""Export song package directory to UltraStar song.txt.
|
||||
|
||||
Reads meta.json, vocals.json, and tempo.json if present.
|
||||
"""
|
||||
song_dir = song_dir.resolve()
|
||||
meta_file = song_dir / "meta.json"
|
||||
vocals_file = song_dir / "vocals.json"
|
||||
tempo_file = song_dir / "tempo.json"
|
||||
output_txt = song_dir / "song.txt"
|
||||
|
||||
if not vocals_file.exists():
|
||||
raise FileNotFoundError(f"vocals.json not found in {song_dir}")
|
||||
|
||||
with open(vocals_file, encoding="utf-8") as f:
|
||||
vocals = VocalsDocument.model_validate(json.load(f))
|
||||
|
||||
meta = None
|
||||
if meta_file.exists():
|
||||
with open(meta_file, encoding="utf-8") as f:
|
||||
meta = MetaDocument.model_validate(json.load(f))
|
||||
|
||||
tempo = None
|
||||
if tempo_file.exists():
|
||||
with open(tempo_file, encoding="utf-8") as f:
|
||||
tempo = TempoDocument.model_validate(json.load(f))
|
||||
|
||||
title = meta.title if meta and meta.title else song_dir.name
|
||||
artist = meta.artist if meta and meta.artist else "Unknown Artist"
|
||||
language = meta.language if meta and meta.language else "German"
|
||||
|
||||
# Find earliest vocal syllable for GAP
|
||||
first_syllable_sec = 0.0
|
||||
for line in vocals.lines:
|
||||
if line.syllables:
|
||||
first_syllable_sec = line.syllables[0].start
|
||||
break
|
||||
|
||||
# Determine reference BPM
|
||||
if tempo and tempo.anchors:
|
||||
base_bpm = tempo.anchors[0].bpm
|
||||
else:
|
||||
base_bpm = 120.0
|
||||
|
||||
# In UltraStar, #BPM is 4x standard BPM (4 beats per quarter note)
|
||||
ultrastar_bpm = base_bpm * 4.0
|
||||
gap_ms = int(max(0.0, first_syllable_sec) * 1000.0)
|
||||
|
||||
# Audio reference file: vocals.wav if present, else original file
|
||||
mp3_name = "stems/vocals.wav" if (song_dir / "stems" / "vocals.wav").exists() else "extracted.wav"
|
||||
|
||||
out_lines = [
|
||||
f"#TITLE:{title}",
|
||||
f"#ARTIST:{artist}",
|
||||
f"#MP3:{mp3_name}",
|
||||
f"#BPM:{ultrastar_bpm:.2f}",
|
||||
f"#GAP:{gap_ms}",
|
||||
f"#LANGUAGE:{language}",
|
||||
]
|
||||
|
||||
def sec_to_ultrastar_beat(sec: float) -> int:
|
||||
rel_sec = max(0.0, sec - (gap_ms / 1000.0))
|
||||
if tempo and tempo.anchors:
|
||||
quarter_beats = sec_to_beat(rel_sec, tempo)
|
||||
return max(0, int(round(quarter_beats * 4.0)))
|
||||
else:
|
||||
beats_per_sec = base_bpm / 60.0
|
||||
return max(0, int(round(rel_sec * beats_per_sec * 4.0)))
|
||||
|
||||
current_beat = 0
|
||||
for line_idx, line in enumerate(vocals.lines):
|
||||
if not line.syllables:
|
||||
continue
|
||||
|
||||
for syl in line.syllables:
|
||||
syl_start_beat = sec_to_ultrastar_beat(syl.start)
|
||||
syl_end_beat = sec_to_ultrastar_beat(syl.end)
|
||||
duration_beats = max(1, syl_end_beat - syl_start_beat)
|
||||
|
||||
# Prevent overlap with previous syllable in same line
|
||||
if syl_start_beat < current_beat:
|
||||
syl_start_beat = current_beat
|
||||
|
||||
current_beat = syl_start_beat + duration_beats
|
||||
|
||||
# UltraStar pitch relative to C4 (MIDI 60)
|
||||
pitch = int(round(syl.midi - 60.0))
|
||||
tag = "*" if syl.golden else ":"
|
||||
|
||||
# Preserve trailing space or text
|
||||
txt = syl.text
|
||||
out_lines.append(f"{tag} {syl_start_beat} {duration_beats} {pitch} {txt}")
|
||||
|
||||
# Add line break if not the last line
|
||||
if line_idx < len(vocals.lines) - 1:
|
||||
line_break_beat = current_beat + 2
|
||||
out_lines.append(f"- {line_break_beat}")
|
||||
current_beat = line_break_beat + 1
|
||||
|
||||
out_lines.append("E")
|
||||
out_lines.append("")
|
||||
|
||||
with open(output_txt, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(out_lines))
|
||||
|
||||
return output_txt
|
||||
|
||||
|
||||
class UltraStarNote:
|
||||
"""A parsed note from an UltraStar file."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
note_type: str,
|
||||
start_beat: int,
|
||||
duration: int,
|
||||
pitch: int,
|
||||
text: str,
|
||||
start_sec: float = 0.0,
|
||||
end_sec: float = 0.0,
|
||||
midi: float = 60.0,
|
||||
):
|
||||
self.note_type = note_type
|
||||
self.start_beat = start_beat
|
||||
self.duration = duration
|
||||
self.pitch = pitch
|
||||
self.text = text
|
||||
self.start_sec = start_sec
|
||||
self.end_sec = end_sec
|
||||
self.midi = midi
|
||||
|
||||
|
||||
class UltraStarSong:
|
||||
"""A complete parsed UltraStar song structure."""
|
||||
|
||||
def __init__(self, headers: dict[str, str], lines: list[list[UltraStarNote]]):
|
||||
self.headers = headers
|
||||
self.lines = lines
|
||||
|
||||
@property
|
||||
def title(self) -> str:
|
||||
return self.headers.get("TITLE", "")
|
||||
|
||||
@property
|
||||
def artist(self) -> str:
|
||||
return self.headers.get("ARTIST", "")
|
||||
|
||||
@property
|
||||
def bpm(self) -> float:
|
||||
# Standard quarter-note BPM
|
||||
return float(self.headers.get("BPM", "480").replace(",", ".")) / 4.0
|
||||
|
||||
@property
|
||||
def gap_ms(self) -> float:
|
||||
return float(self.headers.get("GAP", "0").replace(",", "."))
|
||||
|
||||
|
||||
def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
||||
"""Parse an UltraStar .txt file into structured notes and absolute times in seconds."""
|
||||
headers: dict[str, str] = {}
|
||||
lines: list[list[UltraStarNote]] = []
|
||||
current_line: list[UltraStarNote] = []
|
||||
|
||||
with open(file_path, encoding="utf-8", errors="replace") as f:
|
||||
content = f.read()
|
||||
|
||||
raw_lines = content.splitlines()
|
||||
|
||||
for raw in raw_lines:
|
||||
line = raw.rstrip("\r\n")
|
||||
if not line or not line.strip():
|
||||
continue
|
||||
|
||||
if line.startswith("#"):
|
||||
# Header line: #KEY:VALUE
|
||||
match = re.match(r"^#([A-Za-z0-9_-]+):(.*)$", line.strip())
|
||||
if match:
|
||||
k, v = match.group(1).upper(), match.group(2).strip()
|
||||
headers[k] = v
|
||||
continue
|
||||
|
||||
if line.startswith("E"):
|
||||
# End of song
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
current_line = []
|
||||
break
|
||||
|
||||
if line.startswith("-"):
|
||||
# Line break
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
current_line = []
|
||||
continue
|
||||
|
||||
# Note line: : 10 4 2 text
|
||||
match = re.match(r"^([:*F])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line)
|
||||
if match:
|
||||
ntype, s_beat, dur, pitch, text = match.groups()
|
||||
note = UltraStarNote(
|
||||
note_type=ntype,
|
||||
start_beat=int(s_beat),
|
||||
duration=int(dur),
|
||||
pitch=int(pitch),
|
||||
text=text,
|
||||
)
|
||||
current_line.append(note)
|
||||
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
|
||||
# Calculate absolute timings in seconds for each note
|
||||
raw_bpm = float(headers.get("BPM", "480").replace(",", "."))
|
||||
gap_sec = float(headers.get("GAP", "0").replace(",", ".")) / 1000.0
|
||||
|
||||
# UltraStar tick duration in seconds = 60.0 / BPM
|
||||
sec_per_tick = 60.0 / raw_bpm if raw_bpm > 0 else 0.125
|
||||
|
||||
for line_notes in lines:
|
||||
for note in line_notes:
|
||||
note.start_sec = gap_sec + (note.start_beat * sec_per_tick)
|
||||
note.end_sec = note.start_sec + (note.duration * sec_per_tick)
|
||||
note.midi = float(note.pitch + 60)
|
||||
|
||||
return UltraStarSong(headers=headers, lines=lines)
|
||||
|
||||
@ -47,7 +47,6 @@ class StemsStage(Stage):
|
||||
return {
|
||||
"stems": ctx.stems,
|
||||
"quality": ctx.quality,
|
||||
"segment": 7 if ctx.quality == "fast" else 10,
|
||||
"shifts": 0 if ctx.quality == "fast" else 1,
|
||||
}
|
||||
|
||||
@ -100,7 +99,6 @@ class StemsStage(Stage):
|
||||
wav = (wav - ref.mean()) / (ref.std() + 1e-8)
|
||||
|
||||
params = self.get_params(ctx)
|
||||
segment = params["segment"]
|
||||
shifts = params["shifts"]
|
||||
|
||||
# Add batch dimension: [1, 2, samples]
|
||||
@ -114,7 +112,6 @@ class StemsStage(Stage):
|
||||
shifts=shifts,
|
||||
split=True,
|
||||
overlap=0.25,
|
||||
segment=segment,
|
||||
device=device,
|
||||
progress=False,
|
||||
)
|
||||
|
||||
@ -1,27 +1,179 @@
|
||||
"""Stage 3: Lyrics transcription & alignment (Whisper + WhisperX + hyphenation)."""
|
||||
"""Stage 3: Lyrics transcription & alignment (Whisper + pyphen hyphenation)."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pyphen
|
||||
|
||||
from songsplit.config import config
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
|
||||
|
||||
def hyphenate_word(word_text: str, dic: pyphen.Pyphen) -> list[str]:
|
||||
"""Split a word into syllables using pyphen while preserving punctuation and spacing."""
|
||||
stripped = word_text.strip()
|
||||
if not stripped:
|
||||
return [word_text]
|
||||
|
||||
# Separate leading/trailing punctuation from core word
|
||||
match = re.match(r"^(\W*)([\w\-]+)(\W*)$", stripped)
|
||||
if not match:
|
||||
return [word_text]
|
||||
|
||||
prefix, core, suffix = match.groups()
|
||||
|
||||
# Hyphenate core word
|
||||
hyphenated = dic.inserted(core)
|
||||
parts = hyphenated.split("-") if "-" in hyphenated else [core]
|
||||
|
||||
if len(parts) == 1:
|
||||
return [word_text]
|
||||
|
||||
# Attach prefix to first syllable, suffix (and trailing space if original had one) to last
|
||||
has_trailing_space = word_text.endswith(" ")
|
||||
res = []
|
||||
for i, p in enumerate(parts):
|
||||
s = p
|
||||
if i == 0 and prefix:
|
||||
s = prefix + s
|
||||
if i == len(parts) - 1:
|
||||
if suffix:
|
||||
s = s + suffix
|
||||
if has_trailing_space:
|
||||
s = s + " "
|
||||
res.append(s)
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def split_word_into_syllables_timed(
|
||||
word_text: str, start: float, end: float, dic: pyphen.Pyphen
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Hyphenate word and distribute duration proportionally to syllable length."""
|
||||
syllables = hyphenate_word(word_text, dic)
|
||||
duration = max(0.01, end - start)
|
||||
|
||||
if len(syllables) == 1:
|
||||
return [{"text": syllables[0], "start": start, "end": end}]
|
||||
|
||||
total_chars = sum(max(1, len(s.strip())) for s in syllables)
|
||||
timed = []
|
||||
cur_t = start
|
||||
|
||||
for i, syl in enumerate(syllables):
|
||||
char_len = max(1, len(syl.strip()))
|
||||
if i == len(syllables) - 1:
|
||||
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})
|
||||
cur_t = syl_end
|
||||
|
||||
return timed
|
||||
|
||||
|
||||
class LyricsStage(Stage):
|
||||
"""Stage 3 transcribes vocals into word-aligned syllables using Whisper and pyphen."""
|
||||
|
||||
name = "s3_lyrics"
|
||||
version = "1.0.0"
|
||||
model_name = "whisper-large-v3"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s2_stems"]
|
||||
|
||||
def __init__(self, model_name: str = "whisper-large-v3"):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.stems_dir / "vocals.wav"]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.output_dir / ".cache" / "lyrics_raw.json"]
|
||||
return [ctx.cache_dir / "lyrics_raw.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {"lang": ctx.lang}
|
||||
return {
|
||||
"lang": ctx.lang or "de",
|
||||
"model_size": "base" if ctx.quality == "fast" else "large-v3",
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
# Implementation in M2
|
||||
raise NotImplementedError("Stage s3_lyrics will be implemented in M2.")
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
vocals_wav = self.get_inputs(ctx)[0]
|
||||
if not vocals_wav.exists():
|
||||
raise FileNotFoundError(f"Vocals stem not found: {vocals_wav}")
|
||||
|
||||
params = self.get_params(ctx)
|
||||
lang = params["lang"]
|
||||
model_size = params["model_size"]
|
||||
self.model_name = f"whisper-{model_size}"
|
||||
|
||||
# Setup pyphen dictionary
|
||||
pyphen_lang = "de_DE" if lang.lower().startswith("de") else "en_US"
|
||||
try:
|
||||
dic = pyphen.Pyphen(lang=pyphen_lang)
|
||||
except Exception:
|
||||
dic = pyphen.Pyphen(lang="en_US")
|
||||
|
||||
# Determine compute device
|
||||
device_str = config.get_device(self.name)
|
||||
compute_type = "float16" if device_str.startswith("cuda") else "int8"
|
||||
device = "cuda" if device_str.startswith("cuda") else "cpu"
|
||||
|
||||
models_dir = config.get_models_dir()
|
||||
model = WhisperModel(
|
||||
model_size,
|
||||
device=device,
|
||||
compute_type=compute_type,
|
||||
download_root=str(models_dir),
|
||||
)
|
||||
|
||||
segments, info = model.transcribe(
|
||||
str(vocals_wav),
|
||||
language=lang,
|
||||
word_timestamps=True,
|
||||
vad_filter=True,
|
||||
)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
|
||||
for seg in segments:
|
||||
seg_syllables: list[dict[str, Any]] = []
|
||||
if seg.words:
|
||||
for idx, w in enumerate(seg.words):
|
||||
# Attach space to word text if not the last word in segment
|
||||
w_text = w.word.strip()
|
||||
if idx < len(seg.words) - 1:
|
||||
w_text += " "
|
||||
|
||||
w_sylls = split_word_into_syllables_timed(w_text, w.start, w.end, dic)
|
||||
seg_syllables.extend(w_sylls)
|
||||
else:
|
||||
# Segment without word timestamps fallback
|
||||
w_sylls = split_word_into_syllables_timed(seg.text.strip(), seg.start, seg.end, dic)
|
||||
seg_syllables.extend(w_sylls)
|
||||
|
||||
if seg_syllables:
|
||||
lines.append(
|
||||
{
|
||||
"start": seg.start,
|
||||
"end": seg.end,
|
||||
"text": seg.text.strip(),
|
||||
"syllables": seg_syllables,
|
||||
}
|
||||
)
|
||||
|
||||
output_data = {
|
||||
"language": lang,
|
||||
"detected_language": info.language if hasattr(info, "language") else lang,
|
||||
"lines": lines,
|
||||
}
|
||||
|
||||
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:
|
||||
json.dump(output_data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
@ -1,30 +1,222 @@
|
||||
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
|
||||
from songsplit.config import config
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
from songsplit.schema.base import GeneratedBy
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def hz_to_midi(hz: np.ndarray) -> np.ndarray:
|
||||
"""Convert frequency in Hz to fractional MIDI note numbers."""
|
||||
valid = hz > 0
|
||||
midi = np.zeros_like(hz, dtype=np.float32)
|
||||
midi[valid] = 69.0 + 12.0 * np.log2(hz[valid] / 440.0)
|
||||
return midi
|
||||
|
||||
|
||||
def correct_octave_errors(syllables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Correct isolated octave doubling/halving jumps relative to melodic context."""
|
||||
if len(syllables) < 3:
|
||||
return syllables
|
||||
|
||||
pitches = [s["midi"] for s in syllables]
|
||||
corrected = list(pitches)
|
||||
|
||||
for i in range(1, len(syllables) - 1):
|
||||
prev_p = corrected[i - 1]
|
||||
next_p = pitches[i + 1]
|
||||
cur_p = pitches[i]
|
||||
|
||||
local_mean = (prev_p + next_p) / 2.0
|
||||
diff = cur_p - local_mean
|
||||
|
||||
# Check for +12 (octave too high)
|
||||
if 10.5 <= diff <= 13.5:
|
||||
corrected[i] = cur_p - 12.0
|
||||
# Check for -12 (octave too low)
|
||||
elif -13.5 <= diff <= -10.5:
|
||||
corrected[i] = cur_p + 12.0
|
||||
# Check for +24 (two octaves too high)
|
||||
elif 22.5 <= diff <= 25.5:
|
||||
corrected[i] = cur_p - 24.0
|
||||
# Check for -24 (two octaves too low)
|
||||
elif -25.5 <= diff <= -22.5:
|
||||
corrected[i] = cur_p + 24.0
|
||||
|
||||
for s, p in zip(syllables, corrected, strict=False):
|
||||
s["midi"] = float(p)
|
||||
|
||||
return syllables
|
||||
|
||||
|
||||
class PitchStage(Stage):
|
||||
"""Stage 4 extracts vocal fundamental frequency and assigns median pitch per syllable."""
|
||||
|
||||
name = "s4_pitch"
|
||||
version = "1.0.0"
|
||||
model_name = "torchcrepe-full"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s3_lyrics"]
|
||||
|
||||
def __init__(self, model_name: str = "torchcrepe-full"):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [
|
||||
ctx.stems_dir / "vocals.wav",
|
||||
ctx.output_dir / ".cache" / "lyrics_raw.json",
|
||||
ctx.cache_dir / "lyrics_raw.json",
|
||||
]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.output_dir / "vocals.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {"hop_length_ms": 10, "viterbi": True}
|
||||
return {
|
||||
"hop_length_ms": 10,
|
||||
"voicing_threshold": 0.25,
|
||||
"crepe_model": "tiny" if ctx.quality == "fast" else "full",
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
# Implementation in M2
|
||||
raise NotImplementedError("Stage s4_pitch will be implemented in M2.")
|
||||
import torchcrepe
|
||||
|
||||
vocals_wav, lyrics_json = self.get_inputs(ctx)
|
||||
if not vocals_wav.exists():
|
||||
raise FileNotFoundError(f"Vocals stem not found: {vocals_wav}")
|
||||
if not lyrics_json.exists():
|
||||
raise FileNotFoundError(f"Lyrics file not found: {lyrics_json}")
|
||||
|
||||
with open(lyrics_json, encoding="utf-8") as f:
|
||||
lyrics_data = json.load(f)
|
||||
|
||||
params = self.get_params(ctx)
|
||||
hop_length_ms = params["hop_length_ms"]
|
||||
voicing_thresh = params["voicing_threshold"]
|
||||
crepe_model = params["crepe_model"]
|
||||
self.model_name = f"torchcrepe-{crepe_model}"
|
||||
|
||||
# Load audio using soundfile (resample to 16000 Hz for CREPE)
|
||||
audio_data, sr = sf.read(str(vocals_wav), dtype="float32")
|
||||
if audio_data.ndim > 1:
|
||||
# Downmix to mono
|
||||
audio_data = audio_data.mean(axis=-1)
|
||||
|
||||
crepe_sr = 16000
|
||||
hop_length = int(crepe_sr * (hop_length_ms / 1000.0))
|
||||
|
||||
# Convert to torch tensor
|
||||
audio_tensor = torch.from_numpy(audio_data).unsqueeze(0)
|
||||
if sr != crepe_sr:
|
||||
import julius
|
||||
|
||||
audio_tensor = julius.resample_frac(audio_tensor, sr, crepe_sr)
|
||||
|
||||
device_str = config.get_device(self.name)
|
||||
if device_str.startswith("cuda") and not torch.cuda.is_available():
|
||||
device_str = "cpu"
|
||||
device = torch.device(device_str)
|
||||
|
||||
# Run CREPE pitch prediction
|
||||
pitch_hz, periodicity = torchcrepe.predict(
|
||||
audio_tensor.to(device),
|
||||
crepe_sr,
|
||||
hop_length=hop_length,
|
||||
fmin=50,
|
||||
fmax=1006,
|
||||
model=crepe_model,
|
||||
batch_size=2048,
|
||||
device=device,
|
||||
return_periodicity=True,
|
||||
)
|
||||
|
||||
pitch_hz = pitch_hz.squeeze(0).cpu().numpy()
|
||||
periodicity = periodicity.squeeze(0).cpu().numpy()
|
||||
|
||||
# Frame timestamps: t_k = k * (hop_length / crepe_sr)
|
||||
frame_times = np.arange(len(pitch_hz)) * (hop_length / crepe_sr)
|
||||
midi_frames = hz_to_midi(pitch_hz)
|
||||
|
||||
# Process each line and syllable
|
||||
vocal_lines: list[VocalLine] = []
|
||||
|
||||
for line_dict in lyrics_data.get("lines", []):
|
||||
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"]
|
||||
|
||||
# Frames within syllable
|
||||
mask = (frame_times >= s_start) & (frame_times <= s_end)
|
||||
voiced_mask = mask & (periodicity >= voicing_thresh) & (pitch_hz > 50)
|
||||
|
||||
if np.any(voiced_mask):
|
||||
voiced_midis = midi_frames[voiced_mask]
|
||||
voiced_confs = periodicity[voiced_mask]
|
||||
median_midi = float(np.median(voiced_midis))
|
||||
conf = float(np.mean(voiced_confs))
|
||||
elif np.any(mask):
|
||||
median_midi = float(np.median(midi_frames[mask]))
|
||||
conf = float(np.mean(periodicity[mask])) * 0.5
|
||||
else:
|
||||
median_midi = 60.0
|
||||
conf = 0.1
|
||||
|
||||
line_syllables_raw.append(
|
||||
{
|
||||
"text": text,
|
||||
"start": s_start,
|
||||
"end": s_end,
|
||||
"midi": median_midi,
|
||||
"confidence": float(np.clip(conf, 0.0, 1.0)),
|
||||
}
|
||||
)
|
||||
|
||||
# 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",
|
||||
)
|
||||
for s in corrected_sylls
|
||||
]
|
||||
|
||||
if syl_objects:
|
||||
vocal_lines.append(
|
||||
VocalLine(
|
||||
start=line_dict["start"],
|
||||
end=line_dict["end"],
|
||||
syllables=syl_objects,
|
||||
)
|
||||
)
|
||||
|
||||
doc = VocalsDocument(
|
||||
schema_version="1.0",
|
||||
generated_by=GeneratedBy(
|
||||
stage=self.name,
|
||||
model=self.model_name,
|
||||
model_version=self.version,
|
||||
params=params,
|
||||
),
|
||||
lines=vocal_lines,
|
||||
)
|
||||
|
||||
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))
|
||||
|
||||
@ -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")
|
||||
|
||||
@ -1,18 +1,173 @@
|
||||
"""Stage 6: Chord recognition -> chords.json."""
|
||||
"""Stage 6: Chord recognition -> chords.json with beat-synchronous quantization."""
|
||||
|
||||
import json
|
||||
import re
|
||||
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.chords import ChordEvent, ChordsDocument
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.tempo import beat_to_sec, sec_to_beat
|
||||
|
||||
PITCH_CLASSES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
|
||||
|
||||
|
||||
def parse_harte_chord(label: str) -> tuple[str | None, str | None, str | None]:
|
||||
"""Parse Harte chord label into (root, quality, bass).
|
||||
|
||||
Examples:
|
||||
- 'C' -> ('C', 'maj', None)
|
||||
- 'Am' -> ('A', 'min', None)
|
||||
- 'G7' -> ('G', '7', None)
|
||||
- 'Dsus4' -> ('D', 'sus4', None)
|
||||
- 'F/A' -> ('F', 'maj', 'A')
|
||||
- 'N' -> (None, None, None)
|
||||
"""
|
||||
clean = label.strip()
|
||||
if not clean or clean.upper() in ("N", "NONE", "NO CHORD"):
|
||||
return None, None, None
|
||||
|
||||
# Check for bass note (slash chord): F/A
|
||||
bass = None
|
||||
if "/" in clean:
|
||||
parts = clean.split("/", 1)
|
||||
clean = parts[0]
|
||||
bass = parts[1].strip()
|
||||
|
||||
# Match Root (e.g. C, C#, Db, Eb, etc.)
|
||||
match = re.match(r"^([A-G][#b]?)(.*)$", clean)
|
||||
if not match:
|
||||
return clean, None, bass
|
||||
|
||||
root, rest = match.groups()
|
||||
|
||||
# Determine quality
|
||||
rest = rest.strip()
|
||||
if not rest or rest == "maj":
|
||||
quality = "maj"
|
||||
elif rest in ("m", "min"):
|
||||
quality = "min"
|
||||
elif rest in ("7", "dom7"):
|
||||
quality = "7"
|
||||
elif rest in ("m7", "min7"):
|
||||
quality = "min7"
|
||||
elif rest in ("maj7", "M7"):
|
||||
quality = "maj7"
|
||||
elif "sus4" in rest:
|
||||
quality = "sus4"
|
||||
elif "sus2" in rest:
|
||||
quality = "sus2"
|
||||
elif "dim" in rest:
|
||||
quality = "dim"
|
||||
elif "aug" in rest:
|
||||
quality = "aug"
|
||||
else:
|
||||
quality = rest
|
||||
|
||||
return root, quality, bass
|
||||
|
||||
|
||||
# Krumhansl-Schmuckler Key Profiles for key detection
|
||||
MAJOR_PROFILE = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
|
||||
MINOR_PROFILE = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
|
||||
|
||||
|
||||
def estimate_key(chroma_mean: np.ndarray) -> str:
|
||||
"""Estimate musical key from mean chromagram profile."""
|
||||
best_key = "C"
|
||||
best_corr = -1.0
|
||||
|
||||
chroma_norm = chroma_mean - np.mean(chroma_mean)
|
||||
|
||||
for i, pc in enumerate(PITCH_CLASSES):
|
||||
# Major correlation
|
||||
maj_roll = np.roll(MAJOR_PROFILE, i)
|
||||
maj_norm = maj_roll - np.mean(maj_roll)
|
||||
corr_maj = float(np.corrcoef(chroma_norm, maj_norm)[0, 1])
|
||||
if corr_maj > best_corr:
|
||||
best_corr = corr_maj
|
||||
best_key = f"{pc}"
|
||||
|
||||
# Minor correlation
|
||||
min_roll = np.roll(MINOR_PROFILE, i)
|
||||
min_norm = min_roll - np.mean(min_roll)
|
||||
corr_min = float(np.corrcoef(chroma_norm, min_norm)[0, 1])
|
||||
if corr_min > best_corr:
|
||||
best_corr = corr_min
|
||||
best_key = f"{pc}m"
|
||||
|
||||
return best_key
|
||||
|
||||
|
||||
def extract_chords_template(audio_data: np.ndarray, sr: int) -> list[tuple[float, str]]:
|
||||
"""Chroma-based chord template recognition as baseline/comparison."""
|
||||
if audio_data.ndim > 1:
|
||||
audio_data = audio_data.mean(axis=-1)
|
||||
|
||||
# Compute Chroma CQT
|
||||
hop_length = 2048
|
||||
chroma = librosa.feature.chroma_cqt(y=audio_data, sr=sr, hop_length=hop_length)
|
||||
times = librosa.frames_to_time(np.arange(chroma.shape[1]), sr=sr, hop_length=hop_length)
|
||||
|
||||
# 12 Major and 12 Minor chord templates
|
||||
templates: list[tuple[str, np.ndarray]] = []
|
||||
for i, root in enumerate(PITCH_CLASSES):
|
||||
# Major triad: root, +4, +7
|
||||
maj = np.zeros(12)
|
||||
maj[i] = 1.0
|
||||
maj[(i + 4) % 12] = 1.0
|
||||
maj[(i + 7) % 12] = 1.0
|
||||
templates.append((root, maj / np.linalg.norm(maj)))
|
||||
|
||||
# Minor triad: root, +3, +7
|
||||
min_t = np.zeros(12)
|
||||
min_t[i] = 1.0
|
||||
min_t[(i + 3) % 12] = 1.0
|
||||
min_t[(i + 7) % 12] = 1.0
|
||||
templates.append((f"{root}m", min_t / np.linalg.norm(min_t)))
|
||||
|
||||
raw_chords: list[tuple[float, str]] = []
|
||||
for t_idx, t_sec in enumerate(times):
|
||||
frame = chroma[:, t_idx]
|
||||
norm = np.linalg.norm(frame)
|
||||
if norm < 1e-4:
|
||||
raw_chords.append((float(t_sec), "N"))
|
||||
continue
|
||||
|
||||
frame_norm = frame / norm
|
||||
best_chord = "N"
|
||||
best_sim = -1.0
|
||||
|
||||
for chord_name, template in templates:
|
||||
sim = float(np.dot(frame_norm, template))
|
||||
if sim > best_sim:
|
||||
best_sim = sim
|
||||
best_chord = chord_name
|
||||
|
||||
raw_chords.append((float(t_sec), best_chord))
|
||||
|
||||
return raw_chords
|
||||
|
||||
|
||||
class ChordsStage(Stage):
|
||||
"""Stage 6 recognizes musical chords and quantizes them onto the beat grid."""
|
||||
|
||||
name = "s6_chords"
|
||||
version = "1.0.0"
|
||||
model_name = "chordino"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s5_tempo"]
|
||||
|
||||
def __init__(self, backend: str = "chordino"):
|
||||
self.backend = backend
|
||||
self.model_name = backend
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [
|
||||
ctx.stems_dir / "instrumental.wav",
|
||||
@ -23,8 +178,128 @@ class ChordsStage(Stage):
|
||||
return [ctx.output_dir / "chords.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {"backend": "chordino"}
|
||||
return {
|
||||
"backend": self.backend,
|
||||
"quantization": "beat",
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
# Implementation in M4
|
||||
raise NotImplementedError("Stage s6_chords will be implemented in M4.")
|
||||
inst_path, tempo_path = self.get_inputs(ctx)
|
||||
if not inst_path.exists():
|
||||
raise FileNotFoundError(f"Instrumental stem not found: {inst_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(inst_path), dtype="float32")
|
||||
|
||||
# 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))
|
||||
|
||||
meta = ctx.load_or_init_meta()
|
||||
meta.key = detected_key
|
||||
ctx.save_meta(meta)
|
||||
|
||||
params = self.get_params(ctx)
|
||||
backend = params.get("backend", "chordino")
|
||||
|
||||
time_chord_pairs: list[tuple[float, str]] = []
|
||||
|
||||
if backend == "chordino":
|
||||
try:
|
||||
from chord_extractor import ChordExtractor
|
||||
|
||||
extractor = ChordExtractor()
|
||||
chord_changes = extractor.extract(str(inst_path))
|
||||
for change in chord_changes:
|
||||
time_chord_pairs.append((float(change.timestamp), str(change.chord)))
|
||||
except Exception:
|
||||
# Fallback to template if chordino vamp is unavailable
|
||||
time_chord_pairs = extract_chords_template(audio_data, sr)
|
||||
self.model_name = "chroma-template"
|
||||
else:
|
||||
time_chord_pairs = extract_chords_template(audio_data, sr)
|
||||
self.model_name = "chroma-template"
|
||||
|
||||
# Beat-synchronous quantization
|
||||
info = sf.info(str(inst_path))
|
||||
total_duration_sec = info.duration
|
||||
|
||||
total_beats = int(np.ceil(sec_to_beat(total_duration_sec, tempo_doc)))
|
||||
total_beats = max(1, total_beats)
|
||||
|
||||
# Sample dominant chord per beat
|
||||
beat_chords: list[str] = []
|
||||
for b in range(total_beats):
|
||||
b_start_sec = beat_to_sec(float(b), tempo_doc)
|
||||
b_end_sec = beat_to_sec(float(b + 1), tempo_doc)
|
||||
|
||||
# Find chords active in this beat interval
|
||||
active = [ch for t, ch in time_chord_pairs if b_start_sec <= t < b_end_sec]
|
||||
if active:
|
||||
# Most frequent chord in this beat
|
||||
dom = max(set(active), key=active.count)
|
||||
else:
|
||||
# Chord active before b_start_sec
|
||||
prior = [ch for t, ch in time_chord_pairs if t <= b_start_sec]
|
||||
dom = prior[-1] if prior else "N"
|
||||
beat_chords.append(dom)
|
||||
|
||||
# Merge consecutive identical beat chords into ChordEvent segments
|
||||
chord_events: list[ChordEvent] = []
|
||||
cur_chord = beat_chords[0]
|
||||
cur_start_beat = 0.0
|
||||
|
||||
for b_idx in range(1, len(beat_chords)):
|
||||
ch = beat_chords[b_idx]
|
||||
if ch != cur_chord:
|
||||
root, quality, bass = parse_harte_chord(cur_chord)
|
||||
chord_events.append(
|
||||
ChordEvent(
|
||||
start_beat=cur_start_beat,
|
||||
end_beat=float(b_idx),
|
||||
label=cur_chord,
|
||||
root=root,
|
||||
quality=quality,
|
||||
bass=bass,
|
||||
confidence=0.85 if cur_chord != "N" else 0.5,
|
||||
source="auto",
|
||||
)
|
||||
)
|
||||
cur_chord = ch
|
||||
cur_start_beat = float(b_idx)
|
||||
|
||||
# Final segment
|
||||
root, quality, bass = parse_harte_chord(cur_chord)
|
||||
chord_events.append(
|
||||
ChordEvent(
|
||||
start_beat=cur_start_beat,
|
||||
end_beat=float(len(beat_chords)),
|
||||
label=cur_chord,
|
||||
root=root,
|
||||
quality=quality,
|
||||
bass=bass,
|
||||
confidence=0.85 if cur_chord != "N" else 0.5,
|
||||
source="auto",
|
||||
)
|
||||
)
|
||||
|
||||
chords_doc = ChordsDocument(
|
||||
schema_version="1.0",
|
||||
generated_by=GeneratedBy(
|
||||
stage=self.name,
|
||||
model=self.model_name,
|
||||
model_version=self.version,
|
||||
params=params,
|
||||
),
|
||||
chords=chord_events,
|
||||
)
|
||||
|
||||
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(chords_doc.model_dump_json(indent=2))
|
||||
|
||||
@ -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 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
|
||||
|
||||
|
||||
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):
|
||||
"""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]:
|
||||
return [
|
||||
ctx.stems_dir / "instrumental.wav",
|
||||
ctx.output_dir / "tempo.json",
|
||||
]
|
||||
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": "8th"}
|
||||
return {
|
||||
"grid": self.grid,
|
||||
"status": "experimental",
|
||||
"hop_length": 512,
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
# Implementation in M5
|
||||
raise NotImplementedError("Stage s7_strumming will be implemented in M5.")
|
||||
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))
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""Tempo-Map conversion between seconds and musical beats.
|
||||
"""Tempo-Map conversion between seconds and musical beats and click track generation.
|
||||
|
||||
As defined in the concept:
|
||||
- Vocals are in seconds
|
||||
@ -8,7 +8,9 @@ As defined in the concept:
|
||||
|
||||
from bisect import bisect_right
|
||||
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
import numpy as np
|
||||
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
|
||||
|
||||
|
||||
def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]:
|
||||
@ -62,3 +64,146 @@ def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float:
|
||||
anchor = anchors[idx]
|
||||
delta_beat = beat - anchor.beat
|
||||
return anchor.sec + delta_beat * (60.0 / anchor.bpm)
|
||||
|
||||
|
||||
def build_tempo_map_from_beats(
|
||||
beat_times: list[float] | np.ndarray,
|
||||
downbeat_times: list[float] | np.ndarray | None = None,
|
||||
min_tempo_change_bpm: float = 4.0,
|
||||
min_beats_for_change: int = 6,
|
||||
) -> TempoDocument:
|
||||
"""Construct a clean TempoDocument from raw detected beat and downbeat timestamps.
|
||||
|
||||
Only inserts new anchors for true persistent tempo changes, keeping single-anchor
|
||||
representation for songs with steady tempo.
|
||||
"""
|
||||
beats = np.sort(np.asarray(beat_times, dtype=np.float64))
|
||||
if len(beats) < 2:
|
||||
# Fallback default 120 BPM
|
||||
return TempoDocument(
|
||||
anchors=[TempoAnchor(sec=float(beats[0]) if len(beats) == 1 else 0.0, beat=0.0, bpm=120.0)],
|
||||
time_signature=TimeSignature(numerator=4, denominator=4),
|
||||
downbeat_offset=0,
|
||||
)
|
||||
|
||||
# Determine time signature and downbeat offset
|
||||
time_sig = TimeSignature(numerator=4, denominator=4)
|
||||
downbeat_offset = 0
|
||||
|
||||
if downbeat_times is not None and len(downbeat_times) >= 2:
|
||||
downbeats = np.sort(np.asarray(downbeat_times, dtype=np.float64))
|
||||
# Match downbeats to nearest beat indices
|
||||
downbeat_indices = []
|
||||
for db in downbeats:
|
||||
nearest_idx = int(np.argmin(np.abs(beats - db)))
|
||||
if np.abs(beats[nearest_idx] - db) < 0.2: # within 200ms
|
||||
downbeat_indices.append(nearest_idx)
|
||||
|
||||
if len(downbeat_indices) >= 2:
|
||||
intervals = np.diff(downbeat_indices)
|
||||
median_num = int(round(float(np.median(intervals))))
|
||||
if median_num in (3, 4, 6):
|
||||
time_sig = TimeSignature(numerator=median_num, denominator=4)
|
||||
downbeat_offset = downbeat_indices[0] % time_sig.numerator
|
||||
|
||||
# Calculate initial tempo from the beginning of the song
|
||||
ibis = np.diff(beats) # Inter-beat intervals in seconds
|
||||
valid_mask = (ibis > 0.15) & (ibis < 2.0) # 30 to 400 BPM
|
||||
clean_ibis = ibis[valid_mask]
|
||||
if len(clean_ibis) == 0:
|
||||
base_bpm = 120.0
|
||||
else:
|
||||
init_window = clean_ibis[: max(4, min_beats_for_change)]
|
||||
base_bpm = float(np.median(60.0 / init_window))
|
||||
|
||||
# Segment into anchors if persistent tempo shifts occur
|
||||
anchors = []
|
||||
current_sec = float(beats[0])
|
||||
current_beat = 0.0
|
||||
current_bpm = base_bpm
|
||||
|
||||
anchors.append(
|
||||
TempoAnchor(
|
||||
sec=round(current_sec, 3),
|
||||
beat=round(current_beat, 3),
|
||||
bpm=round(current_bpm, 2),
|
||||
)
|
||||
)
|
||||
|
||||
# Detect sustained tempo changes across window
|
||||
i = 0
|
||||
while i <= len(ibis) - min_beats_for_change:
|
||||
win_ibis = ibis[i : i + min_beats_for_change]
|
||||
# Check all intervals are valid
|
||||
if np.all((win_ibis > 0.15) & (win_ibis < 2.0)):
|
||||
win_bpms = 60.0 / win_ibis
|
||||
win_bpm = float(np.median(win_bpms))
|
||||
win_std = float(np.std(win_bpms))
|
||||
|
||||
# Trigger change only when the new section is stable and genuinely different
|
||||
if abs(win_bpm - current_bpm) >= min_tempo_change_bpm and win_std < (min_tempo_change_bpm * 0.75):
|
||||
new_sec = float(beats[i])
|
||||
# Calculate beat position from previous anchor
|
||||
elapsed_sec = new_sec - current_sec
|
||||
new_beat = current_beat + elapsed_sec * (current_bpm / 60.0)
|
||||
|
||||
current_sec = new_sec
|
||||
current_beat = new_beat
|
||||
current_bpm = win_bpm
|
||||
|
||||
anchors.append(
|
||||
TempoAnchor(
|
||||
sec=round(current_sec, 3),
|
||||
beat=round(current_beat, 3),
|
||||
bpm=round(current_bpm, 2),
|
||||
)
|
||||
)
|
||||
i += min_beats_for_change
|
||||
continue
|
||||
i += 1
|
||||
|
||||
return TempoDocument(
|
||||
anchors=anchors,
|
||||
time_signature=time_sig,
|
||||
downbeat_offset=downbeat_offset,
|
||||
)
|
||||
|
||||
|
||||
def generate_click_track(
|
||||
tempo_map: TempoDocument,
|
||||
duration_sec: float,
|
||||
sr: int = 44100,
|
||||
) -> np.ndarray:
|
||||
"""Generate a click track waveform aligned to the TempoDocument.
|
||||
|
||||
Downbeats receive a distinct high click (1600 Hz), regular beats a low click (800 Hz).
|
||||
"""
|
||||
total_samples = int(duration_sec * sr)
|
||||
click_audio = np.zeros(total_samples, dtype=np.float32)
|
||||
|
||||
click_len = int(sr * 0.02) # 20 ms
|
||||
t_click = np.linspace(0, 0.02, click_len, endpoint=False)
|
||||
envelope = np.exp(-t_click / 0.005).astype(np.float32)
|
||||
|
||||
high_click = (0.7 * np.sin(2 * np.pi * 1600.0 * t_click) * envelope).astype(np.float32)
|
||||
low_click = (0.5 * np.sin(2 * np.pi * 800.0 * t_click) * envelope).astype(np.float32)
|
||||
|
||||
# Step through beats from 0 until duration_sec
|
||||
num = tempo_map.time_signature.numerator
|
||||
offset = tempo_map.downbeat_offset
|
||||
|
||||
beat = 0.0
|
||||
while True:
|
||||
sec = beat_to_sec(beat, tempo_map)
|
||||
if sec > duration_sec:
|
||||
break
|
||||
if sec >= 0:
|
||||
idx = int(sec * sr)
|
||||
if idx + click_len <= total_samples:
|
||||
# Check if this beat is a downbeat
|
||||
is_downbeat = (int(round(beat)) % num) == (offset % num)
|
||||
sample_click = high_click if is_downbeat else low_click
|
||||
click_audio[idx : idx + click_len] += sample_click
|
||||
beat += 1.0
|
||||
|
||||
return click_audio
|
||||
|
||||
75
tests/test_chords.py
Normal file
75
tests/test_chords.py
Normal file
@ -0,0 +1,75 @@
|
||||
"""Unit tests for Harte chord parsing, key detection, and template chord recognition."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.pipeline.s6_chords import estimate_key, extract_chords_template, parse_harte_chord
|
||||
|
||||
|
||||
def test_parse_harte_chord_labels():
|
||||
# Major triad
|
||||
root, quality, bass = parse_harte_chord("C")
|
||||
assert root == "C"
|
||||
assert quality == "maj"
|
||||
assert bass is None
|
||||
|
||||
# Minor triad
|
||||
root, quality, bass = parse_harte_chord("Am")
|
||||
assert root == "A"
|
||||
assert quality == "min"
|
||||
assert bass is None
|
||||
|
||||
# Dominant 7th
|
||||
root, quality, bass = parse_harte_chord("G7")
|
||||
assert root == "G"
|
||||
assert quality == "7"
|
||||
assert bass is None
|
||||
|
||||
# Sus4
|
||||
root, quality, bass = parse_harte_chord("Dsus4")
|
||||
assert root == "D"
|
||||
assert quality == "sus4"
|
||||
assert bass is None
|
||||
|
||||
# Slash chord
|
||||
root, quality, bass = parse_harte_chord("F/A")
|
||||
assert root == "F"
|
||||
assert quality == "maj"
|
||||
assert bass == "A"
|
||||
|
||||
# No chord
|
||||
root, quality, bass = parse_harte_chord("N")
|
||||
assert root is None
|
||||
assert quality is None
|
||||
assert bass is None
|
||||
|
||||
|
||||
def test_estimate_key():
|
||||
# Synthetic C major profile (peaks at C, E, G -> indices 0, 4, 7)
|
||||
c_maj_chroma = np.zeros(12)
|
||||
c_maj_chroma[0] = 5.0
|
||||
c_maj_chroma[4] = 4.0
|
||||
c_maj_chroma[7] = 4.5
|
||||
assert estimate_key(c_maj_chroma) == "C"
|
||||
|
||||
# Synthetic A minor profile (peaks at A, C, E -> indices 9, 0, 4)
|
||||
a_min_chroma = np.zeros(12)
|
||||
a_min_chroma[9] = 5.0
|
||||
a_min_chroma[0] = 4.0
|
||||
a_min_chroma[4] = 4.5
|
||||
assert estimate_key(a_min_chroma) == "Am"
|
||||
|
||||
|
||||
def test_extract_chords_template_synthetic():
|
||||
sr = 22050
|
||||
duration = 1.0
|
||||
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
|
||||
|
||||
# Synthesize C major: C4 (261.63), E4 (329.63), G4 (392.00)
|
||||
c_chord = (np.sin(2 * np.pi * 261.63 * t) + np.sin(2 * np.pi * 329.63 * t) + np.sin(2 * np.pi * 392.00 * t)).astype(
|
||||
np.float32
|
||||
)
|
||||
|
||||
raw_chords = extract_chords_template(c_chord, sr)
|
||||
labels = [ch for _, ch in raw_chords]
|
||||
# Dominant detected chord should be "C"
|
||||
assert labels.count("C") > len(labels) * 0.5
|
||||
39
tests/test_lyrics.py
Normal file
39
tests/test_lyrics.py
Normal file
@ -0,0 +1,39 @@
|
||||
"""Unit tests for Stage 3 lyrics hyphenation and proportional timing."""
|
||||
|
||||
import pyphen
|
||||
|
||||
from songsplit.pipeline.s3_lyrics import hyphenate_word, split_word_into_syllables_timed
|
||||
|
||||
|
||||
def test_hyphenate_word_german():
|
||||
dic = pyphen.Pyphen(lang="de_DE")
|
||||
# "Guten" -> ["Gu", "ten"]
|
||||
sylls = hyphenate_word("Guten", dic)
|
||||
assert len(sylls) == 2
|
||||
assert "".join(sylls) == "Guten"
|
||||
|
||||
# With trailing punctuation and space: "Morgen! "
|
||||
sylls_punct = hyphenate_word("Morgen! ", dic)
|
||||
assert len(sylls_punct) == 2
|
||||
assert "".join(sylls_punct) == "Morgen! "
|
||||
|
||||
|
||||
def test_hyphenate_word_english():
|
||||
dic = pyphen.Pyphen(lang="en_US")
|
||||
# "Hello" -> ["Hel", "lo"]
|
||||
sylls = hyphenate_word("Hello", dic)
|
||||
assert len(sylls) == 2
|
||||
assert "".join(sylls) == "Hello"
|
||||
|
||||
|
||||
def test_split_word_into_syllables_timed():
|
||||
dic = pyphen.Pyphen(lang="en_US")
|
||||
# "Hello " duration 1.0s (from 10.0 to 11.0)
|
||||
timed = split_word_into_syllables_timed("Hello ", 10.0, 11.0, dic)
|
||||
assert len(timed) == 2
|
||||
assert timed[0]["start"] == 10.0
|
||||
assert timed[1]["end"] == 11.0
|
||||
assert timed[0]["end"] == timed[1]["start"]
|
||||
# Syllables should be "Hel" and "lo "
|
||||
assert timed[0]["text"] == "Hel"
|
||||
assert timed[1]["text"] == "lo "
|
||||
81
tests/test_metrics.py
Normal file
81
tests/test_metrics.py
Normal file
@ -0,0 +1,81 @@
|
||||
"""Unit tests for evaluation metrics (timing, pitch, WER)."""
|
||||
|
||||
import pytest
|
||||
|
||||
from songsplit.eval.metrics import evaluate_vocals, normalize_text_for_wer
|
||||
from songsplit.export.ultrastar import UltraStarNote, UltraStarSong
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def test_normalize_text_for_wer():
|
||||
raw = "Hallo, Welt! Wie geht's?"
|
||||
norm = normalize_text_for_wer(raw)
|
||||
assert norm == "hallo welt wie gehts"
|
||||
|
||||
|
||||
def test_evaluate_vocals_perfect_match():
|
||||
# Ground truth: 2 syllables
|
||||
ref_song = UltraStarSong(
|
||||
headers={"BPM": "480", "GAP": "1000"},
|
||||
lines=[
|
||||
[
|
||||
UltraStarNote(":", 0, 4, 0, "Hal", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||
UltraStarNote(":", 4, 4, 2, "lo", start_sec=1.5, end_sec=2.0, midi=62.0),
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
pred_doc = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=1.0,
|
||||
end=2.0,
|
||||
syllables=[
|
||||
VocalSyllable(text="Hal", start=1.0, end=1.5, midi=60.0),
|
||||
VocalSyllable(text="lo", start=1.5, end=2.0, midi=62.0),
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
metrics = evaluate_vocals(pred_doc, ref_song)
|
||||
assert metrics["mae_timing_ms"] == pytest.approx(0.0)
|
||||
assert metrics["median_timing_ms"] == pytest.approx(0.0)
|
||||
assert metrics["fraction_within_100ms"] == pytest.approx(1.0)
|
||||
assert metrics["strict_pitch_accuracy"] == pytest.approx(1.0)
|
||||
assert metrics["octave_equiv_pitch_accuracy"] == pytest.approx(1.0)
|
||||
assert metrics["wer"] == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_evaluate_vocals_octave_error_and_timing_offset():
|
||||
ref_song = UltraStarSong(
|
||||
headers={"BPM": "480", "GAP": "1000"},
|
||||
lines=[
|
||||
[
|
||||
# Note at 60.0, start 1.0
|
||||
UltraStarNote(":", 0, 4, 0, "Test", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
# Prediction is offset by 50ms and has octave error (72.0 vs 60.0)
|
||||
pred_doc = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=1.05,
|
||||
end=1.55,
|
||||
syllables=[
|
||||
VocalSyllable(text="Test", start=1.05, end=1.55, midi=72.0),
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
metrics = evaluate_vocals(pred_doc, ref_song)
|
||||
assert metrics["mae_timing_ms"] == pytest.approx(50.0, abs=1.0)
|
||||
assert metrics["fraction_within_100ms"] == pytest.approx(1.0)
|
||||
# Strict pitch should fail (72 != 60)
|
||||
assert metrics["strict_pitch_accuracy"] == pytest.approx(0.0)
|
||||
# Octave equivalent pitch should succeed (72 % 12 == 60 % 12)
|
||||
assert metrics["octave_equiv_pitch_accuracy"] == pytest.approx(1.0)
|
||||
assert metrics["wer"] == pytest.approx(0.0)
|
||||
98
tests/test_pipeline_m2.py
Normal file
98
tests/test_pipeline_m2.py
Normal file
@ -0,0 +1,98 @@
|
||||
"""End-to-end integration test for Milestone 2 (Lyrics, Pitch, UltraStar export, and Eval runner)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.eval.metrics import evaluate_vocals
|
||||
from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s4_pitch import PitchStage
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def test_m2_pitch_ultrastar_and_eval(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
stems_dir = song_dir / "stems"
|
||||
cache_dir = song_dir / ".cache"
|
||||
stems_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Create a 2.0s 440 Hz (A4 = MIDI 69) test vocal stem
|
||||
sr = 16000
|
||||
t = np.linspace(0, 2.0, int(sr * 2.0), endpoint=False)
|
||||
sine_wave = 0.5 * np.sin(2 * np.pi * 440.0 * t).astype(np.float32)
|
||||
vocals_wav = stems_dir / "vocals.wav"
|
||||
sf.write(str(vocals_wav), sine_wave, sr)
|
||||
|
||||
# 2. Write mock lyrics in .cache/lyrics_raw.json (two syllables)
|
||||
lyrics_data = {
|
||||
"language": "de",
|
||||
"lines": [
|
||||
{
|
||||
"start": 0.2,
|
||||
"end": 1.8,
|
||||
"text": "Hal-lo ",
|
||||
"syllables": [
|
||||
{"text": "Hal-", "start": 0.2, "end": 0.9},
|
||||
{"text": "lo ", "start": 0.9, "end": 1.8},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
(cache_dir / "lyrics_raw.json").write_text(json.dumps(lyrics_data, indent=2))
|
||||
|
||||
# 3. Write meta.json
|
||||
meta = MetaDocument(
|
||||
title="Integration Song",
|
||||
artist="Test Singer",
|
||||
language="de",
|
||||
duration_sec=2.0,
|
||||
source_file=SourceFileInfo(path=str(vocals_wav), sha256="fakehash", size_bytes=len(sine_wave)),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# 4. Run PitchStage (CREPE) with crepe_model="tiny" for fast test execution
|
||||
ctx = PipelineContext(
|
||||
source_file=vocals_wav,
|
||||
output_dir=song_dir,
|
||||
quality="fast", # uses tiny crepe model
|
||||
)
|
||||
pitch_stage = PitchStage()
|
||||
pitch_stage.run(ctx)
|
||||
|
||||
vocals_json = song_dir / "vocals.json"
|
||||
assert vocals_json.exists()
|
||||
|
||||
with open(vocals_json, encoding="utf-8") as f:
|
||||
doc = VocalsDocument.model_validate(json.load(f))
|
||||
|
||||
assert len(doc.lines) == 1
|
||||
sylls = doc.lines[0].syllables
|
||||
assert len(sylls) == 2
|
||||
# Sine wave is at 440 Hz -> MIDI 69.0
|
||||
assert 68.0 <= sylls[0].midi <= 70.0
|
||||
assert 68.0 <= sylls[1].midi <= 70.0
|
||||
assert sylls[0].confidence > 0.5
|
||||
|
||||
# 5. Export UltraStar song.txt
|
||||
txt_path = export_ultrastar(song_dir)
|
||||
assert txt_path.exists()
|
||||
|
||||
song = parse_ultrastar(txt_path)
|
||||
assert song.title == "Integration Song"
|
||||
assert len(song.lines) == 1
|
||||
assert len(song.lines[0]) == 2
|
||||
# Pitch relative to C4 (60) -> 69 - 60 = 9
|
||||
assert song.lines[0][0].pitch == 9
|
||||
|
||||
# 6. Evaluate predicted vocals against ground truth UltraStar song
|
||||
metrics = evaluate_vocals(doc, song)
|
||||
assert metrics["mae_timing_ms"] <= 50.0
|
||||
assert metrics["strict_pitch_accuracy"] >= 0.99
|
||||
assert metrics["octave_equiv_pitch_accuracy"] >= 0.99
|
||||
assert metrics["wer"] == 0.0
|
||||
94
tests/test_pipeline_m3.py
Normal file
94
tests/test_pipeline_m3.py
Normal file
@ -0,0 +1,94 @@
|
||||
"""Integration test for Milestone 3 (Stage 5 Tempo Map and Click Track)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s5_tempo import TempoStage
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def test_m3_tempo_stage_and_click_track(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
stems_dir = song_dir / "stems"
|
||||
cache_dir = song_dir / ".cache"
|
||||
stems_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Generate 6.0s synthetic drum beats at 120 BPM (beats at 0.0, 0.5, 1.0, 1.5, ...)
|
||||
sr = 44100
|
||||
duration_sec = 6.0
|
||||
audio = np.zeros(int(sr * duration_sec), dtype=np.float32)
|
||||
|
||||
# Place a 10ms burst pulse every 0.5s
|
||||
burst_len = int(sr * 0.01)
|
||||
burst = np.sin(2 * np.pi * 300.0 * np.linspace(0, 0.01, burst_len, endpoint=False)).astype(np.float32)
|
||||
|
||||
for t in np.arange(0.5, 5.5, 0.5):
|
||||
idx = int(t * sr)
|
||||
audio[idx : idx + burst_len] += burst
|
||||
|
||||
drums_wav = stems_dir / "drums.wav"
|
||||
sf.write(str(drums_wav), audio, sr)
|
||||
|
||||
# 2. Write meta.json
|
||||
meta = MetaDocument(
|
||||
title="Tempo Test Song",
|
||||
artist="Test Drummer",
|
||||
duration_sec=duration_sec,
|
||||
source_file=SourceFileInfo(path=str(drums_wav), sha256="fakehash", size_bytes=len(audio)),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# 3. Write minimal vocals.json
|
||||
vocals = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=1.0,
|
||||
end=2.0,
|
||||
syllables=[VocalSyllable(text="Beat", start=1.0, end=2.0, midi=60.0)],
|
||||
)
|
||||
]
|
||||
)
|
||||
(song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2))
|
||||
|
||||
# 4. Run TempoStage
|
||||
ctx = PipelineContext(source_file=drums_wav, output_dir=song_dir)
|
||||
stage = TempoStage()
|
||||
stage.run(ctx)
|
||||
|
||||
# 5. Verify tempo.json
|
||||
tempo_json = song_dir / "tempo.json"
|
||||
assert tempo_json.exists()
|
||||
|
||||
with open(tempo_json, encoding="utf-8") as f:
|
||||
doc = TempoDocument.model_validate(json.load(f))
|
||||
|
||||
assert len(doc.anchors) >= 1
|
||||
# Detected tempo should be around 120 BPM (or 60/240 subharmonic)
|
||||
bpm = doc.anchors[0].bpm
|
||||
assert (
|
||||
bpm == pytest.approx(120.0, abs=5.0)
|
||||
or bpm == pytest.approx(60.0, abs=5.0)
|
||||
or bpm == pytest.approx(240.0, abs=10.0)
|
||||
)
|
||||
|
||||
# 6. Verify click track audio generated
|
||||
click_track = cache_dir / "click_track.wav"
|
||||
assert click_track.exists()
|
||||
click_data, click_sr = sf.read(str(click_track))
|
||||
assert len(click_data) == len(audio)
|
||||
|
||||
# 7. Test UltraStar export derives BPM/GAP from tempo.json
|
||||
txt_path = export_ultrastar(song_dir)
|
||||
assert txt_path.exists()
|
||||
song = parse_ultrastar(txt_path)
|
||||
assert song.bpm == pytest.approx(doc.anchors[0].bpm, abs=1.0)
|
||||
76
tests/test_pipeline_m4.py
Normal file
76
tests/test_pipeline_m4.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Integration test for Milestone 4 (Stage 6 Beat-Quantized Chord Recognition)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s6_chords import ChordsStage
|
||||
from songsplit.schema.chords import ChordsDocument
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
|
||||
|
||||
def test_m4_chords_stage_pipeline(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
stems_dir = song_dir / "stems"
|
||||
stems_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Synthesize 4.0s instrumental audio:
|
||||
# 2.0s C major (261.63, 329.63, 392.00) + 2.0s A minor (220.0, 261.63, 329.63)
|
||||
sr = 22050
|
||||
t_half = np.linspace(0, 2.0, int(sr * 2.0), endpoint=False)
|
||||
|
||||
c_major = (
|
||||
np.sin(2 * np.pi * 261.63 * t_half) + np.sin(2 * np.pi * 329.63 * t_half) + np.sin(2 * np.pi * 392.00 * t_half)
|
||||
).astype(np.float32)
|
||||
|
||||
a_minor = (
|
||||
np.sin(2 * np.pi * 220.00 * t_half) + np.sin(2 * np.pi * 261.63 * t_half) + np.sin(2 * np.pi * 329.63 * t_half)
|
||||
).astype(np.float32)
|
||||
|
||||
inst_audio = np.concatenate([c_major, a_minor])
|
||||
inst_wav = stems_dir / "instrumental.wav"
|
||||
sf.write(str(inst_wav), inst_audio, sr)
|
||||
|
||||
# 2. Prepare tempo.json: 120 BPM starting at 0.0s (0.5s per beat)
|
||||
# 4.0s = 8 beats total (0.0 to 4.0 beat is C, 4.0 to 8.0 beat is Am)
|
||||
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.0, beat=0.0, bpm=120.0)])
|
||||
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
|
||||
|
||||
# 3. Prepare meta.json
|
||||
meta = MetaDocument(
|
||||
title="Chord Test Song",
|
||||
artist="Test Pianist",
|
||||
duration_sec=4.0,
|
||||
source_file=SourceFileInfo(path=str(inst_wav), sha256="fakehash", size_bytes=len(inst_audio)),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# 4. Run ChordsStage with template backend
|
||||
ctx = PipelineContext(source_file=inst_wav, output_dir=song_dir)
|
||||
stage = ChordsStage(backend="template")
|
||||
stage.run(ctx)
|
||||
|
||||
chords_json = song_dir / "chords.json"
|
||||
assert chords_json.exists()
|
||||
|
||||
with open(chords_json, encoding="utf-8") as f:
|
||||
doc = ChordsDocument.model_validate(json.load(f))
|
||||
|
||||
assert len(doc.chords) >= 1
|
||||
labels = [c.label for c in doc.chords]
|
||||
assert "C" in labels or "Am" in labels
|
||||
|
||||
# Check beat-based timing
|
||||
for ch in doc.chords:
|
||||
assert ch.start_beat >= 0.0
|
||||
assert ch.end_beat > ch.start_beat
|
||||
assert ch.confidence > 0.0
|
||||
|
||||
# 5. Verify meta.json updated with key
|
||||
updated_meta = ctx.load_or_init_meta()
|
||||
assert updated_meta.key in ("C", "Am")
|
||||
77
tests/test_pipeline_m5.py
Normal file
77
tests/test_pipeline_m5.py
Normal file
@ -0,0 +1,77 @@
|
||||
"""Integration test for Milestone 5 (Stage 7 Strumming Analysis)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s7_strumming import StrummingStage
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.strumming import StrummingDocument
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
|
||||
|
||||
def test_m5_strumming_pipeline(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
stems_dir = song_dir / "stems"
|
||||
stems_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Synthesize 4.0s audio with strumming acoustic pulses
|
||||
sr = 22050
|
||||
duration_sec = 4.0
|
||||
audio = np.zeros(int(sr * duration_sec), dtype=np.float32)
|
||||
|
||||
# Pulses every 0.25s (8th notes at 120 BPM: 0.5s per quarter beat -> 0.25s per 8th note)
|
||||
pulse_len = int(sr * 0.05)
|
||||
t_pulse = np.linspace(0, 0.05, pulse_len, endpoint=False)
|
||||
pulse = (np.sin(2 * np.pi * 350.0 * t_pulse) * np.exp(-t_pulse / 0.01)).astype(np.float32)
|
||||
|
||||
for onset_t in np.arange(0.25, 3.75, 0.25):
|
||||
idx = int(onset_t * sr)
|
||||
audio[idx : idx + pulse_len] += pulse
|
||||
|
||||
guitar_wav = stems_dir / "guitar.wav"
|
||||
sf.write(str(guitar_wav), audio, sr)
|
||||
|
||||
# 2. Prepare tempo.json at 120 BPM starting at 0.0s
|
||||
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.0, beat=0.0, bpm=120.0)])
|
||||
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
|
||||
|
||||
# 3. Prepare meta.json
|
||||
meta = MetaDocument(
|
||||
title="Strumming Test Song",
|
||||
artist="Test Guitarist",
|
||||
duration_sec=duration_sec,
|
||||
source_file=SourceFileInfo(path=str(guitar_wav), sha256="fakehash", size_bytes=len(audio)),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# 4. Run StrummingStage
|
||||
ctx = PipelineContext(source_file=guitar_wav, output_dir=song_dir)
|
||||
stage = StrummingStage(grid="8th")
|
||||
stage.run(ctx)
|
||||
|
||||
strum_json = song_dir / "strumming.json"
|
||||
assert strum_json.exists()
|
||||
|
||||
with open(strum_json, encoding="utf-8") as f:
|
||||
doc = StrummingDocument.model_validate(json.load(f))
|
||||
|
||||
assert len(doc.events) > 0
|
||||
for e in doc.events:
|
||||
# Quantized to 8th note grid (multiples of 0.5 beats)
|
||||
assert (e.beat * 2).is_integer()
|
||||
assert e.direction in ("down", "up")
|
||||
assert 0.0 <= e.strength <= 1.0
|
||||
assert 0.0 <= e.confidence <= 1.0
|
||||
|
||||
# Verify marked as experimental in generated_by metadata
|
||||
assert doc.generated_by is not None
|
||||
assert doc.generated_by.params.get("status") == "experimental"
|
||||
|
||||
# Patterns generated
|
||||
assert len(doc.patterns) > 0
|
||||
assert doc.patterns[0].grid == "8th"
|
||||
41
tests/test_pitch.py
Normal file
41
tests/test_pitch.py
Normal file
@ -0,0 +1,41 @@
|
||||
"""Unit tests for Stage 4 pitch processing (Hz to MIDI and octave error correction)."""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from songsplit.pipeline.s4_pitch import correct_octave_errors, hz_to_midi
|
||||
|
||||
|
||||
def test_hz_to_midi_standards():
|
||||
# A4 = 440 Hz -> MIDI 69
|
||||
# A3 = 220 Hz -> MIDI 57
|
||||
# C4 = 261.6256 Hz -> MIDI 60
|
||||
hz = np.array([440.0, 220.0, 261.6256])
|
||||
midi = hz_to_midi(hz)
|
||||
assert midi[0] == pytest.approx(69.0, abs=0.01)
|
||||
assert midi[1] == pytest.approx(57.0, abs=0.01)
|
||||
assert midi[2] == pytest.approx(60.0, abs=0.01)
|
||||
|
||||
|
||||
def test_correct_octave_errors():
|
||||
# Line with an octave spike in the middle: 60, 72 (+12 jump), 61
|
||||
syllables = [
|
||||
{"text": "A", "midi": 60.0},
|
||||
{"text": "B", "midi": 72.0}, # Isolated octave jump
|
||||
{"text": "C", "midi": 61.0},
|
||||
]
|
||||
corrected = correct_octave_errors(syllables)
|
||||
assert corrected[0]["midi"] == 60.0
|
||||
assert corrected[1]["midi"] == pytest.approx(60.0) # Corrected from 72 down to 60
|
||||
assert corrected[2]["midi"] == 61.0
|
||||
|
||||
|
||||
def test_no_correction_for_legitimate_contour():
|
||||
# Gradual rise: 60 -> 64 -> 67 (C major triad arpeggio)
|
||||
syllables = [
|
||||
{"text": "A", "midi": 60.0},
|
||||
{"text": "B", "midi": 64.0},
|
||||
{"text": "C", "midi": 67.0},
|
||||
]
|
||||
corrected = correct_octave_errors(syllables)
|
||||
assert corrected[1]["midi"] == 64.0
|
||||
@ -69,10 +69,8 @@ def test_stems_stage_chunking_params(tmp_path: Path):
|
||||
|
||||
ctx_fast = PipelineContext(source_file=source, output_dir=out_dir, quality="fast")
|
||||
params_fast = stage.get_params(ctx_fast)
|
||||
assert params_fast["segment"] == 7
|
||||
assert params_fast["shifts"] == 0
|
||||
|
||||
ctx_best = PipelineContext(source_file=source, output_dir=out_dir, quality="best")
|
||||
params_best = stage.get_params(ctx_best)
|
||||
assert params_best["segment"] == 10
|
||||
assert params_best["shifts"] == 1
|
||||
|
||||
39
tests/test_strumming.py
Normal file
39
tests/test_strumming.py
Normal file
@ -0,0 +1,39 @@
|
||||
"""Unit tests for strumming direction estimation and pattern aggregation."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.pipeline.s7_strumming import aggregate_strum_patterns, estimate_strum_direction
|
||||
from songsplit.schema.strumming import StrumEvent
|
||||
|
||||
|
||||
def test_estimate_strum_direction_phase_prior():
|
||||
sr = 22050
|
||||
audio = np.random.randn(sr).astype(np.float32)
|
||||
|
||||
# On-beat (beat 0.0) -> down
|
||||
dir_down, conf_down = estimate_strum_direction(audio, sr, onset_sec=0.1, beat=0.0)
|
||||
assert dir_down == "down"
|
||||
assert conf_down >= 0.5
|
||||
|
||||
# Off-beat (beat 0.5) -> up
|
||||
dir_up, conf_up = estimate_strum_direction(audio, sr, onset_sec=0.1, beat=0.5)
|
||||
assert dir_up == "up"
|
||||
assert conf_up >= 0.5
|
||||
|
||||
|
||||
def test_aggregate_strum_patterns_island_strum():
|
||||
# Famous "island strum": D . D U . U D U (slots: 0, 1, 2, 3, 4, 5, 6, 7 on 8th grid)
|
||||
# slots: 0.0 (D), 1.0 (D), 1.5 (U), 2.5 (U), 3.0 (D), 3.5 (U)
|
||||
events = [
|
||||
StrumEvent(beat=0.0, direction="down", strength=0.9, confidence=0.8),
|
||||
StrumEvent(beat=1.0, direction="down", strength=0.8, confidence=0.8),
|
||||
StrumEvent(beat=1.5, direction="up", strength=0.7, confidence=0.7),
|
||||
StrumEvent(beat=2.5, direction="up", strength=0.7, confidence=0.7),
|
||||
StrumEvent(beat=3.0, direction="down", strength=0.8, confidence=0.8),
|
||||
StrumEvent(beat=3.5, direction="up", strength=0.7, confidence=0.7),
|
||||
]
|
||||
|
||||
patterns = aggregate_strum_patterns(events, total_beats=4.0, grid="8th", pattern_beats=4.0, section_beats=4.0)
|
||||
assert len(patterns) == 1
|
||||
assert patterns[0].pattern == "D . D U . U D U"
|
||||
assert patterns[0].grid == "8th"
|
||||
63
tests/test_tempo_detection.py
Normal file
63
tests/test_tempo_detection.py
Normal file
@ -0,0 +1,63 @@
|
||||
"""Unit tests for tempo map builder and click track generator."""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
|
||||
from songsplit.tempo import build_tempo_map_from_beats, generate_click_track
|
||||
|
||||
|
||||
def test_build_tempo_map_constant_tempo():
|
||||
# 120 BPM = 0.5s per beat, 16 beats = 8.0s
|
||||
beat_times = np.arange(0.5, 8.5, 0.5)
|
||||
# Downbeats every 4 beats (indices 0, 4, 8, 12 -> 0.5, 2.5, 4.5, 6.5)
|
||||
downbeat_times = beat_times[::4]
|
||||
|
||||
tempo_doc = build_tempo_map_from_beats(beat_times, downbeat_times)
|
||||
|
||||
# Should only create 1 anchor for steady tempo
|
||||
assert len(tempo_doc.anchors) == 1
|
||||
anchor = tempo_doc.anchors[0]
|
||||
assert anchor.bpm == pytest.approx(120.0, abs=0.5)
|
||||
assert anchor.sec == pytest.approx(0.5, abs=0.01)
|
||||
assert tempo_doc.time_signature.numerator == 4
|
||||
assert tempo_doc.downbeat_offset == 0
|
||||
|
||||
|
||||
def test_build_tempo_map_3_4_time_signature():
|
||||
# 3/4 time signature: downbeats every 3 beats
|
||||
beat_times = np.arange(0.0, 9.0, 0.5) # 120 BPM
|
||||
downbeat_times = beat_times[::3]
|
||||
|
||||
tempo_doc = build_tempo_map_from_beats(beat_times, downbeat_times)
|
||||
assert tempo_doc.time_signature.numerator == 3
|
||||
|
||||
|
||||
def test_build_tempo_map_sustained_tempo_change():
|
||||
# Section 1: 120 BPM (0.5s per beat) for 16 beats -> 8.0s
|
||||
sec1 = np.arange(0.0, 8.0, 0.5)
|
||||
# Section 2: 150 BPM (0.4s per beat) for 16 beats -> 6.4s
|
||||
sec2 = 8.0 + np.arange(0.0, 6.4, 0.4)
|
||||
all_beats = np.concatenate([sec1, sec2])
|
||||
|
||||
tempo_doc = build_tempo_map_from_beats(all_beats, min_tempo_change_bpm=3.0, min_beats_for_change=6)
|
||||
# Should detect 2 anchors: one around 120 BPM, one around 150 BPM
|
||||
assert len(tempo_doc.anchors) >= 2
|
||||
assert tempo_doc.anchors[0].bpm == pytest.approx(120.0, abs=1.0)
|
||||
assert tempo_doc.anchors[1].bpm == pytest.approx(150.0, abs=2.0)
|
||||
|
||||
|
||||
def test_generate_click_track():
|
||||
tempo_doc = TempoDocument(
|
||||
anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)],
|
||||
time_signature=TimeSignature(numerator=4, denominator=4),
|
||||
downbeat_offset=0,
|
||||
)
|
||||
sr = 44100
|
||||
duration_sec = 4.0
|
||||
clicks = generate_click_track(tempo_doc, duration_sec=duration_sec, sr=sr)
|
||||
|
||||
assert len(clicks) == int(duration_sec * sr)
|
||||
# At sec=0.5, there should be non-zero audio (first beat click)
|
||||
click_idx = int(0.5 * sr)
|
||||
assert np.max(np.abs(clicks[click_idx : click_idx + 100])) > 0.1
|
||||
81
tests/test_ultrastar.py
Normal file
81
tests/test_ultrastar.py
Normal file
@ -0,0 +1,81 @@
|
||||
"""Unit tests for UltraStar writer and reader round-trip."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def test_ultrastar_writer_and_reader(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
song_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Prepare meta.json
|
||||
meta = MetaDocument(
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
language="de",
|
||||
duration_sec=30.0,
|
||||
source_file=SourceFileInfo(path="/tmp/test.mp3", sha256="abc", size_bytes=100),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# 2. Prepare tempo.json (120 BPM)
|
||||
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)])
|
||||
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
|
||||
|
||||
# 3. Prepare vocals.json
|
||||
vocals = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=0.5,
|
||||
end=2.0,
|
||||
syllables=[
|
||||
VocalSyllable(text="Hal-", start=0.5, end=1.0, midi=60.0),
|
||||
VocalSyllable(text="lo ", start=1.0, end=2.0, midi=62.0),
|
||||
],
|
||||
),
|
||||
VocalLine(
|
||||
start=3.0,
|
||||
end=4.5,
|
||||
syllables=[
|
||||
VocalSyllable(text="Welt", start=3.0, end=4.5, midi=64.0),
|
||||
],
|
||||
),
|
||||
]
|
||||
)
|
||||
(song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2))
|
||||
|
||||
# 4. Export to UltraStar song.txt
|
||||
txt_path = export_ultrastar(song_dir)
|
||||
assert txt_path.exists()
|
||||
|
||||
content = txt_path.read_text(encoding="utf-8")
|
||||
assert "#TITLE:Test Song" in content
|
||||
assert "#ARTIST:Test Artist" in content
|
||||
assert "#BPM:480.00" in content # 120 * 4 = 480
|
||||
assert "#GAP:500" in content # 0.5s = 500 ms
|
||||
assert "E" in content
|
||||
|
||||
# 5. Parse back using parse_ultrastar
|
||||
parsed = parse_ultrastar(txt_path)
|
||||
assert parsed.title == "Test Song"
|
||||
assert parsed.artist == "Test Artist"
|
||||
assert parsed.bpm == 120.0
|
||||
assert parsed.gap_ms == 500.0
|
||||
|
||||
assert len(parsed.lines) == 2
|
||||
line1 = parsed.lines[0]
|
||||
assert len(line1) == 2
|
||||
assert line1[0].text == "Hal-"
|
||||
assert line1[0].midi == 60.0
|
||||
assert line1[1].text == "lo "
|
||||
assert line1[1].midi == 62.0
|
||||
|
||||
line2 = parsed.lines[1]
|
||||
assert len(line2) == 1
|
||||
assert line2[0].text == "Welt"
|
||||
assert line2[0].midi == 64.0
|
||||
Reference in New Issue
Block a user