feat(lyrics): implement stage 3 Whisper transcription and pyphen hyphenation
This commit is contained in:
@ -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)
|
||||
|
||||
Reference in New Issue
Block a user