7 Commits

17 changed files with 1970 additions and 158 deletions

View File

@ -46,7 +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.
- [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`.
- [ ] **M3 – Tempo-Map**: Stufe 5 (beat_this).
- [ ] **M3 – Tempo-Map**: Stufe 5 (beat_this).
- [ ] **M4 – Akkorde**: Stufe 6 (Chordino / Transformer).
- [ ] **M5 – Strumming**: Stufe 7 (librosa Onsets / Strumming-Muster).

View File

@ -9,9 +9,15 @@ 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",
]
[project.optional-dependencies]
@ -38,6 +44,15 @@ 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.ruff]
line-length = 120
target-version = "py312"

View File

@ -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"]

View File

@ -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,
}

View File

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

View File

@ -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"]

View File

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

View File

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

View File

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

View File

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

39
tests/test_lyrics.py Normal file
View 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
View 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
View 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

41
tests/test_pitch.py Normal file
View 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

View File

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

81
tests/test_ultrastar.py Normal file
View 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

922
uv.lock generated

File diff suppressed because it is too large Load Diff