From c761a244d84c9b09c8c601f07947b4ddbdef0d66 Mon Sep 17 00:00:00 2001 From: wlkns-dev Date: Sat, 7 Nov 2026 11:55:56 +0100 Subject: [PATCH] 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 --- README.md | 6 ++- src/unmix/cli.py | 29 ++++++++++++ src/unmix/pipeline/lrclib.py | 85 ++++++++++++++++++++++++++++++++++++ src/unmix/schema/meta.py | 1 + tests/test_align.py | 30 +++++++++++++ 5 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 src/unmix/pipeline/lrclib.py diff --git a/README.md b/README.md index 47eb0dc..004eeb7 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,9 @@ unmix analyze song.mp3 -o output_song/ --lang en --ultrastar ground_truth_song.t # Modus 3: nur Text (richtet den Text per Forced Alignment am Gesang aus, statt Whisper) unmix analyze song.mp3 -o output_song/ --lang en --lyrics lyrics.txt +# Modus 3 mit Text von LRCLIB (nur lokal nutzen, Texte nicht weitergeben) +unmix analyze song.mp3 -o output_song/ --lang en --lyrics-from lrclib --artist "Snow Patrol" --title "Chasing Cars" + # Schneller Direkt-Import (übernimmt UltraStar-Gesang, rechnet nur Stems/Akkorde/Tempo) unmix import-ultrastar ground_truth_song.txt song.mp3 -o output_song/ ``` @@ -163,7 +166,8 @@ Jede Analyse läuft in genau einem Modus. Der Modus steht danach in `meta.json` - **Modus 2** ist die Messlatte: Zusätzlich zum Songpack entsteht `training_diff.json` mit dem Vergleich der KI-Vorhersage Note für Note (systematischer Timing- und Dauern-Drift, übersehene Noten, Melismen). Die KI-Vorhersage wird dafür in `.cache/vocals_ai.json` gesichert, damit ein späterer Lauf im selben Ordner nicht die Referenz mit sich selbst vergleicht. - **Modus 3** braucht eine Textdatei, eine Zeile pro gesungener Zeile. Abschnittsmarker wie `[Verse 1]` werden ignoriert. Auch eine UltraStar-Datei ist als Text möglich, dann werden nur Text und Zeilenumbrüche übernommen, nicht die Zeiten. Unterstützt sind Englisch und Deutsch. Beim ersten Lauf lädt torchaudio ein Alignment-Modell (ca. 360 MB). -- `--lyrics` und `--ultrastar` schließen sich aus. Eine UltraStar-Datei an `--lyrics` übergeben ist ein Fehler. +- Der Text kommt entweder aus einer Datei (`--lyrics`) oder von [LRCLIB](https://lrclib.net) (`--lyrics-from lrclib`, braucht `--artist` und `--title`). Bei LRCLIB wird die Fassung gewählt, deren Länge zur Audiodatei passt (bis 5 s Abweichung), Live-, Akustik- und Remix-Fassungen nur, wenn es keine andere gibt. Die gewählte Fassung steht in `meta.json` unter `lyrics_source`. LRCLIB liefert nur den Text, die Zeiten bestimmt die Ausrichtung am Audio. Die Texte sind urheberrechtlich geschützt: nur lokal verwenden, nicht weitergeben. +- `--lyrics`, `--lyrics-from` und `--ultrastar` schließen sich aus. Eine UltraStar-Datei an `--lyrics` übergeben ist ein Fehler. - Laufen Modus 1 oder 3 in einem Ordner, der noch die Referenz aus Modus 2 enthält, wird die Tonhöhe neu berechnet, damit `vocals.json` nicht als KI-Ergebnis gilt. diff --git a/src/unmix/cli.py b/src/unmix/cli.py index 56edeba..6a37f83 100644 --- a/src/unmix/cli.py +++ b/src/unmix/cli.py @@ -57,6 +57,11 @@ def analyze( title: str | None = typer.Option(None, "--title", help="Song title metadata"), artist: str | None = typer.Option(None, "--artist", help="Song artist metadata"), reference: Path | None = typer.Option(None, "--reference", help="UltraStar ground-truth song.txt for evaluation"), + lyrics_from: str | None = typer.Option( + None, + "--lyrics-from", + help="Fetch the lyrics text instead of a file. Only 'lrclib' (needs --artist and --title). Local use only.", + ), ultrastar: Path | None = typer.Option( None, "--ultrastar", @@ -110,6 +115,17 @@ def analyze( if lyrics is not None and not lyrics.exists(): console.print(f"[red][ERROR][/red] Lyrics file not found: {lyrics}") raise typer.Exit(code=1) + lyrics_label: str | None = f"file: {lyrics.name}" if lyrics is not None else None + if lyrics_from is not None: + if lyrics_from.lower() != "lrclib": + console.print(f"[red][ERROR][/red] --lyrics-from kennt nur 'lrclib', nicht '{lyrics_from}'.") + raise typer.Exit(code=1) + if lyrics is not None or reference is not None: + console.print("[red][ERROR][/red] --lyrics-from schließt --lyrics und --ultrastar aus.") + raise typer.Exit(code=1) + if not title or not artist: + console.print("[red][ERROR][/red] --lyrics-from lrclib braucht --artist und --title.") + raise typer.Exit(code=1) if lyrics is not None: from unmix.pipeline.align import is_ultrastar_file @@ -120,6 +136,18 @@ def analyze( ) raise typer.Exit(code=1) + if lyrics_from is not None: + from unmix.pipeline.lrclib import LyricsLookupError, audio_duration_sec, fetch_lyrics_file + + try: + lyrics, lyrics_label = fetch_lyrics_file( + artist, title, audio_duration_sec(source_path), output_dir / ".cache" + ) + except LyricsLookupError as exc: + console.print(f"[red][ERROR][/red] {exc}") + raise typer.Exit(code=1) from exc + console.print(f"[cyan][INFO][/cyan] Lyrics: {lyrics_label}") + ctx = PipelineContext( source_file=source_path, output_dir=output_dir, @@ -143,6 +171,7 @@ def analyze( meta = runner.run(ctx) if reference is None: meta.vocals_source = mode_label(lyrics is not None) + meta.lyrics_source = lyrics_label ctx.save_meta(meta) # Persist title/artist overrides if provided diff --git a/src/unmix/pipeline/lrclib.py b/src/unmix/pipeline/lrclib.py new file mode 100644 index 0000000..62b386c --- /dev/null +++ b/src/unmix/pipeline/lrclib.py @@ -0,0 +1,85 @@ +"""Plain lyrics from LRCLIB (https://lrclib.net) for ``--lyrics-from lrclib``. + +Only the text is used. LRCLIB timestamps are line-level and belong to one release of a song, so they are not used +for alignment; the text is aligned to the audio as in ``--lyrics``. Several releases exist per song, so the one whose +length matches the audio is chosen. + +Local, personal use only: lyrics are copyrighted and must not be redistributed. +""" + +import json +import subprocess +import urllib.parse +import urllib.request +from pathlib import Path +from typing import Any + +API_SEARCH = "https://lrclib.net/api/search" +USER_AGENT = "unmix/0.1 (local analysis tool)" +MAX_DURATION_DIFF_SEC = 5.0 +ALTERNATE_VERSION_WORDS = ("live", "acoustic", "remix", "karaoke", "instrumental", "unplugged") +TIMEOUT_SEC = 20 + + +class LyricsLookupError(RuntimeError): + """Raised when LRCLIB cannot provide a usable text for the song.""" + + +def audio_duration_sec(path: Path) -> float: + out = subprocess.run( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)], + capture_output=True, + text=True, + check=False, + ) + try: + return float(out.stdout.strip()) + except ValueError as exc: + raise LyricsLookupError(f"Dauer von {path.name} nicht lesbar (ffprobe)") from exc + + +def pick_version(results: list[dict[str, Any]], duration_sec: float) -> dict[str, Any]: + """Choose the release whose length is closest to the audio, among entries with text.""" + candidates = [r for r in results if r.get("plainLyrics") and not r.get("instrumental")] + if not candidates: + raise LyricsLookupError("LRCLIB: kein Eintrag mit Text gefunden") + + # Prefer studio releases: live, acoustic, remix or karaoke versions only win if nothing else is left. + def rank(r: dict[str, Any]) -> tuple[bool, float]: + name = f"{r.get('albumName') or ''} {r.get('trackName') or ''}".lower() + return ( + any(word in name for word in ALTERNATE_VERSION_WORDS), + abs(float(r.get("duration") or 0) - duration_sec), + ) + + best = min(candidates, key=rank) + diff = abs(float(best.get("duration") or 0) - duration_sec) + if diff > MAX_DURATION_DIFF_SEC: + raise LyricsLookupError( + f"LRCLIB: keine Version mit passender Länge (nächste {best.get('duration')} s, Audio {duration_sec:.0f} s)" + ) + return best + + +def search(artist: str, title: str) -> list[dict[str, Any]]: + query = urllib.parse.urlencode({"track_name": title, "artist_name": artist}) + request = urllib.request.Request(f"{API_SEARCH}?{query}", headers={"User-Agent": USER_AGENT}) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT_SEC) as response: + data = json.load(response) + except (OSError, ValueError) as exc: + raise LyricsLookupError(f"LRCLIB nicht erreichbar: {exc}") from exc + if not isinstance(data, list): + raise LyricsLookupError("LRCLIB: unerwartete Antwort") + return data + + +def fetch_lyrics_file(artist: str, title: str, duration_sec: float, target_dir: Path) -> tuple[Path, str]: + """Write the chosen plain text to ``target_dir`` and return (path, human-readable source label).""" + chosen = pick_version(search(artist, title), duration_sec) + target_dir.mkdir(parents=True, exist_ok=True) + safe = "".join(c if c.isalnum() else "_" for c in f"{artist}_{title}") + path = target_dir / f"lrclib_{safe}.txt" + path.write_text(chosen["plainLyrics"].strip() + "\n", encoding="utf-8") + label = f"lrclib: {chosen.get('artistName')} - {chosen.get('trackName')} ({chosen.get('albumName')}, {chosen.get('duration')} s)" + return path, label diff --git a/src/unmix/schema/meta.py b/src/unmix/schema/meta.py index a079e99..c309a09 100644 --- a/src/unmix/schema/meta.py +++ b/src/unmix/schema/meta.py @@ -91,6 +91,7 @@ class MetaDocument(SongPackageBase): stages_failed: dict[str, str] = Field(default_factory=dict) reference_eval: dict[str, Any] | None = None vocals_source: Literal["whisper", "lyrics_aligned", "reference_ultrastar", "ai"] = "ai" + lyrics_source: str | None = None # where the aligned text came from, e.g. "file: x.txt" or "lrclib: ..." training_diff: dict[str, Any] | None = None diff --git a/tests/test_align.py b/tests/test_align.py index ec1919d..559551d 100644 --- a/tests/test_align.py +++ b/tests/test_align.py @@ -98,3 +98,33 @@ def test_is_ultrastar_file_detects_ultrastar_but_not_plain_text(tmp_path): 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")