Files
unmix/tests/test_align.py
wlkns-dev c761a244d8 feat(lyrics): fetch lyrics text from LRCLIB (--lyrics-from lrclib)
Text only; the audio alignment is unchanged. The release is chosen by length
(within 5 s of the audio) and live/acoustic/remix/karaoke versions rank last.
The chosen release is recorded in meta.json as lyrics_source.
Local use only: lyrics are copyrighted and must not be redistributed.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 11:55:56 +01:00

131 lines
5.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Unit tests for text-guided lyrics alignment (CTC forced alignment, lyrics file parsing)."""
import pytest
import torch
from unmix.pipeline import align
from unmix.pipeline.align import align_words, clean_word, lyrics_to_timed_lines, read_lyrics_lines
LABELS = ("-", "|", "A", "B", "C", "D", "E", "'")
def test_read_plain_lyrics_skips_blank_lines_and_section_markers(tmp_path):
f = tmp_path / "lyrics.txt"
f.write_text("[Verse 1]\nWe'll do it all\n\n Everything on our own \n(Chorus)\nIf I lay here\n", encoding="utf-8")
assert read_lyrics_lines(f) == [
["We'll", "do", "it", "all"],
["Everything", "on", "our", "own"],
["If", "I", "lay", "here"],
]
def test_read_lyrics_from_ultrastar_uses_text_and_line_structure(tmp_path):
f = tmp_path / "song.txt"
f.write_text(
"#TITLE:T\n#ARTIST:A\n#BPM:120\n#GAP:0\n"
": 0 4 4 We \n: 5 4 4 do \n: 10 4 4 it\n- 20\n: 24 4 4 Ev\n: 28 4 4 ~ery \n: 32 4 4 day\nE\n",
encoding="utf-8",
)
assert read_lyrics_lines(f) == [["We", "do", "it"], ["Every", "day"]]
def test_clean_word_maps_to_model_alphabet():
assert clean_word("Bad'e,", LABELS, "en") == "BAD'E"
assert clean_word("Ad’e", LABELS, "en") == "AD'E" # typographic apostrophe
assert clean_word("1234!", LABELS, "en") == "" # nothing alignable
def _emissions(frames: list[str]) -> torch.Tensor:
"""Log-probs that put (almost) all mass on the given label per frame; '-' is the CTC blank."""
idx = {c: i for i, c in enumerate(LABELS)}
em = torch.full((len(frames), len(LABELS)), -20.0)
for t, c in enumerate(frames):
em[t, idx[c]] = 0.0
return em
def test_align_words_returns_monotonic_word_times():
# frame: 0 1 2 3 4 5 6 7 8
frames = ["-", "A", "B", "-", "-", "C", "D", "D", "-"]
em = _emissions(frames)
res = align_words(em, [["AB"], ["CD"]], LABELS)
(s1, e1), (s2, e2) = res[(0, 0)], res[(1, 0)]
assert s1 == pytest.approx(1 * align.FRAME_SEC)
assert e1 <= s2
assert s2 == pytest.approx(5 * align.FRAME_SEC)
assert e2 > s2
def test_align_words_rejects_too_long_text():
em = _emissions(["A", "B"])
with pytest.raises(ValueError, match="too long"):
align_words(em, [["ABABAB"]], LABELS)
def test_lyrics_to_timed_lines_builds_syllables_and_skips_unalignable_words(monkeypatch, tmp_path):
class FakeBundle:
sample_rate = 16000
def get_labels(self):
return LABELS
frames = ["-", "A", "B", "-", "-", "C", "D", "-", "-", "-"]
monkeypatch.setattr(align, "load_aligner", lambda lang: (FakeBundle(), object()))
monkeypatch.setattr(align, "compute_emissions", lambda wav, model, bundle: _emissions(frames))
def syllabify(text, start, end):
return [{"text": text, "start": start, "end": end, "word_end": text.endswith(" ")}]
lines = lyrics_to_timed_lines([["ab", "...", "cd"]], tmp_path / "v.wav", "en", syllabify)
assert len(lines) == 1
texts = [s["text"] for s in lines[0]["syllables"]]
assert texts == ["ab ", "cd"] # "..." has no alignable characters and is skipped
assert lines[0]["text"] == "ab cd"
assert lines[0]["start"] < lines[0]["end"]
def test_unsupported_language_gives_clear_error():
with pytest.raises(ValueError, match="supports languages"):
align.load_aligner("fr")
def test_is_ultrastar_file_detects_ultrastar_but_not_plain_text(tmp_path):
from unmix.pipeline.align import is_ultrastar_file
us = tmp_path / "us.txt"
us.write_text("#TITLE:T\n#BPM:120\n#GAP:0\n: 0 4 4 We \nE\n", encoding="utf-8")
plain = tmp_path / "plain.txt"
plain.write_text("We do it all\nEverything on our own\n", encoding="utf-8")
assert is_ultrastar_file(us)
assert not is_ultrastar_file(plain)
def test_pick_version_chooses_length_match_and_skips_instrumentals_and_empty():
import pytest
from unmix.pipeline.lrclib import LyricsLookupError, pick_version
results = [
{"trackName": "A", "plainLyrics": None, "duration": 221.0},
{"trackName": "B", "plainLyrics": "la", "instrumental": True, "duration": 221.0},
{"trackName": "C", "plainLyrics": "text", "duration": 266.0},
{"trackName": "D", "plainLyrics": "text", "duration": 222.0},
]
assert pick_version(results, 221.5)["trackName"] == "D"
with pytest.raises(LyricsLookupError, match="passender Länge"):
pick_version(results, 120.0)
with pytest.raises(LyricsLookupError, match="kein Eintrag"):
pick_version([{"plainLyrics": None, "duration": 221.0}], 221.0)
def test_pick_version_prefers_studio_over_live_when_both_fit():
from unmix.pipeline.lrclib import pick_version
results = [
{"trackName": "Chasing Cars", "albumName": "Live in Studio - Acoustic", "plainLyrics": "a", "duration": 268.0},
{"trackName": "Chasing Cars", "albumName": "Eyes Open", "plainLyrics": "b", "duration": 270.0},
]
assert pick_version(results, 268.0)["albumName"] == "Eyes Open"
# if only the live version fits, it is still used
assert pick_version(results[:1], 268.0)["albumName"].startswith("Live")