Compare commits
4 Commits
bcae76279b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d783221fce | |||
| c761a244d8 | |||
| c4613d5616 | |||
| 5c8c2835fd |
125
README.md
125
README.md
@ -12,10 +12,36 @@ Um Songs für interaktive Musiktrainer (Gesang, Gitarre, Klavier) und Editoren n
|
|||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
Version `0.1.0`. Alle Kern-Meilensteine (M0 bis M6) und die [Songpack-Spezifikation v1.0](songpack-spec.md) sind vollständig implementiert und durch eine automatisierte Testsuite (58 Tests) abgedeckt.
|
Version `0.1.0`, Entwicklungsstand. Die Pipeline (Stufen 1 bis 7), das [Songpack-Format v1.0](songpack-spec.md), der UltraStar-Export und die Auswertung gegen Referenzen sind implementiert. Die Testsuite umfasst 87 Tests und läuft grün.
|
||||||
|
|
||||||
|
Die Qualität ist **nicht** die eines fertigen Karaoke-Produkts. Die Zahlen unten stammen aus Messungen an neun Songs mit handgetimten UltraStar-Referenzen und sind ein Ausgangspunkt, keine Garantie.
|
||||||
|
|
||||||
Getestet auf: Linux (CachyOS / Arch / Ubuntu, Kernel 6.13+, AMD Ryzen AI 9 / Strix Point, ROCm / CPU). Funktioniert dank standardisiertem PyTorch/Soundfile-Stack auf allen Plattformen mit Python 3.12 und `ffmpeg`.
|
Getestet auf: Linux (CachyOS / Arch / Ubuntu, Kernel 6.13+, AMD Ryzen AI 9 / Strix Point, ROCm / CPU). Funktioniert dank standardisiertem PyTorch/Soundfile-Stack auf allen Plattformen mit Python 3.12 und `ffmpeg`.
|
||||||
|
|
||||||
|
### Was funktioniert, was nicht
|
||||||
|
|
||||||
|
| Bereich | Stand |
|
||||||
|
| :--- | :--- |
|
||||||
|
| Stems, Tempo, Akkorde, Strumming | läuft, nicht gegen Referenzen gemessen |
|
||||||
|
| Text und Silben (Modus 1, Whisper) | Zeilen fehlen oft, lange Vokalisen (z. B. „ah ah ah") schlecht erkannt |
|
||||||
|
| Text und Silben (Modus 3, mit Text) | Zeilen vollständig, Zeitfehler meist unter 0,5 s |
|
||||||
|
| Tonhöhe (CREPE) | Noten grob richtig, aber Oktavlage der Referenzen weicht oft ab, strikte Treffer deshalb niedrig |
|
||||||
|
| UltraStar-Export | verlustbehaftet: Tonhöhe auf Halbtöne gerundet, Zeiten an BPM gebunden |
|
||||||
|
| Sprachen für Textausrichtung | Englisch und Deutsch |
|
||||||
|
|
||||||
|
### Messwerte (neun Songs, echte Pipeline)
|
||||||
|
|
||||||
|
| Messung | Modus 1 (Whisper) | Modus 3 (mit Text) |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| Zeilenstarts innerhalb 200 ms | 42 % | 71 % |
|
||||||
|
| Zeilenstarts innerhalb 500 ms | 53 % | 80 % |
|
||||||
|
| Zeilenenden innerhalb 300 ms | 28 % | 66 % |
|
||||||
|
| Gefundene Zeilen | teils deutlich weniger als in der Referenz | alle |
|
||||||
|
| Notenzeit-Abweichung (MAE) | ca. 95–225 ms | ca. 85–135 ms |
|
||||||
|
| Noten, oktav-korrigiert | 40–71 % | 43–75 % |
|
||||||
|
|
||||||
|
Die Referenzen sind handgetimte UltraStar-Dateien. Sie sind die Messlatte, aber selbst nicht fehlerfrei. Die Auswahl der Testsongs ist klein: die Regeln für Zeilenbildung und Zeilenenden wurden zum Teil an denselben Songs entwickelt, auf denen sie bewertet wurden.
|
||||||
|
|
||||||
## Before you use it
|
## Before you use it
|
||||||
|
|
||||||
**Rechenleistung & VRAM:** Die Ausführung im Qualitätsmodus `best` nutzt speicherintensive Modelle (`htdemucs_ft`, `whisper-large-v3`, `torchcrepe-full`). Auf Systemen mit weniger als 8 GB VRAM oder bei reiner CPU-Nutzung empfiehlt sich der Modus `--quality fast` (mit Modell-Chunking) oder das gezielte Ausführen einzelner Teilstufen über `--stage <name>`.
|
**Rechenleistung & VRAM:** Die Ausführung im Qualitätsmodus `best` nutzt speicherintensive Modelle (`htdemucs_ft`, `whisper-large-v3`, `torchcrepe-full`). Auf Systemen mit weniger als 8 GB VRAM oder bei reiner CPU-Nutzung empfiehlt sich der Modus `--quality fast` (mit Modell-Chunking) oder das gezielte Ausführen einzelner Teilstufen über `--stage <name>`.
|
||||||
@ -81,12 +107,13 @@ uv run ruff format --check
|
|||||||
| Feature | Description |
|
| Feature | Description |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| **Stem-Trennung (Demucs)** | Extrahiert 4 oder 6 Spuren (`vocals`, `drums`, `bass`, `other`, `guitar`, `piano`) und berechnet das Summen-Playback `instrumental.wav`. |
|
| **Stem-Trennung (Demucs)** | Extrahiert 4 oder 6 Spuren (`vocals`, `drums`, `bass`, `other`, `guitar`, `piano`) und berechnet das Summen-Playback `instrumental.wav`. |
|
||||||
| **Lyrics & Silben-Timing** | Whisper-Transkription mit VAD und Wort-Timestamps; Silbentrennung via `pyphen` mit proportionaler Zeitverteilung und Wortgrenzen. |
|
| **Lyrics & Silben-Timing** | Drei Eingabemodi: Whisper-Transkription (Modus 1), Ausrichtung eines vorhandenen Textes per CTC-Forced-Alignment (`--lyrics`, `--lyrics-from lrclib`) oder Übernahme einer UltraStar-Datei (`--ultrastar`). Silbentrennung via `pyphen` mit proportionaler Zeitverteilung. |
|
||||||
| **Tonhöhenerkennung (CREPE)** | Frame-genaue F0-Extraktion mit Hop-Size 10 ms, Medianberechnung pro Silbe, Voicing-Filterung und Oktavfehler-Korrektur. |
|
| **Tonhöhenerkennung (CREPE)** | Frame-genaue F0-Extraktion mit Hop-Size 10 ms, Medianberechnung pro Silbe, Voicing-Filterung und Oktavfehler-Korrektur. |
|
||||||
| **Tempo-Map & Beat-Grid** | Beat- und Downbeat-Tracking (`beat_this`), Erkennung von Taktarten (4/4, 3/4, 6/8) und Synthese von Metronom-Klickspuren. |
|
| **Tempo-Map & Beat-Grid** | Beat- und Downbeat-Tracking (`beat_this`), Erkennung von Taktarten (4/4, 3/4, 6/8) und Synthese von Metronom-Klickspuren. |
|
||||||
| **Akkorderkennung** | Harte-Notation (`C`, `Am`, `G7`, `Dsus4`), Quantisierung auf das Beat-Raster und Tonarterkennung (Krumhansl-Schmuckler). |
|
| **Akkorderkennung** | Harte-Notation (`C`, `Am`, `G7`, `Dsus4`), Quantisierung auf das Beat-Raster und Tonarterkennung (Krumhansl-Schmuckler). |
|
||||||
| **Instrumenten-Tracks (Strumming)** | Erkennung von Anschlägen (Onsets) auf der Gitarrenspur, Down/Up-Richtungsvorschlag und Muster-Kompression (`D . D U . U D U`). |
|
| **Instrumenten-Tracks (Strumming)** | Erkennung von Anschlägen (Onsets) auf der Gitarrenspur, Down/Up-Richtungsvorschlag und Muster-Kompression (`D . D U . U D U`). |
|
||||||
| **UltraStar Deluxe Export** | Erzeugt spielbereite `song.txt`-Dateien für Karaoke- und Übungssoftware (`export/song.txt`). |
|
| **UltraStar Deluxe Export** | Erzeugt `song.txt` für UltraStar-kompatible Software (`export/song.txt`). Verlustbehaftet, siehe Tabelle oben. |
|
||||||
|
| **Auswertung gegen Referenzen** | `unmix eval` misst Zeiten, Tonhöhe, Zeilen und Wortfehler gegen UltraStar-Dateien und erzeugt einen Bericht. |
|
||||||
| **Sicherer Songpack-Container** | Packt und entpackt `.songpack`-Container mit Whitelist-Filterung, Pfadtraversierungs- und Zip-Bomben-Schutz. |
|
| **Sicherer Songpack-Container** | Packt und entpackt `.songpack`-Container mit Whitelist-Filterung, Pfadtraversierungs- und Zip-Bomben-Schutz. |
|
||||||
|
|
||||||
## How it works
|
## How it works
|
||||||
@ -141,16 +168,34 @@ unmix analyze song.mp4 -o output_song/ --stems 6 --quality fast --lang en
|
|||||||
# Analyse direkt von YouTube/Web-URL (benötigt yt-dlp)
|
# Analyse direkt von YouTube/Web-URL (benötigt yt-dlp)
|
||||||
unmix analyze "https://www.youtube.com/watch?v=..." -o output_song/ --lang en
|
unmix analyze "https://www.youtube.com/watch?v=..." -o output_song/ --lang en
|
||||||
|
|
||||||
# Analyse mit Dual-Track Referenzmodus (erzeugt perfektes Songpack + Trainings-Differenzprotokoll)
|
# Modus 2: UltraStar-Datei (übernimmt Noten und Zeiten, vergleicht zusätzlich mit der KI-Vorhersage)
|
||||||
unmix analyze song.mp3 -o output_song/ --lang en --reference ground_truth_song.txt
|
unmix analyze song.mp3 -o output_song/ --lang en --ultrastar ground_truth_song.txt
|
||||||
|
|
||||||
|
# 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)
|
# Schneller Direkt-Import (übernimmt UltraStar-Gesang, rechnet nur Stems/Akkorde/Tempo)
|
||||||
unmix import-ultrastar ground_truth_song.txt song.mp3 -o output_song/
|
unmix import-ultrastar ground_truth_song.txt song.mp3 -o output_song/
|
||||||
```
|
```
|
||||||
|
|
||||||
> [!TIP]
|
### Die drei Eingabemodi
|
||||||
> **Dual-Track & Training-Feedback (`--reference`):**
|
|
||||||
> Wird `--reference <file.txt>` übergeben, nutzt `unmix` die verifizierten Referenznoten für das fertige Songpack (`vocals.json`) und vergleicht gleichzeitig die KI-Vorhersage Note für Note mit der Referenz. Die genaue Fehleranalyse wird in `training_diff.json` gespeichert (systematischer Timing- und Dauern-Drift, übersehene Noten, Melismen), um die Pipeline kontinuierlich datengetrieben zu verbessern.
|
Jede Analyse läuft in genau einem Modus. Der Modus steht danach in `meta.json` unter `vocals_source`.
|
||||||
|
|
||||||
|
| Modus | Aufruf | Quelle des Gesangs (`vocals.json`) | `vocals_source` |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1. Nur Audio/Video | `unmix analyze song.mp3 -o out --lang en` | Whisper (Text) + CREPE (Tonhöhe) | `whisper` |
|
||||||
|
| 2. UltraStar-Datei | `--ultrastar song.txt` | Noten und Zeiten der Datei, auf das Audio eingerastet | `reference_ultrastar` |
|
||||||
|
| 3. Nur Text | `--lyrics lyrics.txt` | Text per Forced Alignment am Gesang ausgerichtet, Tonhöhe weiterhin CREPE | `lyrics_aligned` |
|
||||||
|
|
||||||
|
- **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).
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
@ -186,6 +231,70 @@ unmix export-ultrastar output_song/
|
|||||||
unmix eval testset.toml
|
unmix eval testset.toml
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Im Testset steht pro Song `reference` (UltraStar-Datei) und optional `audio` (sonst wird das Audio über den `#VIDEO:`-Tag der Referenz per yt-dlp geholt). Mit `lyrics = "reference"` richtet der Benchmark den Text der Referenz am Audio aus (Modus 3), ohne deren Zeiten zu verwenden. So lässt sich Modus 3 gegen Modus 1 messen.
|
||||||
|
|
||||||
|
## Integration in andere Programme
|
||||||
|
|
||||||
|
Eine App (z. B. ein Übungsprogramm oder Editor) braucht nur den Songpack-Ordner oder das `.songpack`-Archiv. Die Pipeline muss nicht in der App laufen. Die verbindliche Beschreibung des Formats steht in der [Songpack-Spezifikation](songpack-spec.md).
|
||||||
|
|
||||||
|
### 1. Was die App liest
|
||||||
|
|
||||||
|
| Datei | Pflicht | Inhalt |
|
||||||
|
|---|---|---|
|
||||||
|
| `manifest.json` | ja | Version, Varianten, Dateiliste |
|
||||||
|
| `meta.json` | ja | Titel, Sprache, Quelle, `vocals_source` (welcher Modus) |
|
||||||
|
| `vocals.json` | ja, für Gesangstraining | Silben mit Start/Ende in Sekunden, Tonhöhe (MIDI) |
|
||||||
|
| `tempo.json` | sobald Akkorde oder Strumming vorhanden | Tempo-Map (Sekunde ↔ Beat) |
|
||||||
|
| `chords.json`, `tracks/*.json` | optional | Akkorde und Instrumenten-Tracks in Beats |
|
||||||
|
| `vocals_f0.json` | optional | Tonhöhenverlauf |
|
||||||
|
| `stems/` | bei Variante `full` | Audiospuren, fehlen bei `data` |
|
||||||
|
| `export/song.txt` | optional | UltraStar-Export, nur zur Anzeige, nicht als Quelle nutzen |
|
||||||
|
|
||||||
|
Die App sollte `manifest.json` zuerst lesen und nur die Dateien laden, die sie braucht. Zeiten in `vocals.json` und `tracks/` sind in Sekunden bzw. Beats, die Umrechnung läuft über `tempo.json`. Unbekannte Felder soll die App ignorieren, damit neue optionale Felder in Minor-Versionen nicht brechen.
|
||||||
|
|
||||||
|
`training_diff.json` und `.cache/` sind interne Dateien für Auswertung und Pipeline. Eine App soll sie nicht lesen.
|
||||||
|
|
||||||
|
### 2. Aufruf über die Kommandozeile
|
||||||
|
|
||||||
|
Ein fremdes Programm startet `unmix` als Prozess:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Ergebnis als JSON auf stdout (eine Zeile, am Ende der Ausgabe)
|
||||||
|
unmix analyze song.mp3 -o out/ --lang en --json
|
||||||
|
|
||||||
|
# Songpack packen (full = mit Stems, data = ohne Audio)
|
||||||
|
unmix pack out/ -o song.songpack
|
||||||
|
unmix pack out/ -o song_data.songpack --variant data
|
||||||
|
|
||||||
|
# Archiv sicher entpacken (prüft Pfade und Größen)
|
||||||
|
unmix unpack song.songpack -o unpacked/
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Exit-Code:** `0` bei Erfolg, `1` bei Fehlern (fehlende Datei, falscher Modus, Stufe fehlgeschlagen).
|
||||||
|
- **`--json`** gibt `output_dir`, `stages_done`, `stages_failed` und `reference_eval` aus. Bei fehlgeschlagenen Stufen bricht `analyze` mit Exit-Code `1` ab, ohne JSON.
|
||||||
|
- Die Laufzeit liegt bei Minuten pro Song, die Modelle brauchen GPU oder genug RAM (siehe *Before you use it*). Die App sollte den Aufruf im Hintergrund starten und den Fortschritt nicht erwarten.
|
||||||
|
|
||||||
|
### 3. Aufruf aus Python
|
||||||
|
|
||||||
|
```python
|
||||||
|
from pathlib import Path
|
||||||
|
from unmix.pipeline import PipelineContext, get_default_pipeline
|
||||||
|
from unmix.schema.vocals import VocalsDocument
|
||||||
|
|
||||||
|
ctx = PipelineContext(source_file=Path("song.mp3"), output_dir=Path("out"), lang="en")
|
||||||
|
meta = get_default_pipeline().run(ctx)
|
||||||
|
|
||||||
|
vocals = VocalsDocument.model_validate_json(Path("out/vocals.json").read_text(encoding="utf-8"))
|
||||||
|
```
|
||||||
|
|
||||||
|
Die Datenmodelle (`unmix.schema.*`) sind Pydantic-Modelle und validieren beim Laden. Die Funktionen unter `unmix.pipeline` und `unmix.export` sind die Schnittstellen, die außerhalb der CLI genutzt werden können. Interne Hilfsfunktionen (mit `_` beginnend) sind nicht Teil der Schnittstelle.
|
||||||
|
|
||||||
|
### 4. Versionen
|
||||||
|
|
||||||
|
- Das Format ist mit `manifest.json` versioniert (aktuell `1.0`). Minor-Erhöhungen fügen nur optionale Felder hinzu, Major-Erhöhungen können Felder ändern oder entfernen.
|
||||||
|
- Eine App prüft `schema_version` und lehnt Major-Versionen ab, die sie nicht kennt.
|
||||||
|
- Die Spezifikation hat offene Punkte (z. B. Stem-Format WAV oder FLAC, Tempo-Rampen), siehe Abschnitt 15 dort.
|
||||||
|
|
||||||
## References & Links
|
## References & Links
|
||||||
|
|
||||||
* **[Songpack-Spezifikation](songpack-spec.md)** – Vollständige Spezifikation des Songpack-Containers v1.0.
|
* **[Songpack-Spezifikation](songpack-spec.md)** – Vollständige Spezifikation des Songpack-Containers v1.0.
|
||||||
|
|||||||
@ -57,6 +57,11 @@ def analyze(
|
|||||||
title: str | None = typer.Option(None, "--title", help="Song title metadata"),
|
title: str | None = typer.Option(None, "--title", help="Song title metadata"),
|
||||||
artist: str | None = typer.Option(None, "--artist", help="Song artist 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"),
|
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(
|
ultrastar: Path | None = typer.Option(
|
||||||
None,
|
None,
|
||||||
"--ultrastar",
|
"--ultrastar",
|
||||||
@ -110,6 +115,17 @@ def analyze(
|
|||||||
if lyrics is not None and not lyrics.exists():
|
if lyrics is not None and not lyrics.exists():
|
||||||
console.print(f"[red][ERROR][/red] Lyrics file not found: {lyrics}")
|
console.print(f"[red][ERROR][/red] Lyrics file not found: {lyrics}")
|
||||||
raise typer.Exit(code=1)
|
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:
|
if lyrics is not None:
|
||||||
from unmix.pipeline.align import is_ultrastar_file
|
from unmix.pipeline.align import is_ultrastar_file
|
||||||
|
|
||||||
@ -120,6 +136,18 @@ def analyze(
|
|||||||
)
|
)
|
||||||
raise typer.Exit(code=1)
|
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(
|
ctx = PipelineContext(
|
||||||
source_file=source_path,
|
source_file=source_path,
|
||||||
output_dir=output_dir,
|
output_dir=output_dir,
|
||||||
@ -143,6 +171,7 @@ def analyze(
|
|||||||
meta = runner.run(ctx)
|
meta = runner.run(ctx)
|
||||||
if reference is None:
|
if reference is None:
|
||||||
meta.vocals_source = mode_label(lyrics is not None)
|
meta.vocals_source = mode_label(lyrics is not None)
|
||||||
|
meta.lyrics_source = lyrics_label
|
||||||
ctx.save_meta(meta)
|
ctx.save_meta(meta)
|
||||||
|
|
||||||
# Persist title/artist overrides if provided
|
# Persist title/artist overrides if provided
|
||||||
|
|||||||
85
src/unmix/pipeline/lrclib.py
Normal file
85
src/unmix/pipeline/lrclib.py
Normal file
@ -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
|
||||||
@ -91,6 +91,7 @@ class MetaDocument(SongPackageBase):
|
|||||||
stages_failed: dict[str, str] = Field(default_factory=dict)
|
stages_failed: dict[str, str] = Field(default_factory=dict)
|
||||||
reference_eval: dict[str, Any] | None = None
|
reference_eval: dict[str, Any] | None = None
|
||||||
vocals_source: Literal["whisper", "lyrics_aligned", "reference_ultrastar", "ai"] = "ai"
|
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
|
training_diff: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -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")
|
plain.write_text("We do it all\nEverything on our own\n", encoding="utf-8")
|
||||||
assert is_ultrastar_file(us)
|
assert is_ultrastar_file(us)
|
||||||
assert not is_ultrastar_file(plain)
|
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")
|
||||||
|
|||||||
Reference in New Issue
Block a user