diff --git a/src/songsplit/pipeline/s3_lyrics.py b/src/songsplit/pipeline/s3_lyrics.py index fe2ff2a..7c4e229 100644 --- a/src/songsplit/pipeline/s3_lyrics.py +++ b/src/songsplit/pipeline/s3_lyrics.py @@ -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) diff --git a/tests/test_lyrics.py b/tests/test_lyrics.py new file mode 100644 index 0000000..9d00cd0 --- /dev/null +++ b/tests/test_lyrics.py @@ -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 "