Compare commits
13 Commits
d4745a48e0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d783221fce | |||
| c761a244d8 | |||
| c4613d5616 | |||
| 5c8c2835fd | |||
| bcae76279b | |||
| 861f6a29f2 | |||
| 904ce6253f | |||
| 3fdd639f47 | |||
| 4024b74953 | |||
| 769910286f | |||
| c73ad8d66b | |||
| dcde066772 | |||
| c93d2c696e |
6
.gitignore
vendored
6
.gitignore
vendored
@ -41,6 +41,12 @@ testdata/
|
||||
*.flac
|
||||
*.ogg
|
||||
|
||||
# Local evaluation data and reports
|
||||
testset*.local.toml
|
||||
eval_runs/
|
||||
eval_report.*
|
||||
.downloads/
|
||||
|
||||
# Allow synthetic demo audio
|
||||
!examples/demo_song/stems/*.wav
|
||||
pragmatic_readme_template*.md
|
||||
|
||||
127
README.md
127
README.md
@ -12,10 +12,36 @@ Um Songs für interaktive Musiktrainer (Gesang, Gitarre, Klavier) und Editoren n
|
||||
|
||||
## 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`.
|
||||
|
||||
### 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
|
||||
|
||||
**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 |
|
||||
| :--- | :--- |
|
||||
| **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. |
|
||||
| **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). |
|
||||
| **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. |
|
||||
|
||||
## How it works
|
||||
@ -141,10 +168,36 @@ unmix analyze song.mp4 -o output_song/ --stems 6 --quality fast --lang en
|
||||
# Analyse direkt von YouTube/Web-URL (benötigt yt-dlp)
|
||||
unmix analyze "https://www.youtube.com/watch?v=..." -o output_song/ --lang en
|
||||
|
||||
# Analyse mit direktem Vergleich gegen UltraStar-Referenzdatei
|
||||
unmix analyze song.mp3 -o output_song/ --lang en --reference ground_truth_song.txt
|
||||
# Modus 2: UltraStar-Datei (übernimmt Noten und Zeiten, vergleicht zusätzlich mit der KI-Vorhersage)
|
||||
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)
|
||||
unmix import-ultrastar ground_truth_song.txt song.mp3 -o output_song/
|
||||
```
|
||||
|
||||
### Die drei Eingabemodi
|
||||
|
||||
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]
|
||||
> **Rechtlicher Hinweis zu Online-Quellen:** Der Download von Audiodaten aus Online-Quellen (wie YouTube) über `yt-dlp` geschieht ausschließlich auf Veranlassung des Nutzers. Der Nutzer ist selbst dafür verantwortlich, dass die erforderlichen Rechte für die Verarbeitung und Analyse der Inhalte vorliegen.
|
||||
|
||||
@ -178,6 +231,70 @@ unmix export-ultrastar output_song/
|
||||
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
|
||||
|
||||
* **[Songpack-Spezifikation](songpack-spec.md)** – Vollständige Spezifikation des Songpack-Containers v1.0.
|
||||
|
||||
255
src/unmix/cli.py
255
src/unmix/cli.py
@ -57,6 +57,27 @@ 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",
|
||||
help="UltraStar song.txt: its notes and timings become the result (same as --reference)",
|
||||
),
|
||||
lyrics: Path | None = typer.Option(
|
||||
None,
|
||||
"--lyrics",
|
||||
help="Known lyrics (plain text, one sung line per line, or an UltraStar .txt): align them to the vocals "
|
||||
"instead of transcribing with Whisper (languages: en, de)",
|
||||
),
|
||||
keep_ai_vocals: bool = typer.Option(
|
||||
False,
|
||||
"--keep-ai-vocals",
|
||||
help="Keep AI-generated vocals.json instead of replacing with ground truth reference",
|
||||
),
|
||||
export_ultrastar_flag: bool = typer.Option(
|
||||
True, "--export-ultrastar/--no-export-ultrastar", help="Export UltraStar song.txt to export/"
|
||||
),
|
||||
@ -83,6 +104,50 @@ def analyze(
|
||||
console.print(f"[red][ERROR][/red] Input file not found: {source_path}")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
if ultrastar is not None:
|
||||
if reference is not None and reference.resolve() != ultrastar.resolve():
|
||||
console.print("[red][ERROR][/red] --ultrastar und --reference nur einzeln angeben.")
|
||||
raise typer.Exit(code=1)
|
||||
reference = ultrastar
|
||||
if lyrics is not None and reference is not None:
|
||||
console.print("[red][ERROR][/red] --lyrics und --ultrastar schließen sich aus: genau einen Modus wählen.")
|
||||
raise typer.Exit(code=1)
|
||||
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
|
||||
|
||||
if is_ultrastar_file(lyrics):
|
||||
console.print(
|
||||
"[red][ERROR][/red] Das ist eine UltraStar-Datei. Dafür --ultrastar nutzen "
|
||||
"(Noten und Zeiten werden übernommen). --lyrics ist für reinen Text gedacht."
|
||||
)
|
||||
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,
|
||||
@ -91,9 +156,23 @@ def analyze(
|
||||
quality=quality,
|
||||
force=force,
|
||||
target_stage=stage,
|
||||
lyrics_file=lyrics,
|
||||
)
|
||||
from unmix.pipeline.source_modes import (
|
||||
invalidate_pitch_cache,
|
||||
mode_label,
|
||||
previous_vocals_source,
|
||||
)
|
||||
|
||||
if reference is None and previous_vocals_source(ctx.meta_file) == "reference_ultrastar":
|
||||
# vocals.json still holds the ground truth of an earlier --ultrastar run: recompute pitch
|
||||
invalidate_pitch_cache(ctx.cache_dir)
|
||||
runner = get_default_pipeline()
|
||||
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
|
||||
updated_meta = False
|
||||
@ -121,46 +200,91 @@ def analyze(
|
||||
language=meta.language,
|
||||
)
|
||||
|
||||
# Evaluation against reference if requested
|
||||
# Evaluation against reference & Dual-Track ground-truth packaging
|
||||
if reference is not None:
|
||||
ref_path = reference.resolve()
|
||||
if not ref_path.exists():
|
||||
console.print(f"[yellow][WARN][/yellow] Reference file not found: {ref_path}")
|
||||
elif not vocals_json.exists():
|
||||
console.print("[yellow][WARN][/yellow] vocals.json was not generated; skipping reference evaluation.")
|
||||
else:
|
||||
from unmix.eval.metrics import evaluate_vocals
|
||||
from unmix.export.ultrastar import parse_ultrastar
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
from unmix.eval.metrics import generate_training_diff
|
||||
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar, ultrastar_to_vocals
|
||||
from unmix.pipeline.source_modes import invalidate_pitch_cache, prepare_ai_vocals
|
||||
|
||||
with open(vocals_json, encoding="utf-8") as vf:
|
||||
pred_vocals = VocalsDocument.model_validate(json.load(vf))
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
eval_metrics = evaluate_vocals(pred_vocals, ref_song)
|
||||
|
||||
# Store in meta.json
|
||||
meta.reference_eval = eval_metrics
|
||||
# 1. AI Vocals evaluation & Training Diff (Track B)
|
||||
training_diff = None
|
||||
ai_vocals = prepare_ai_vocals(output_dir, ctx.cache_dir, meta.vocals_source)
|
||||
if ai_vocals is not None:
|
||||
# Generate detailed note-by-note training difference
|
||||
training_diff = generate_training_diff(ai_vocals, ref_song)
|
||||
diff_path = output_dir / "training_diff.json"
|
||||
with open(diff_path, "w", encoding="utf-8") as tdf:
|
||||
json.dump(training_diff, tdf, indent=2)
|
||||
|
||||
meta.reference_eval = training_diff["summary"]
|
||||
meta.training_diff = training_diff["systematic_biases"]
|
||||
|
||||
# 2. Ground-Truth Packaging (Track A)
|
||||
if not keep_ai_vocals:
|
||||
vocals_wav = ctx.stems_dir / "vocals.wav"
|
||||
gt_vocals = ultrastar_to_vocals(ref_song, vocals_wav=vocals_wav)
|
||||
with open(vocals_json, "w", encoding="utf-8") as vf:
|
||||
vf.write(gt_vocals.model_dump_json(indent=2))
|
||||
invalidate_pitch_cache(ctx.cache_dir)
|
||||
meta.vocals_source = "reference_ultrastar"
|
||||
console.print(
|
||||
"[bold green][OK][/bold green] High-Quality Ground-Truth vocals.json generated from reference."
|
||||
)
|
||||
else:
|
||||
meta.vocals_source = "whisper"
|
||||
|
||||
ctx.save_meta(meta)
|
||||
|
||||
# Display evaluation table
|
||||
table = Table(title="UltraStar Referenz-Evaluierung")
|
||||
table.add_column("Metrik", style="cyan")
|
||||
table.add_column("Wert", style="bold green")
|
||||
# Re-export song.txt from authoritative vocals.json
|
||||
if export_ultrastar_flag and vocals_json.exists():
|
||||
export_ultrastar(
|
||||
output_dir,
|
||||
title=meta.title or ref_song.title,
|
||||
artist=meta.artist or ref_song.artist,
|
||||
language=meta.language,
|
||||
)
|
||||
|
||||
# Display rich summary tables
|
||||
if training_diff:
|
||||
eval_metrics = training_diff["summary"]
|
||||
biases = training_diff["systematic_biases"]
|
||||
|
||||
table = Table(title="UltraStar Dual-Track Evaluierung & Training")
|
||||
table.add_column("Metrik", style="cyan")
|
||||
table.add_column("Wert", style="bold green")
|
||||
|
||||
table.add_row("Referenz-Silben", str(eval_metrics["num_ref_syllables"]))
|
||||
table.add_row("KI-Vorhersage Silben", str(eval_metrics["num_pred_syllables"]))
|
||||
table.add_row(
|
||||
"Gematchte Noten", f"{biases['matched_notes_count']} / {eval_metrics['num_ref_syllables']}"
|
||||
)
|
||||
table.add_row("Ungematchte Ref-Noten (KI verpasst)", f"{biases['unmatched_ref_notes_count']}")
|
||||
table.add_row("Falsch-positive KI-Noten", f"{biases['unmatched_predictions_count']}")
|
||||
table.add_row("Timing MAE", f"{eval_metrics['mae_timing_ms']:.1f} ms")
|
||||
table.add_row("Timing Median", f"{eval_metrics['median_timing_ms']:.1f} ms")
|
||||
table.add_row("Systematischer Timing-Drift", f"{biases['mean_timing_bias_ms']:+.1f} ms")
|
||||
table.add_row("Timing <= 50 ms", f"{eval_metrics['fraction_within_50ms'] * 100:.1f} %")
|
||||
table.add_row("Timing <= 100 ms", f"{eval_metrics['fraction_within_100ms'] * 100:.1f} %")
|
||||
table.add_row("Timing <= 200 ms", f"{eval_metrics['fraction_within_200ms'] * 100:.1f} %")
|
||||
table.add_row("Notendauer MAE", f"{eval_metrics['duration_mae_ms']:.1f} ms")
|
||||
table.add_row("Systematischer Dauer-Drift", f"{biases['mean_duration_bias_ms']:+.1f} ms")
|
||||
table.add_row(
|
||||
"Noten exakt (oktav-korrigiert)", f"{eval_metrics['octave_equiv_pitch_accuracy'] * 100:.1f} %"
|
||||
)
|
||||
table.add_row("Tonklasse gleich (Chroma)", f"{eval_metrics['pitch_class_accuracy'] * 100:.1f} %")
|
||||
table.add_row("Median Oktavabweichung", f"{eval_metrics['median_octave_offset']:+.0f}")
|
||||
table.add_row("WER (Word Error Rate)", f"{eval_metrics['wer']:.2f}")
|
||||
console.print(table)
|
||||
console.print(
|
||||
f"[dim]Trainings-Differenzprotokoll gespeichert in: {output_dir / 'training_diff.json'}[/dim]"
|
||||
)
|
||||
|
||||
table.add_row("Referenz-Silben", str(eval_metrics["num_ref_syllables"]))
|
||||
table.add_row("Vorhergesagte Silben", str(eval_metrics["num_pred_syllables"]))
|
||||
table.add_row("Zeilen (Pred / Ref)", f"{eval_metrics['num_pred_lines']} / {eval_metrics['num_ref_lines']}")
|
||||
table.add_row("Timing MAE", f"{eval_metrics['mae_timing_ms']:.1f} ms")
|
||||
table.add_row("Timing Median", f"{eval_metrics['median_timing_ms']:.1f} ms")
|
||||
table.add_row("Timing <= 50 ms", f"{eval_metrics['fraction_within_50ms'] * 100:.1f} %")
|
||||
table.add_row("Timing <= 100 ms", f"{eval_metrics['fraction_within_100ms'] * 100:.1f} %")
|
||||
table.add_row("Timing <= 200 ms", f"{eval_metrics['fraction_within_200ms'] * 100:.1f} %")
|
||||
table.add_row("Notendauer MAE", f"{eval_metrics['duration_mae_ms']:.1f} ms")
|
||||
table.add_row("Tonhöhe (strikt)", f"{eval_metrics['strict_pitch_accuracy'] * 100:.1f} %")
|
||||
table.add_row("Tonklasse gleich", f"{eval_metrics['pitch_class_accuracy'] * 100:.1f} %")
|
||||
table.add_row("Median Oktavabweichung", f"{eval_metrics['median_octave_offset']:+.0f}")
|
||||
table.add_row("WER (Word Error Rate)", f"{eval_metrics['wer']:.2f}")
|
||||
console.print(table)
|
||||
|
||||
# Cleanup temporary download directory
|
||||
if temp_dir_obj is not None:
|
||||
@ -203,6 +327,79 @@ def export_ultrastar_cmd(
|
||||
print(str(res))
|
||||
|
||||
|
||||
@app.command(name="import-ultrastar")
|
||||
def import_ultrastar_cmd(
|
||||
ultrastar_file: Path = typer.Argument(..., help="Path to UltraStar song.txt file", exists=True),
|
||||
audio: str = typer.Argument(..., help="Audio file path or YouTube URL"),
|
||||
output_dir: Path = typer.Option(..., "-o", "--output", help="Output song package directory"),
|
||||
stems: int = typer.Option(4, "--stems", help="Number of stems to separate (4 or 6)"),
|
||||
quality: str = typer.Option("best", "--quality", help="Separation quality ('fast' or 'best')"),
|
||||
force: bool = typer.Option(False, "--force", help="Force recalculation"),
|
||||
) -> None:
|
||||
"""Import an UltraStar song.txt and audio file into a production-ready Song-Paket.
|
||||
|
||||
Extracts audio stems, chords, and tempo while using verified UltraStar vocals
|
||||
(bypassing Whisper and CREPE for ultra-fast packaging).
|
||||
"""
|
||||
from unmix.export.ultrastar import export_ultrastar, import_ultrastar, parse_ultrastar
|
||||
from unmix.pipeline import PipelineContext, get_default_pipeline
|
||||
from unmix.sources import download_url_audio, is_url
|
||||
|
||||
temp_dir_obj = None
|
||||
if is_url(audio):
|
||||
console.print(f"[cyan][INFO][/cyan] Downloading audio stream via yt-dlp: {audio}")
|
||||
temp_dir_obj = tempfile.TemporaryDirectory(prefix="unmix_yt_")
|
||||
temp_dir = Path(temp_dir_obj.name)
|
||||
source_path, _ = download_url_audio(audio, temp_dir)
|
||||
console.print(f"[green][OK][/green] Downloaded audio: {source_path.name}")
|
||||
else:
|
||||
source_path = Path(audio).resolve()
|
||||
if not source_path.exists():
|
||||
console.print(f"[red][ERROR][/red] Input audio file not found: {source_path}")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
ref_song = parse_ultrastar(ultrastar_file)
|
||||
lang = "en" if "english" in ref_song.headers.get("LANGUAGE", "").lower() else "de"
|
||||
|
||||
# Run stems, chords, tempo, strumming (target stage: strumming)
|
||||
ctx = PipelineContext(
|
||||
source_file=source_path,
|
||||
output_dir=output_dir,
|
||||
lang=lang,
|
||||
stems=stems,
|
||||
quality=quality,
|
||||
force=force,
|
||||
target_stage="strumming",
|
||||
)
|
||||
runner = get_default_pipeline()
|
||||
meta = runner.run(ctx)
|
||||
|
||||
# Import verified vocals directly from UltraStar
|
||||
vocals_wav = ctx.stems_dir / "vocals.wav"
|
||||
import_ultrastar(ultrastar_file, output_dir, vocals_wav=vocals_wav)
|
||||
meta.vocals_source = "reference_ultrastar"
|
||||
if ref_song.title and not meta.title:
|
||||
meta.title = ref_song.title
|
||||
if ref_song.artist and not meta.artist:
|
||||
meta.artist = ref_song.artist
|
||||
meta.language = lang
|
||||
ctx.save_meta(meta)
|
||||
|
||||
# Re-export clean song.txt
|
||||
export_ultrastar(output_dir, title=meta.title, artist=meta.artist, language=meta.language)
|
||||
|
||||
if temp_dir_obj is not None:
|
||||
try:
|
||||
temp_dir_obj.cleanup()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
console.print(
|
||||
f"[bold green][OK][/bold green] Successfully imported UltraStar Songpack to: {output_dir.resolve()}"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@app.command(name="eval")
|
||||
def eval_cmd(
|
||||
testset_config: Path = typer.Argument(..., help="Path to testset.toml", exists=True),
|
||||
|
||||
@ -165,6 +165,19 @@ def evaluate_vocals(
|
||||
else:
|
||||
median_octave_offset = 0.0
|
||||
|
||||
# Octave-aligned pitch accuracy (strict match after adjusting for song's median octave offset)
|
||||
if matched_pairs and median_octave_offset != 0.0:
|
||||
oct_aligned_correct = []
|
||||
for r, p in matched_pairs:
|
||||
ref_m = int(round(r.midi))
|
||||
pred_m = int(round(p.midi - median_octave_offset * 12.0)) if p.midi is not None else -999
|
||||
oct_aligned_correct.append(1.0 if pred_m == ref_m else 0.0)
|
||||
for _ in range(len(ref_notes) - len(matched_pairs)):
|
||||
oct_aligned_correct.append(0.0)
|
||||
octave_equiv_pitch_acc = float(np.mean(oct_aligned_correct))
|
||||
else:
|
||||
octave_equiv_pitch_acc = strict_pitch_acc
|
||||
|
||||
# 3. Line metrics
|
||||
ref_lines_valid = [r_line for r_line in reference.lines if any(n.text.strip() for n in r_line)]
|
||||
pred_lines_valid = [p_line for p_line in predicted.lines if any(s.text.strip() for s in p_line.syllables)]
|
||||
@ -217,9 +230,119 @@ def evaluate_vocals(
|
||||
"duration_mae_ms": duration_mae_ms,
|
||||
"strict_pitch_accuracy": strict_pitch_acc,
|
||||
"pitch_class_accuracy": pitch_class_acc,
|
||||
"octave_equiv_pitch_accuracy": pitch_class_acc,
|
||||
"octave_equiv_pitch_accuracy": octave_equiv_pitch_acc,
|
||||
"median_octave_offset": median_octave_offset,
|
||||
"line_start_mae_ms": line_start_mae_ms,
|
||||
"line_end_mae_ms": line_end_mae_ms,
|
||||
"wer": wer_score,
|
||||
}
|
||||
|
||||
|
||||
def generate_training_diff(
|
||||
predicted: VocalsDocument,
|
||||
reference: UltraStarSong,
|
||||
max_match_distance_sec: float = 2.0,
|
||||
) -> dict[str, Any]:
|
||||
"""Generate detailed note-by-note training difference and error breakdown."""
|
||||
summary = evaluate_vocals(predicted, reference, max_match_distance_sec)
|
||||
|
||||
ref_notes = [n for line in reference.lines for n in line if n.text.strip()]
|
||||
pred_sylls = [syl for line in predicted.lines for syl in line.syllables if syl.text.strip()]
|
||||
|
||||
matched_pairs: list[dict[str, Any]] = []
|
||||
matched_pred_indices: set[int] = set()
|
||||
unmatched_ref_notes: list[dict[str, Any]] = []
|
||||
|
||||
for ref in ref_notes:
|
||||
best_idx = None
|
||||
best_diff = float("inf")
|
||||
|
||||
for idx, pred in enumerate(pred_sylls):
|
||||
if idx in matched_pred_indices:
|
||||
continue
|
||||
diff = abs(pred.start - ref.start_sec)
|
||||
if diff < best_diff and diff <= max_match_distance_sec:
|
||||
best_diff = diff
|
||||
best_idx = idx
|
||||
|
||||
if best_idx is not None:
|
||||
matched_pred_indices.add(best_idx)
|
||||
pred = pred_sylls[best_idx]
|
||||
timing_err = (pred.start - ref.start_sec) * 1000.0
|
||||
dur_err = ((pred.end - pred.start) - (ref.end_sec - ref.start_sec)) * 1000.0
|
||||
p_midi = round(pred.midi, 2) if pred.midi is not None else None
|
||||
r_midi = round(ref.midi, 2)
|
||||
pitch_err = round(pred.midi - ref.midi, 2) if pred.midi is not None else None
|
||||
is_class = (int(round(pred.midi)) % 12) == (int(round(ref.midi)) % 12) if pred.midi is not None else False
|
||||
oct_off = int(round((pred.midi - ref.midi) / 12.0)) if pred.midi is not None else None
|
||||
|
||||
matched_pairs.append(
|
||||
{
|
||||
"ref_text": ref.text.strip(),
|
||||
"pred_text": pred.text.strip(),
|
||||
"ref_start": round(ref.start_sec, 3),
|
||||
"pred_start": round(pred.start, 3),
|
||||
"timing_error_ms": round(timing_err, 1),
|
||||
"ref_duration_ms": round((ref.end_sec - ref.start_sec) * 1000.0, 1),
|
||||
"pred_duration_ms": round((pred.end - pred.start) * 1000.0, 1),
|
||||
"duration_error_ms": round(dur_err, 1),
|
||||
"ref_midi": r_midi,
|
||||
"pred_midi": p_midi,
|
||||
"pitch_error_semitones": pitch_err,
|
||||
"pitch_class_match": is_class,
|
||||
"octave_offset": oct_off,
|
||||
}
|
||||
)
|
||||
else:
|
||||
unmatched_ref_notes.append(
|
||||
{
|
||||
"text": ref.text.strip(),
|
||||
"start": round(ref.start_sec, 3),
|
||||
"end": round(ref.end_sec, 3),
|
||||
"duration_ms": round((ref.end_sec - ref.start_sec) * 1000.0, 1),
|
||||
"midi": round(ref.midi, 2),
|
||||
}
|
||||
)
|
||||
|
||||
unmatched_predictions: list[dict[str, Any]] = [
|
||||
{
|
||||
"text": pred.text.strip(),
|
||||
"start": round(pred.start, 3),
|
||||
"end": round(pred.end, 3),
|
||||
"duration_ms": round((pred.end - pred.start) * 1000.0, 1),
|
||||
"midi": round(pred.midi, 2) if pred.midi is not None else None,
|
||||
}
|
||||
for idx, pred in enumerate(pred_sylls)
|
||||
if idx not in matched_pred_indices
|
||||
]
|
||||
|
||||
# Calculate systematic biases on matched notes
|
||||
if matched_pairs:
|
||||
signed_timing = [p["timing_error_ms"] for p in matched_pairs]
|
||||
signed_dur = [p["duration_error_ms"] for p in matched_pairs]
|
||||
mean_signed_timing_ms = float(np.mean(signed_timing))
|
||||
median_signed_timing_ms = float(np.median(signed_timing))
|
||||
mean_signed_dur_ms = float(np.mean(signed_dur))
|
||||
else:
|
||||
mean_signed_timing_ms = 0.0
|
||||
median_signed_timing_ms = 0.0
|
||||
mean_signed_dur_ms = 0.0
|
||||
|
||||
systematic_biases = {
|
||||
"mean_timing_bias_ms": round(mean_signed_timing_ms, 1),
|
||||
"median_timing_bias_ms": round(median_signed_timing_ms, 1),
|
||||
"mean_duration_bias_ms": round(mean_signed_dur_ms, 1),
|
||||
"median_octave_offset": summary["median_octave_offset"],
|
||||
"unmatched_ref_notes_count": len(unmatched_ref_notes),
|
||||
"unmatched_predictions_count": len(unmatched_predictions),
|
||||
"matched_notes_count": len(matched_pairs),
|
||||
}
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"systematic_biases": systematic_biases,
|
||||
"matched_notes": matched_pairs,
|
||||
"unmatched_reference_notes": unmatched_ref_notes,
|
||||
"unmatched_predictions": unmatched_predictions,
|
||||
}
|
||||
|
||||
|
||||
@ -26,9 +26,59 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
|
||||
for song_entry in songs:
|
||||
name = song_entry.get("name", "Unnamed")
|
||||
audio_path = Path(song_entry["audio"]).resolve()
|
||||
ref_path = Path(song_entry["reference"]).resolve()
|
||||
lang = song_entry.get("lang", "de")
|
||||
if not ref_path.exists():
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"status": "failed",
|
||||
"error": f"Reference file not found: {ref_path}",
|
||||
"elapsed_sec": 0.0,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
lang = song_entry.get("lang")
|
||||
if not lang:
|
||||
ref_lang = ref_song.headers.get("LANGUAGE", "").lower()
|
||||
if "english" in ref_lang or ref_lang == "en":
|
||||
lang = "en"
|
||||
elif "german" in ref_lang or ref_lang == "de":
|
||||
lang = "de"
|
||||
else:
|
||||
lang = "de"
|
||||
|
||||
audio_str = song_entry.get("audio")
|
||||
audio_path = Path(audio_str).resolve() if audio_str else None
|
||||
|
||||
if not audio_path or not audio_path.exists():
|
||||
from unmix.sources import download_url_audio, is_url
|
||||
|
||||
yt_url = ref_song.youtube_url or (audio_str if audio_str and is_url(audio_str) else None)
|
||||
if yt_url:
|
||||
dl_dir = report_dir / ".downloads"
|
||||
dl_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_name = "".join(c if c.isalnum() else "_" for c in name)
|
||||
downloaded_file = dl_dir / f"{safe_name}.wav"
|
||||
if not downloaded_file.exists():
|
||||
temp_wav, _ = download_url_audio(yt_url, dl_dir)
|
||||
temp_wav.rename(downloaded_file)
|
||||
audio_path = downloaded_file
|
||||
else:
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"status": "failed",
|
||||
"error": f"Audio file not found: {audio_str} and no #VIDEO tag in reference",
|
||||
"elapsed_sec": 0.0,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# lyrics = "reference": align the reference's text and line breaks (not its timings) instead of Whisper
|
||||
lyrics_entry = song_entry.get("lyrics")
|
||||
lyrics_file = ref_path if lyrics_entry == "reference" else (Path(lyrics_entry) if lyrics_entry else None)
|
||||
|
||||
song_out_dir = report_dir / "eval_runs" / name
|
||||
ctx = PipelineContext(
|
||||
@ -36,6 +86,7 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
output_dir=song_out_dir,
|
||||
lang=lang,
|
||||
target_stage="s4_pitch",
|
||||
lyrics_file=lyrics_file,
|
||||
)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
@ -58,7 +109,6 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
with open(vocals_json, encoding="utf-8") as vf:
|
||||
pred_vocals = VocalsDocument.model_validate(json.load(vf))
|
||||
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
metrics = evaluate_vocals(pred_vocals, ref_song)
|
||||
metrics["name"] = name
|
||||
metrics["status"] = "success"
|
||||
@ -73,8 +123,8 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
f"Konfiguration: `{testset_config.name}`",
|
||||
f"Getestete Songs: {len(results)}",
|
||||
"",
|
||||
"| Song | Status | Timing MAE (ms) | <= 50ms | <= 100ms | Noten (strikt) | Tonklasse | Oktav-Median | Dauer MAE | WER | Zeilen (P/R) | Laufzeit (s) |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
"| Song | Status | Timing MAE (ms) | <= 50ms | <= 100ms | Noten (strikt) | Noten (oktav-korr.) | Tonklasse | Oktav-Median | Dauer MAE | WER | Zeilen (P/R) | Laufzeit (s) |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
]
|
||||
|
||||
for r in results:
|
||||
@ -84,6 +134,7 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
f"{r.get('fraction_within_50ms', 0.0) * 100:.1f}% | "
|
||||
f"{r['fraction_within_100ms'] * 100:.1f}% | "
|
||||
f"{r['strict_pitch_accuracy'] * 100:.1f}% | "
|
||||
f"{r.get('octave_equiv_pitch_accuracy', r['strict_pitch_accuracy']) * 100:.1f}% | "
|
||||
f"{r.get('pitch_class_accuracy', 0.0) * 100:.1f}% | "
|
||||
f"{r.get('median_octave_offset', 0.0):+.0f} | "
|
||||
f"{r.get('duration_mae_ms', 0.0):.1f} ms | "
|
||||
@ -93,7 +144,7 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
)
|
||||
else:
|
||||
md_lines.append(
|
||||
f"| {r.get('name', 'Song')} | FEHLER ({r.get('error')}) | - | - | - | - | - | - | - | - | - | {r.get('elapsed_sec', 0.0):.1f}s |"
|
||||
f"| {r.get('name', 'Song')} | FEHLER ({r.get('error')}) | - | - | - | - | - | - | - | - | - | - | {r.get('elapsed_sec', 0.0):.1f}s |"
|
||||
)
|
||||
|
||||
report_md_path = report_dir / "eval_report.md"
|
||||
|
||||
@ -243,6 +243,18 @@ class UltraStarSong:
|
||||
def gap_ms(self) -> float:
|
||||
return float(self.headers.get("GAP", "0").replace(",", "."))
|
||||
|
||||
@property
|
||||
def youtube_url(self) -> str | None:
|
||||
video_tag = self.headers.get("VIDEO", "")
|
||||
if not video_tag:
|
||||
return None
|
||||
match = re.search(r"(?:a=|v=|/watch\?v=|youtu\.be/)([a-zA-Z0-9_-]{11})", video_tag)
|
||||
if match:
|
||||
return f"https://www.youtube.com/watch?v={match.group(1)}"
|
||||
if "youtube.com" in video_tag or "youtu.be" in video_tag:
|
||||
return video_tag.strip()
|
||||
return None
|
||||
|
||||
|
||||
def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
||||
"""Parse an UltraStar .txt file into structured notes and absolute times in seconds."""
|
||||
@ -283,9 +295,16 @@ def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
||||
continue
|
||||
|
||||
# Note line: : 10 4 2 text
|
||||
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line)
|
||||
# The lyric starts after exactly one separator space; further leading spaces mark a word start
|
||||
# (leading-space convention) and are normalised to a trailing space on the previous note below.
|
||||
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)(?: (.*))?$", line)
|
||||
if match:
|
||||
ntype, s_beat, dur, pitch, text = match.groups()
|
||||
text = text or ""
|
||||
if text.startswith(" "):
|
||||
text = text.lstrip(" ")
|
||||
if current_line and not current_line[-1].text.endswith(" "):
|
||||
current_line[-1].text += " "
|
||||
note = UltraStarNote(
|
||||
note_type=ntype,
|
||||
start_beat=int(s_beat),
|
||||
@ -312,3 +331,148 @@ def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
||||
note.midi = float(note.pitch + 60)
|
||||
|
||||
return UltraStarSong(headers=headers, lines=lines)
|
||||
|
||||
|
||||
def ultrastar_to_vocals(
|
||||
song: UltraStarSong,
|
||||
vocals_wav: Path | None = None,
|
||||
snap_tolerance_ms: float = 40.0,
|
||||
) -> VocalsDocument:
|
||||
"""Convert parsed UltraStarSong into a VocalsDocument.
|
||||
|
||||
If vocals_wav is provided and exists, fine-snaps note starts within snap_tolerance_ms
|
||||
to true acoustic transients to compensate for beat-quantization jitter.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
from unmix.schema.base import GeneratedBy
|
||||
from unmix.schema.vocals import VocalLine, VocalSyllable
|
||||
|
||||
octave_shift = 0.0
|
||||
acoustic_onsets = None
|
||||
if vocals_wav and Path(vocals_wav).exists():
|
||||
try:
|
||||
import librosa
|
||||
import soundfile as sf
|
||||
|
||||
audio_data, sr = sf.read(str(vocals_wav), dtype="float32")
|
||||
if audio_data.ndim > 1:
|
||||
audio_data = audio_data.mean(axis=-1)
|
||||
onset_env = librosa.onset.onset_strength(y=audio_data, sr=sr)
|
||||
acoustic_onsets = librosa.onset.onset_detect(onset_envelope=onset_env, sr=sr, units="time")
|
||||
|
||||
# Check for global octave transposition between audio and UltraStar notes
|
||||
mid_sec = len(audio_data) / (2.0 * sr)
|
||||
w_start = max(0, int((mid_sec - 20) * sr))
|
||||
w_end = min(len(audio_data), int((mid_sec + 25) * sr))
|
||||
sample = audio_data[w_start:w_end]
|
||||
if len(sample) > sr * 5:
|
||||
f0 = librosa.yin(sample, fmin=65, fmax=600, sr=sr)
|
||||
valid_f0 = f0[(f0 > 65) & (f0 < 600)]
|
||||
if len(valid_f0) > 100:
|
||||
med_audio_midi = float(69.0 + 12.0 * np.log2(np.median(valid_f0) / 440.0))
|
||||
all_ref_midis = [n.midi for song_line in song.lines for n in song_line if n.midi is not None]
|
||||
if all_ref_midis:
|
||||
med_ref_midi = float(np.median(all_ref_midis))
|
||||
diff_octaves = round((med_ref_midi - med_audio_midi) / 12.0)
|
||||
if abs(diff_octaves) >= 1:
|
||||
octave_shift = -diff_octaves * 12.0
|
||||
except Exception:
|
||||
acoustic_onsets = None
|
||||
octave_shift = 0.0
|
||||
|
||||
vocal_lines: list[VocalLine] = []
|
||||
syl_counter = 0
|
||||
|
||||
for line_idx, r_line in enumerate(song.lines):
|
||||
if not r_line:
|
||||
continue
|
||||
line_sylls: list[VocalSyllable] = []
|
||||
for note_idx, note in enumerate(r_line):
|
||||
syl_counter += 1
|
||||
raw_text = note.text
|
||||
has_space = raw_text.endswith(" ")
|
||||
clean_text = raw_text.rstrip()
|
||||
is_word_end = has_space or (note_idx == len(r_line) - 1)
|
||||
|
||||
s_start = note.start_sec
|
||||
s_end = note.end_sec
|
||||
|
||||
# Fine-snap to acoustic transients if available
|
||||
if acoustic_onsets is not None and len(acoustic_onsets) > 0:
|
||||
tol_sec = snap_tolerance_ms / 1000.0
|
||||
cands = acoustic_onsets[
|
||||
(acoustic_onsets >= s_start - tol_sec) & (acoustic_onsets <= s_start + tol_sec)
|
||||
]
|
||||
if len(cands) > 0:
|
||||
snapped = float(cands[np.argmin(np.abs(cands - s_start))])
|
||||
if snapped < s_end:
|
||||
s_start = snapped
|
||||
|
||||
# Map UltraStar note types
|
||||
stype = "normal"
|
||||
if note.note_type == "*":
|
||||
stype = "golden"
|
||||
elif note.note_type == "F":
|
||||
stype = "freestyle"
|
||||
elif note.note_type == "R":
|
||||
stype = "rap"
|
||||
|
||||
line_sylls.append(
|
||||
VocalSyllable(
|
||||
id=f"s_{syl_counter:04d}",
|
||||
text=clean_text,
|
||||
start=s_start,
|
||||
end=s_end,
|
||||
midi=float(note.midi + octave_shift),
|
||||
confidence=1.0,
|
||||
type=stype,
|
||||
word_end=is_word_end,
|
||||
golden=(stype == "golden"),
|
||||
)
|
||||
)
|
||||
|
||||
if line_sylls:
|
||||
vocal_lines.append(
|
||||
VocalLine(
|
||||
id=f"l_{line_idx + 1:04d}",
|
||||
voice=0,
|
||||
start=line_sylls[0].start,
|
||||
end=line_sylls[-1].end,
|
||||
syllables=line_sylls,
|
||||
)
|
||||
)
|
||||
|
||||
return VocalsDocument(
|
||||
schema_version="1.0",
|
||||
generated_by=GeneratedBy(
|
||||
stage="import_ultrastar",
|
||||
model="reference_ultrastar",
|
||||
model_version="1.0.0",
|
||||
params={
|
||||
"gap_ms": song.gap_ms,
|
||||
"bpm": song.bpm,
|
||||
"title": song.title,
|
||||
"artist": song.artist,
|
||||
},
|
||||
),
|
||||
lines=vocal_lines,
|
||||
)
|
||||
|
||||
|
||||
def import_ultrastar(
|
||||
txt_path: Path,
|
||||
output_dir: Path,
|
||||
vocals_wav: Path | None = None,
|
||||
snap_tolerance_ms: float = 40.0,
|
||||
) -> Path:
|
||||
"""Parse UltraStar file and save as vocals.json in output_dir."""
|
||||
output_dir = output_dir.resolve()
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
song = parse_ultrastar(txt_path)
|
||||
doc = ultrastar_to_vocals(song, vocals_wav=vocals_wav, snap_tolerance_ms=snap_tolerance_ms)
|
||||
out_file = output_dir / "vocals.json"
|
||||
with open(out_file, "w", encoding="utf-8") as f:
|
||||
f.write(doc.model_dump_json(indent=2))
|
||||
return out_file
|
||||
|
||||
|
||||
199
src/unmix/pipeline/align.py
Normal file
199
src/unmix/pipeline/align.py
Normal file
@ -0,0 +1,199 @@
|
||||
"""Text-guided word alignment: place given lyrics on the vocals stem with CTC forced alignment.
|
||||
|
||||
Used by stage 3 when ``--lyrics`` is given instead of transcribing with Whisper. The lyrics file is either
|
||||
plain text (one sung line per line) or an UltraStar ``.txt`` (its line structure and text are used, its timings
|
||||
are ignored).
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import soundfile as sf
|
||||
|
||||
# wav2vec2 CTC models with a character vocabulary, already used elsewhere via the torch hub cache.
|
||||
ALIGN_BUNDLES = {
|
||||
"en": "WAV2VEC2_ASR_BASE_960H",
|
||||
"de": "VOXPOPULI_ASR_BASE_10K_DE",
|
||||
}
|
||||
STRIDE = 320 # samples per wav2vec2 frame at 16 kHz
|
||||
SAMPLE_RATE = 16000
|
||||
FRAME_SEC = STRIDE / SAMPLE_RATE
|
||||
|
||||
_SECTION_MARKER = re.compile(r"^\s*[\[(].*[\])]\s*$")
|
||||
|
||||
|
||||
def supported_languages() -> list[str]:
|
||||
return sorted(ALIGN_BUNDLES)
|
||||
|
||||
|
||||
def read_lyrics_lines(path: Path) -> list[list[str]]:
|
||||
"""Read lyrics as a list of lines, each a list of display words (original case and punctuation)."""
|
||||
text = Path(path).read_text(encoding="utf-8", errors="replace")
|
||||
if is_ultrastar_file(Path(path)):
|
||||
return _lines_from_ultrastar(Path(path))
|
||||
lines: list[list[str]] = []
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if not line or _SECTION_MARKER.match(line):
|
||||
continue
|
||||
words = line.split()
|
||||
if words:
|
||||
lines.append(words)
|
||||
return lines
|
||||
|
||||
|
||||
def is_ultrastar_file(path: Path) -> bool:
|
||||
text = Path(path).read_text(encoding="utf-8", errors="replace")
|
||||
head = text.lstrip("")[:2000]
|
||||
return bool(re.search(r"^#(TITLE|ARTIST|BPM):", head, flags=re.MULTILINE)) and bool(
|
||||
re.search(r"^[:*FR] +-?\d+ +\d+ +-?\d+", text, flags=re.MULTILINE)
|
||||
)
|
||||
|
||||
|
||||
def _lines_from_ultrastar(path: Path) -> list[list[str]]:
|
||||
from unmix.export.ultrastar import parse_ultrastar
|
||||
|
||||
song = parse_ultrastar(path)
|
||||
lines: list[list[str]] = []
|
||||
for line in song.lines:
|
||||
words: list[str] = []
|
||||
cur = ""
|
||||
for note in line:
|
||||
cur += note.text.replace("~", "")
|
||||
if note.text.endswith(" ") and cur.strip():
|
||||
words.append(cur.strip())
|
||||
cur = ""
|
||||
if cur.strip():
|
||||
words.append(cur.strip())
|
||||
if words:
|
||||
lines.append(words)
|
||||
return lines
|
||||
|
||||
|
||||
def clean_word(word: str, labels: tuple[str, ...] | list[str], lang: str) -> str:
|
||||
"""Reduce a display word to the character set of the alignment model."""
|
||||
allowed = set(labels) - {"-", "|"}
|
||||
w = word.strip().replace("’", "'").replace("`", "'").replace("´", "'")
|
||||
w = w.upper() if any(c.isupper() for c in allowed) else w.lower()
|
||||
return "".join(c for c in w if c in allowed)
|
||||
|
||||
|
||||
def compute_emissions(wav_path: Path, model: Any, bundle: Any, window_sec: float = 30.0, ctx_sec: float = 2.0) -> Any:
|
||||
"""Frame-wise log-probabilities for the whole file, computed in overlapping windows."""
|
||||
import torch
|
||||
import torchaudio
|
||||
|
||||
data, sr = sf.read(str(wav_path), dtype="float32")
|
||||
if data.ndim > 1:
|
||||
data = data.mean(axis=-1)
|
||||
wav = torch.from_numpy(data)
|
||||
if sr != bundle.sample_rate:
|
||||
wav = torchaudio.functional.resample(wav, sr, bundle.sample_rate)
|
||||
n = wav.shape[0]
|
||||
win = int(window_sec * SAMPLE_RATE) // STRIDE * STRIDE
|
||||
ctx = int(ctx_sec * SAMPLE_RATE) // STRIDE * STRIDE
|
||||
out = torch.zeros(n // STRIDE + 1, len(bundle.get_labels()))
|
||||
normalize = bool(getattr(bundle, "_normalize_waveform", False))
|
||||
with torch.inference_mode():
|
||||
for s0 in range(0, n, win):
|
||||
a = max(0, s0 - ctx) # always a multiple of STRIDE, so frame indices stay absolute
|
||||
b = min(n, s0 + win + ctx)
|
||||
chunk = wav[a:b]
|
||||
if normalize:
|
||||
chunk = torch.nn.functional.layer_norm(chunk, chunk.shape)
|
||||
logits, _ = model(chunk.unsqueeze(0))
|
||||
logp = torch.log_softmax(logits, dim=-1)[0]
|
||||
f0 = a // STRIDE
|
||||
lo = s0 // STRIDE - f0
|
||||
hi = min(logp.shape[0], min(n, s0 + win) // STRIDE - f0)
|
||||
out[f0 + lo : f0 + hi] = logp[lo:hi]
|
||||
return out
|
||||
|
||||
|
||||
def align_words(
|
||||
emissions: Any, clean_lines: list[list[str]], labels: tuple[str, ...] | list[str]
|
||||
) -> dict[tuple[int, int], tuple[float, float]]:
|
||||
"""CTC forced alignment. Returns {(line_idx, word_idx): (start_sec, end_sec)} for every non-empty word."""
|
||||
import torch
|
||||
import torchaudio.functional as F
|
||||
|
||||
idx = {c: i for i, c in enumerate(labels)}
|
||||
tokens: list[int] = []
|
||||
owner: list[tuple[int, int]] = []
|
||||
for li, words in enumerate(clean_lines):
|
||||
for wi, w in enumerate(words):
|
||||
for c in w:
|
||||
tokens.append(idx[c])
|
||||
owner.append((li, wi))
|
||||
if not tokens:
|
||||
return {}
|
||||
if emissions.shape[0] < len(tokens):
|
||||
raise ValueError(
|
||||
f"Lyrics too long for the audio: {len(tokens)} characters but only {emissions.shape[0]} audio frames."
|
||||
)
|
||||
targets = torch.tensor([tokens], dtype=torch.int32)
|
||||
aligned, scores = F.forced_align(emissions.unsqueeze(0), targets, blank=0)
|
||||
spans = F.merge_tokens(aligned[0], scores[0].exp())
|
||||
if len(spans) != len(tokens):
|
||||
raise ValueError("Forced alignment returned an unexpected number of token spans.")
|
||||
result: dict[tuple[int, int], tuple[float, float]] = {}
|
||||
for span, key in zip(spans, owner, strict=True):
|
||||
s, e = span.start * FRAME_SEC, span.end * FRAME_SEC
|
||||
cur = result.get(key)
|
||||
result[key] = (s, e) if cur is None else (min(cur[0], s), max(cur[1], e))
|
||||
return result
|
||||
|
||||
|
||||
def load_aligner(lang: str) -> tuple[Any, Any]:
|
||||
"""Return (bundle, model) for a language or raise ValueError for unsupported languages."""
|
||||
import torchaudio
|
||||
|
||||
key = (lang or "").lower()[:2]
|
||||
if key not in ALIGN_BUNDLES:
|
||||
raise ValueError(
|
||||
f"--lyrics alignment supports languages {supported_languages()}, got '{lang}'. "
|
||||
"Run without --lyrics to transcribe with Whisper."
|
||||
)
|
||||
bundle = getattr(torchaudio.pipelines, ALIGN_BUNDLES[key])
|
||||
return bundle, bundle.get_model().eval()
|
||||
|
||||
|
||||
def lyrics_to_timed_lines(
|
||||
lyrics: list[list[str]],
|
||||
vocals_wav: Path,
|
||||
lang: str,
|
||||
syllabify: Any,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Align ``lyrics`` to the vocals stem and return stage-3 style lines.
|
||||
|
||||
``syllabify(word_text, start, end)`` splits a timed word into syllable dicts.
|
||||
"""
|
||||
bundle, model = load_aligner(lang)
|
||||
labels = bundle.get_labels()
|
||||
key = lang.lower()[:2]
|
||||
clean = [[clean_word(w, labels, key) for w in line] for line in lyrics]
|
||||
emissions = compute_emissions(vocals_wav, model, bundle)
|
||||
timing = align_words(emissions, clean, labels)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
for li, words in enumerate(lyrics):
|
||||
# Words without alignable characters (e.g. "-", digits) get no time and are skipped.
|
||||
timed = [(wi, w) for wi, w in enumerate(words) if (li, wi) in timing]
|
||||
if not timed:
|
||||
continue
|
||||
syllables: list[dict[str, Any]] = []
|
||||
for pos, (wi, w) in enumerate(timed):
|
||||
start, end = timing[(li, wi)]
|
||||
text = w + (" " if pos < len(timed) - 1 else "")
|
||||
syllables.extend(syllabify(text, start, max(end, start + 0.02)))
|
||||
if syllables:
|
||||
lines.append(
|
||||
{
|
||||
"start": syllables[0]["start"],
|
||||
"end": syllables[-1]["end"],
|
||||
"text": " ".join(w for _, w in timed),
|
||||
"syllables": syllables,
|
||||
}
|
||||
)
|
||||
return lines
|
||||
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
|
||||
@ -35,8 +35,10 @@ class PipelineContext:
|
||||
quality: str = "best",
|
||||
force: bool = False,
|
||||
target_stage: str | None = None,
|
||||
lyrics_file: Path | None = None,
|
||||
):
|
||||
self.source_file = source_file.resolve()
|
||||
self.lyrics_file = lyrics_file.resolve() if lyrics_file else None
|
||||
self.output_dir = output_dir.resolve()
|
||||
self.lang = lang
|
||||
self.stems = stems
|
||||
|
||||
@ -77,6 +77,11 @@ class ExtractStage(Stage):
|
||||
output_wav = self.get_outputs(ctx)[0]
|
||||
output_wav.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if ctx.source_file.resolve() == output_wav.resolve():
|
||||
# Source file is already the cached extracted.wav
|
||||
return
|
||||
|
||||
|
||||
# ffmpeg extraction command:
|
||||
# -y : overwrite output
|
||||
# -i <source>
|
||||
|
||||
@ -48,6 +48,101 @@ def hyphenate_word(word_text: str, dic: pyphen.Pyphen) -> list[str]:
|
||||
return res
|
||||
|
||||
|
||||
def split_into_vocal_lines(
|
||||
syllables: list[dict[str, Any]],
|
||||
gap_sec: float = 0.6,
|
||||
max_line_sec: float = 6.0,
|
||||
min_split_gap_sec: float = 0.1,
|
||||
) -> list[list[dict[str, Any]]]:
|
||||
"""Split a Whisper segment into singable lines.
|
||||
|
||||
Whisper segments follow sentence/breath logic and often span several sung lines. Lines are
|
||||
first cut at pauses between words longer than ``gap_sec``. Chunks that are still longer than
|
||||
``max_line_sec`` are cut recursively at their largest internal word gap (at the word
|
||||
boundary closest to the middle if no gap reaches ``min_split_gap_sec``).
|
||||
"""
|
||||
if not syllables:
|
||||
return []
|
||||
|
||||
chunks: list[list[dict[str, Any]]] = [[syllables[0]]]
|
||||
for prev, cur in zip(syllables, syllables[1:], strict=False):
|
||||
if prev.get("word_end", True) and cur["start"] - prev["end"] > gap_sec:
|
||||
chunks.append([])
|
||||
chunks[-1].append(cur)
|
||||
|
||||
def split_long(chunk: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
|
||||
if chunk[-1]["end"] - chunk[0]["start"] <= max_line_sec:
|
||||
return [chunk]
|
||||
candidates = [i for i in range(1, len(chunk)) if chunk[i - 1].get("word_end", True)]
|
||||
if not candidates:
|
||||
return [chunk]
|
||||
best = max(candidates, key=lambda i: chunk[i]["start"] - chunk[i - 1]["end"])
|
||||
if chunk[best]["start"] - chunk[best - 1]["end"] < min_split_gap_sec:
|
||||
mid = (chunk[0]["start"] + chunk[-1]["end"]) / 2.0
|
||||
best = min(candidates, key=lambda i: abs(chunk[i]["start"] - mid))
|
||||
return split_long(chunk[:best]) + split_long(chunk[best:])
|
||||
|
||||
result: list[list[dict[str, Any]]] = []
|
||||
for c in chunks:
|
||||
result.extend(split_long(c))
|
||||
return result
|
||||
|
||||
|
||||
def pop_trailing_orphan(
|
||||
chunks: list[list[dict[str, Any]]],
|
||||
max_orphan_sec: float = 1.0,
|
||||
) -> tuple[list[list[dict[str, Any]]], list[dict[str, Any]] | None]:
|
||||
"""Detach a mistimed single trailing word from a segment's lines.
|
||||
|
||||
Whisper sometimes assigns the first word of the *next* line to the end of a segment and gives
|
||||
it a start time inside (or just after) the preceding line, or emits it as a segment of its own.
|
||||
If the last chunk of a segment is a single short word, it is returned separately so it can be
|
||||
attached to the following segment.
|
||||
"""
|
||||
if not chunks:
|
||||
return chunks, None
|
||||
last = chunks[-1]
|
||||
is_single_word = sum(1 for s in last if s.get("word_end", True)) == 1
|
||||
if is_single_word and last[-1]["end"] - last[0]["start"] <= max_orphan_sec:
|
||||
return chunks[:-1], last
|
||||
return chunks, None
|
||||
|
||||
|
||||
def merge_leading_orphan(
|
||||
chunks: list[list[dict[str, Any]]],
|
||||
max_orphan_sec: float = 1.0,
|
||||
) -> list[list[dict[str, Any]]]:
|
||||
"""Merge a mistimed single leading word of a segment into the line that follows it."""
|
||||
if len(chunks) < 2:
|
||||
return chunks
|
||||
first = chunks[0]
|
||||
if sum(1 for s in first if s.get("word_end", True)) == 1 and first[-1]["end"] - first[0]["start"] <= max_orphan_sec:
|
||||
return prepend_orphan(first, chunks[1:])
|
||||
return chunks
|
||||
|
||||
|
||||
def prepend_orphan(
|
||||
orphan: list[dict[str, Any]],
|
||||
chunks: list[list[dict[str, Any]]],
|
||||
max_orphan_sec: float = 0.5,
|
||||
) -> list[list[dict[str, Any]]]:
|
||||
"""Merge ``orphan`` into the first chunk, re-timed into the start of that chunk's first syllable.
|
||||
|
||||
The line keeps its start time (Whisper's first word of the following line is usually close to
|
||||
the true line start); the orphan only takes the leading part of the first syllable.
|
||||
"""
|
||||
first = chunks[0][0]
|
||||
span = first["end"] - first["start"]
|
||||
total = min(max_orphan_sec, 0.2 * len(orphan), 0.5 * span)
|
||||
step = total / len(orphan)
|
||||
t0 = first["start"]
|
||||
for i, syl in enumerate(orphan):
|
||||
syl["start"] = round(t0 + i * step, 3)
|
||||
syl["end"] = round(t0 + (i + 1) * step, 3)
|
||||
first["start"] = round(t0 + total, 3)
|
||||
return [orphan + chunks[0], *chunks[1:]]
|
||||
|
||||
|
||||
def split_word_into_syllables_timed(
|
||||
word_text: str, start: float, end: float, dic: pyphen.Pyphen
|
||||
) -> list[dict[str, Any]]:
|
||||
@ -84,11 +179,78 @@ def split_word_into_syllables_timed(
|
||||
return timed
|
||||
|
||||
|
||||
def segments_to_lines(
|
||||
segments: list[dict[str, Any]],
|
||||
dic: pyphen.Pyphen,
|
||||
split_lines: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Turn raw Whisper segments (with word timestamps) into timed, syllabified lines.
|
||||
|
||||
With ``split_lines=False`` every Whisper segment becomes one line (legacy behaviour).
|
||||
"""
|
||||
lines: list[dict[str, Any]] = []
|
||||
prev_seg: tuple[str, float] | None = None
|
||||
pending_orphan: list[dict[str, Any]] | None = None
|
||||
|
||||
for seg in segments:
|
||||
seg_syllables: list[dict[str, Any]] = []
|
||||
words = seg.get("words") or []
|
||||
if words:
|
||||
for idx, w in enumerate(words):
|
||||
# Attach space to word text if not the last word in segment
|
||||
w_text = w["word"].strip()
|
||||
if idx < len(words) - 1:
|
||||
w_text += " "
|
||||
seg_syllables.extend(split_word_into_syllables_timed(w_text, w["start"], w["end"], dic))
|
||||
else:
|
||||
# Segment without word timestamps fallback
|
||||
seg_syllables.extend(split_word_into_syllables_timed(seg["text"].strip(), seg["start"], seg["end"], dic))
|
||||
|
||||
if not seg_syllables:
|
||||
continue
|
||||
|
||||
clean_text = seg["text"].strip()
|
||||
seg_dur = max(0.01, seg["end"] - seg["start"])
|
||||
|
||||
# Skip Whisper hallucinated repetition at segment boundaries / audio fadeout
|
||||
if prev_seg is not None and prev_seg[0] == clean_text.lower():
|
||||
prev_dur = max(0.01, prev_seg[1])
|
||||
# If this duplicate is unnaturally rushed or short (<2s or < 50% prev duration)
|
||||
if seg_dur < 2.0 or (seg_dur < prev_dur * 0.5):
|
||||
continue
|
||||
prev_seg = (clean_text.lower(), seg_dur)
|
||||
|
||||
if not split_lines:
|
||||
lines.append({"start": seg["start"], "end": seg["end"], "text": clean_text, "syllables": seg_syllables})
|
||||
continue
|
||||
|
||||
seg_chunks = merge_leading_orphan(split_into_vocal_lines(seg_syllables))
|
||||
if pending_orphan is not None:
|
||||
seg_chunks = prepend_orphan(pending_orphan, seg_chunks)
|
||||
pending_orphan = None
|
||||
seg_chunks, pending_orphan = pop_trailing_orphan(seg_chunks)
|
||||
for chunk in seg_chunks:
|
||||
lines.append(_chunk_to_line(chunk))
|
||||
|
||||
if pending_orphan is not None:
|
||||
lines.append(_chunk_to_line(pending_orphan))
|
||||
return lines
|
||||
|
||||
|
||||
def _chunk_to_line(chunk: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
return {
|
||||
"start": chunk[0]["start"],
|
||||
"end": chunk[-1]["end"],
|
||||
"text": "".join(x["text"] for x in chunk).strip(),
|
||||
"syllables": chunk,
|
||||
}
|
||||
|
||||
|
||||
class LyricsStage(Stage):
|
||||
"""Stage 3 transcribes vocals into word-aligned syllables using Whisper and pyphen."""
|
||||
|
||||
name = "s3_lyrics"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
model_name = "whisper-large-v3"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s2_stems"]
|
||||
@ -97,7 +259,10 @@ class LyricsStage(Stage):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.stems_dir / "vocals.wav"]
|
||||
inputs = [ctx.stems_dir / "vocals.wav"]
|
||||
if ctx.lyrics_file is not None:
|
||||
inputs.append(ctx.lyrics_file) # content hash invalidates the cache when the lyrics change
|
||||
return inputs
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.cache_dir / "lyrics_raw.json"]
|
||||
@ -106,8 +271,30 @@ class LyricsStage(Stage):
|
||||
return {
|
||||
"lang": ctx.lang or "de",
|
||||
"model_size": "base" if ctx.quality == "fast" else "large-v3",
|
||||
"mode": "aligned" if ctx.lyrics_file is not None else "whisper",
|
||||
}
|
||||
|
||||
def _run_aligned(self, ctx: PipelineContext, vocals_wav: Path, lang: str, dic: pyphen.Pyphen) -> None:
|
||||
"""Place the given lyrics on the vocals stem (CTC forced alignment) instead of transcribing."""
|
||||
from unmix.pipeline.align import lyrics_to_timed_lines, read_lyrics_lines
|
||||
|
||||
assert ctx.lyrics_file is not None
|
||||
lyrics = read_lyrics_lines(ctx.lyrics_file)
|
||||
if not lyrics:
|
||||
raise ValueError(f"No lyrics found in {ctx.lyrics_file}")
|
||||
self.model_name = "wav2vec2-ctc-forced-alignment"
|
||||
lines = lyrics_to_timed_lines(
|
||||
lyrics,
|
||||
vocals_wav,
|
||||
lang,
|
||||
lambda text, start, end: split_word_into_syllables_timed(text, start, end, dic),
|
||||
)
|
||||
output_data = {"language": lang, "detected_language": 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)
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
@ -127,6 +314,10 @@ class LyricsStage(Stage):
|
||||
except Exception:
|
||||
dic = pyphen.Pyphen(lang="en_US")
|
||||
|
||||
if ctx.lyrics_file is not None:
|
||||
self._run_aligned(ctx, vocals_wav, lang, dic)
|
||||
return
|
||||
|
||||
# Determine compute device
|
||||
device_str = config.get_device(self.name)
|
||||
compute_type = "float16" if device_str.startswith("cuda") else "int8"
|
||||
@ -140,40 +331,34 @@ class LyricsStage(Stage):
|
||||
download_root=str(models_dir),
|
||||
)
|
||||
|
||||
vad_params = {
|
||||
"min_silence_duration_ms": 400,
|
||||
"speech_pad_ms": 150,
|
||||
}
|
||||
|
||||
segments, info = model.transcribe(
|
||||
str(vocals_wav),
|
||||
language=lang,
|
||||
word_timestamps=True,
|
||||
vad_filter=True,
|
||||
vad_parameters=vad_params,
|
||||
)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
raw_segments = [
|
||||
{
|
||||
"start": seg.start,
|
||||
"end": seg.end,
|
||||
"text": seg.text,
|
||||
"words": [{"word": w.word, "start": w.start, "end": w.end} for w in (seg.words or [])],
|
||||
}
|
||||
for seg in segments
|
||||
]
|
||||
segments_file = ctx.cache_dir / "whisper_segments.json"
|
||||
segments_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(segments_file, "w", encoding="utf-8") as f:
|
||||
json.dump(raw_segments, f, indent=2, ensure_ascii=False)
|
||||
|
||||
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,
|
||||
}
|
||||
)
|
||||
lines = segments_to_lines(raw_segments, dic, split_lines=True)
|
||||
|
||||
output_data = {
|
||||
"language": lang,
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable."""
|
||||
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable with acoustic onset snapping."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import librosa
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
@ -13,6 +14,53 @@ from unmix.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.schema.base import GeneratedBy
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
# Line ends: follow strictly voiced frames (CREPE periodicity) after the last word.
|
||||
# Short dropouts are always bridged; longer ones (up to the max) only if voicing resumes for a while,
|
||||
# i.e. a held note with a dropout rather than a breath or consonant.
|
||||
LINE_END_VOICING_THRESHOLD = 0.7
|
||||
LINE_END_MAX_GAP_SEC = 0.1
|
||||
LINE_END_RESUME_MAX_GAP_SEC = 0.3
|
||||
LINE_END_RESUME_MIN_RUN_SEC = 0.3
|
||||
|
||||
|
||||
def voiced_run_end(
|
||||
is_voiced: np.ndarray,
|
||||
t0: float,
|
||||
hop_sec: float,
|
||||
max_gap_sec: float,
|
||||
cap_t: float,
|
||||
resume_max_gap_sec: float = 0.0,
|
||||
resume_min_run_sec: float = 0.0,
|
||||
) -> float:
|
||||
"""End time of the voiced run starting at ``t0``.
|
||||
|
||||
Unvoiced gaps up to ``max_gap_sec`` are always bridged. Gaps up to ``resume_max_gap_sec`` are
|
||||
bridged if the voiced run that follows lasts at least ``resume_min_run_sec``.
|
||||
"""
|
||||
n = len(is_voiced)
|
||||
k = int(t0 / hop_sec) if hop_sec > 0 else 0
|
||||
last = k
|
||||
while k < n and k * hop_sec < cap_t:
|
||||
if is_voiced[k]:
|
||||
last = k
|
||||
k += 1
|
||||
continue
|
||||
j = k
|
||||
while j < n and not is_voiced[j]:
|
||||
j += 1
|
||||
if j >= n or j * hop_sec >= cap_t:
|
||||
break
|
||||
gap = (j - k) * hop_sec
|
||||
r = j
|
||||
while r < n and is_voiced[r]:
|
||||
r += 1
|
||||
run = (r - j) * hop_sec
|
||||
if gap <= max_gap_sec or (gap <= resume_max_gap_sec and run >= resume_min_run_sec):
|
||||
k = j
|
||||
else:
|
||||
break
|
||||
return (last + 1) * hop_sec
|
||||
|
||||
|
||||
def hz_to_midi(hz: np.ndarray) -> np.ndarray:
|
||||
"""Convert frequency in Hz to fractional MIDI note numbers."""
|
||||
@ -57,11 +105,108 @@ def correct_octave_errors(syllables: list[dict[str, Any]]) -> list[dict[str, Any
|
||||
return syllables
|
||||
|
||||
|
||||
def snap_onset(
|
||||
target_t: float,
|
||||
w_min: float,
|
||||
w_max: float,
|
||||
acoustic_onsets: np.ndarray,
|
||||
candidate_onsets: np.ndarray,
|
||||
frame_times: np.ndarray,
|
||||
is_voiced: np.ndarray,
|
||||
hop_sec: float,
|
||||
is_line_start: bool = False,
|
||||
) -> float:
|
||||
"""Snap target timestamp to nearest vocal onset, acoustic transient, or voicing edge."""
|
||||
idx_target = int(round(target_t / hop_sec)) if hop_sec > 0 else 0
|
||||
if 0 <= idx_target < len(is_voiced):
|
||||
if is_line_start:
|
||||
lookback_idx = max(0, idx_target - int(1.2 / hop_sec))
|
||||
k = idx_target
|
||||
if not is_voiced[k]:
|
||||
fwd_limit = min(len(is_voiced), idx_target + int(0.5 / hop_sec))
|
||||
found_v = None
|
||||
for j in range(k, fwd_limit):
|
||||
if is_voiced[j]:
|
||||
found_v = j
|
||||
break
|
||||
if found_v is not None:
|
||||
k = found_v
|
||||
if is_voiced[k]:
|
||||
while k > lookback_idx and (is_voiced[k - 1] or (k > 2 and is_voiced[k - 2])):
|
||||
k -= 1
|
||||
voiced_t = float(frame_times[k])
|
||||
cands = acoustic_onsets[(acoustic_onsets >= voiced_t - 0.08) & (acoustic_onsets <= voiced_t + 0.08)]
|
||||
if len(cands) > 0:
|
||||
return float(cands[np.argmin(np.abs(cands - voiced_t))])
|
||||
return voiced_t
|
||||
|
||||
if not is_voiced[idx_target]:
|
||||
# Check if there is an acoustic transient near the target (e.g. consonant attack)
|
||||
ac_near = acoustic_onsets[
|
||||
(acoustic_onsets >= max(w_min, target_t - 0.08)) & (acoustic_onsets <= min(w_max, target_t + 0.06))
|
||||
]
|
||||
if len(ac_near) > 0:
|
||||
return float(ac_near[np.argmin(np.abs(ac_near - target_t))])
|
||||
|
||||
fwd_mask = (frame_times >= target_t) & (frame_times <= w_max) & is_voiced
|
||||
if np.any(fwd_mask):
|
||||
first_voiced = float(frame_times[fwd_mask][0])
|
||||
cands = acoustic_onsets[(acoustic_onsets >= first_voiced - 0.06) & (acoustic_onsets <= first_voiced + 0.06)]
|
||||
if len(cands) > 0:
|
||||
return float(cands[np.argmin(np.abs(cands - first_voiced))])
|
||||
return first_voiced
|
||||
|
||||
cands = candidate_onsets[(candidate_onsets >= w_min) & (candidate_onsets <= w_max)]
|
||||
if len(cands) == 0:
|
||||
return target_t
|
||||
return float(cands[np.argmin(np.abs(cands - target_t))])
|
||||
|
||||
|
||||
def segment_melisma(
|
||||
s_start: float,
|
||||
s_end: float,
|
||||
frame_times: np.ndarray,
|
||||
midi_frames: np.ndarray,
|
||||
is_voiced: np.ndarray,
|
||||
hop_sec: float,
|
||||
min_len: float = 0.20,
|
||||
min_pitch_jump: float = 1.6,
|
||||
) -> list[tuple[float, float, float]]:
|
||||
"""Segment multi-pitch syllables into base syllable + melisma continuation note."""
|
||||
mask = (frame_times >= s_start) & (frame_times <= s_end) & is_voiced
|
||||
if not np.any(mask):
|
||||
return [(s_start, s_end, 60.0)]
|
||||
|
||||
sub_times = frame_times[mask]
|
||||
sub_midis = midi_frames[mask]
|
||||
min_frames = int(min_len / hop_sec) if hop_sec > 0 else 1
|
||||
|
||||
if len(sub_times) < 2 * min_frames:
|
||||
return [(s_start, s_end, float(np.median(sub_midis)))]
|
||||
|
||||
best_split = None
|
||||
best_diff = 0.0
|
||||
for k in range(min_frames, len(sub_times) - min_frames):
|
||||
p1 = np.median(sub_midis[:k])
|
||||
p2 = np.median(sub_midis[k:])
|
||||
diff = abs(p2 - p1)
|
||||
if diff >= min_pitch_jump and diff > best_diff:
|
||||
best_diff = diff
|
||||
best_split = float(sub_times[k])
|
||||
|
||||
if best_split is not None:
|
||||
p1 = float(np.median(sub_midis[sub_times < best_split]))
|
||||
p2 = float(np.median(sub_midis[sub_times >= best_split]))
|
||||
return [(s_start, best_split, p1), (best_split, s_end, p2)]
|
||||
|
||||
return [(s_start, s_end, float(np.median(sub_midis)))]
|
||||
|
||||
|
||||
class PitchStage(Stage):
|
||||
"""Stage 4 extracts vocal fundamental frequency and assigns median pitch per syllable."""
|
||||
|
||||
name = "s4_pitch"
|
||||
version = "1.0.0"
|
||||
version = "1.3.0"
|
||||
model_name = "torchcrepe-full"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s3_lyrics"]
|
||||
@ -103,7 +248,7 @@ class PitchStage(Stage):
|
||||
crepe_model = params["crepe_model"]
|
||||
self.model_name = f"torchcrepe-{crepe_model}"
|
||||
|
||||
# Load audio using soundfile (resample to 16000 Hz for CREPE)
|
||||
# Load audio using soundfile
|
||||
audio_data, sr = sf.read(str(vocals_wav), dtype="float32")
|
||||
if audio_data.ndim > 1:
|
||||
# Downmix to mono
|
||||
@ -111,80 +256,177 @@ class PitchStage(Stage):
|
||||
|
||||
crepe_sr = 16000
|
||||
hop_length = int(crepe_sr * (hop_length_ms / 1000.0))
|
||||
hop_sec = hop_length / crepe_sr
|
||||
|
||||
# Convert to torch tensor
|
||||
# Compute acoustic onsets using librosa
|
||||
try:
|
||||
onset_env = librosa.onset.onset_strength(y=audio_data, sr=sr)
|
||||
acoustic_onsets = librosa.onset.onset_detect(onset_envelope=onset_env, sr=sr, units="time")
|
||||
except Exception:
|
||||
acoustic_onsets = np.array([], dtype=np.float32)
|
||||
|
||||
# Convert to torch tensor for CREPE
|
||||
audio_tensor = torch.from_numpy(audio_data).unsqueeze(0)
|
||||
if sr != crepe_sr:
|
||||
import julius
|
||||
|
||||
audio_tensor = julius.resample_frac(audio_tensor, sr, crepe_sr)
|
||||
|
||||
device_str = config.get_device(self.name)
|
||||
if device_str.startswith("cuda") and not torch.cuda.is_available():
|
||||
device_str = "cpu"
|
||||
device = torch.device(device_str)
|
||||
crepe_cache_file = ctx.cache_dir / f"crepe_f0_{crepe_model}.npz"
|
||||
if crepe_cache_file.exists():
|
||||
cached_data = np.load(crepe_cache_file)
|
||||
pitch_hz = cached_data["pitch_hz"]
|
||||
periodicity = cached_data["periodicity"]
|
||||
else:
|
||||
device_str = config.get_device(self.name)
|
||||
if device_str.startswith("cuda") and not torch.cuda.is_available():
|
||||
device_str = "cpu"
|
||||
device = torch.device(device_str)
|
||||
|
||||
# Run CREPE pitch prediction
|
||||
pitch_hz, periodicity = torchcrepe.predict(
|
||||
audio_tensor.to(device),
|
||||
crepe_sr,
|
||||
hop_length=hop_length,
|
||||
fmin=50,
|
||||
fmax=1006,
|
||||
model=crepe_model,
|
||||
batch_size=2048,
|
||||
device=device,
|
||||
return_periodicity=True,
|
||||
)
|
||||
# Run CREPE pitch prediction
|
||||
pitch_hz_tensor, periodicity_tensor = torchcrepe.predict(
|
||||
audio_tensor.to(device),
|
||||
crepe_sr,
|
||||
hop_length=hop_length,
|
||||
fmin=50,
|
||||
fmax=1006,
|
||||
model=crepe_model,
|
||||
batch_size=2048,
|
||||
device=device,
|
||||
return_periodicity=True,
|
||||
)
|
||||
|
||||
pitch_hz = pitch_hz.squeeze(0).cpu().numpy()
|
||||
periodicity = periodicity.squeeze(0).cpu().numpy()
|
||||
pitch_hz = pitch_hz_tensor.squeeze(0).cpu().numpy()
|
||||
periodicity = periodicity_tensor.squeeze(0).cpu().numpy()
|
||||
np.savez_compressed(crepe_cache_file, pitch_hz=pitch_hz, periodicity=periodicity)
|
||||
|
||||
# Frame timestamps: t_k = k * (hop_length / crepe_sr)
|
||||
frame_times = np.arange(len(pitch_hz)) * (hop_length / crepe_sr)
|
||||
frame_times = np.arange(len(pitch_hz)) * hop_sec
|
||||
midi_frames = hz_to_midi(pitch_hz)
|
||||
|
||||
# Candidate onsets from voicing edges and pitch jumps
|
||||
is_voiced = (periodicity >= voicing_thresh) & (pitch_hz > 50)
|
||||
voiced_diff = np.diff(is_voiced.astype(int), prepend=0)
|
||||
voicing_starts = frame_times[voiced_diff == 1]
|
||||
|
||||
pitch_diff = np.zeros_like(midi_frames)
|
||||
pitch_diff[1:] = np.abs(np.diff(midi_frames))
|
||||
pitch_jump_onsets = frame_times[(pitch_diff >= 1.0) & is_voiced]
|
||||
|
||||
candidate_onsets = np.unique(np.concatenate([acoustic_onsets, voicing_starts, pitch_jump_onsets]))
|
||||
candidate_onsets.sort()
|
||||
|
||||
# Process each line and syllable
|
||||
vocal_lines: list[VocalLine] = []
|
||||
line_counter = 0
|
||||
syl_counter = 0
|
||||
|
||||
for line_dict in lyrics_data.get("lines", []):
|
||||
all_lines = lyrics_data.get("lines", [])
|
||||
is_voiced_strict = (periodicity >= LINE_END_VOICING_THRESHOLD) & (pitch_hz > 50)
|
||||
|
||||
for line_pos, line_dict in enumerate(all_lines):
|
||||
sylls = line_dict.get("syllables", [])
|
||||
if not sylls:
|
||||
continue
|
||||
next_line_start = None
|
||||
for later in all_lines[line_pos + 1 :]:
|
||||
if later.get("syllables"):
|
||||
next_line_start = float(later["syllables"][0]["start"])
|
||||
break
|
||||
|
||||
line_counter += 1
|
||||
line_syllables_raw = []
|
||||
prev_end = 0.0
|
||||
|
||||
for syl_dict in line_dict.get("syllables", []):
|
||||
s_start = float(syl_dict["start"])
|
||||
s_end = float(syl_dict["end"])
|
||||
text = syl_dict["text"]
|
||||
w_end = syl_dict.get("word_end", False)
|
||||
for idx, s in enumerate(sylls):
|
||||
s_start = float(s["start"])
|
||||
s_end = float(s["end"])
|
||||
|
||||
# Frames within syllable
|
||||
mask = (frame_times >= s_start) & (frame_times <= s_end)
|
||||
voiced_mask = mask & (periodicity >= voicing_thresh) & (pitch_hz > 50)
|
||||
w_min = max(prev_end, s_start - 0.12)
|
||||
w_max = s_start + (0.50 if idx == 0 else 0.20)
|
||||
|
||||
if np.any(voiced_mask):
|
||||
voiced_midis = midi_frames[voiced_mask]
|
||||
voiced_confs = periodicity[voiced_mask]
|
||||
median_midi = float(np.median(voiced_midis))
|
||||
conf = float(np.mean(voiced_confs))
|
||||
elif np.any(mask):
|
||||
median_midi = float(np.median(midi_frames[mask]))
|
||||
conf = float(np.mean(periodicity[mask])) * 0.5
|
||||
else:
|
||||
median_midi = 60.0
|
||||
conf = 0.1
|
||||
|
||||
line_syllables_raw.append(
|
||||
{
|
||||
"text": text,
|
||||
"start": s_start,
|
||||
"end": s_end,
|
||||
"midi": median_midi,
|
||||
"confidence": float(np.clip(conf, 0.0, 1.0)),
|
||||
"word_end": w_end,
|
||||
}
|
||||
snapped_start = snap_onset(
|
||||
s_start,
|
||||
w_min,
|
||||
w_max,
|
||||
acoustic_onsets=acoustic_onsets,
|
||||
candidate_onsets=candidate_onsets,
|
||||
frame_times=frame_times,
|
||||
is_voiced=is_voiced,
|
||||
hop_sec=hop_sec,
|
||||
is_line_start=(idx == 0),
|
||||
)
|
||||
if snapped_start < prev_end:
|
||||
snapped_start = prev_end
|
||||
|
||||
real_end = max(snapped_start + 0.08, s_end)
|
||||
|
||||
# Extend held vowels if singer continues voicing beyond Whisper speech boundary
|
||||
next_start_limit = (
|
||||
float(sylls[idx + 1]["start"]) - 0.04 if idx < len(sylls) - 1 else real_end + 3.0
|
||||
)
|
||||
if real_end < next_start_limit:
|
||||
idx_end = int(round(real_end / hop_sec)) if hop_sec > 0 else 0
|
||||
while (
|
||||
idx_end < len(is_voiced)
|
||||
and is_voiced[idx_end]
|
||||
and frame_times[idx_end] < next_start_limit
|
||||
):
|
||||
idx_end += 1
|
||||
extended_end = float(frame_times[min(len(frame_times) - 1, idx_end)])
|
||||
if extended_end > real_end:
|
||||
real_end = min(next_start_limit, extended_end)
|
||||
|
||||
if idx == len(sylls) - 1:
|
||||
# Line end: end of the strictly voiced run after the last word (holds sustained vowels)
|
||||
cap_t = next_line_start - 0.05 if next_line_start is not None else s_end + 3.0
|
||||
strict_end = voiced_run_end(
|
||||
is_voiced_strict,
|
||||
s_start,
|
||||
hop_sec,
|
||||
LINE_END_MAX_GAP_SEC,
|
||||
cap_t,
|
||||
resume_max_gap_sec=LINE_END_RESUME_MAX_GAP_SEC,
|
||||
resume_min_run_sec=LINE_END_RESUME_MIN_RUN_SEC,
|
||||
)
|
||||
real_end = max(snapped_start + 0.08, min(strict_end, cap_t))
|
||||
|
||||
segs = segment_melisma(
|
||||
snapped_start,
|
||||
real_end,
|
||||
frame_times=frame_times,
|
||||
midi_frames=midi_frames,
|
||||
is_voiced=is_voiced,
|
||||
hop_sec=hop_sec,
|
||||
)
|
||||
|
||||
for seg_idx, (seg_start, seg_end, seg_midi) in enumerate(segs):
|
||||
is_melisma = seg_idx > 0
|
||||
txt = "~ " if is_melisma else s["text"]
|
||||
is_word_end = s.get("word_end", False) if seg_idx == len(segs) - 1 else False
|
||||
|
||||
s_mask = (frame_times >= seg_start) & (frame_times <= seg_end)
|
||||
if np.any(s_mask):
|
||||
conf = float(np.mean(periodicity[s_mask]))
|
||||
else:
|
||||
conf = 0.5
|
||||
|
||||
line_syllables_raw.append(
|
||||
{
|
||||
"text": txt,
|
||||
"start": seg_start,
|
||||
"end": seg_end,
|
||||
"midi": seg_midi,
|
||||
"confidence": float(np.clip(conf, 0.0, 1.0)),
|
||||
"word_end": is_word_end,
|
||||
}
|
||||
)
|
||||
prev_end = line_syllables_raw[-1]["end"]
|
||||
|
||||
# Prevent overlapping within line
|
||||
for i in range(len(line_syllables_raw) - 1):
|
||||
if line_syllables_raw[i]["end"] > line_syllables_raw[i + 1]["start"]:
|
||||
line_syllables_raw[i]["end"] = line_syllables_raw[i + 1]["start"]
|
||||
|
||||
# Apply octave error correction within phrase
|
||||
corrected_sylls = correct_octave_errors(line_syllables_raw)
|
||||
@ -214,8 +456,8 @@ class PitchStage(Stage):
|
||||
VocalLine(
|
||||
id=f"l_{line_counter:04d}",
|
||||
voice=0,
|
||||
start=line_dict["start"],
|
||||
end=line_dict["end"],
|
||||
start=syl_objects[0].start,
|
||||
end=syl_objects[-1].end,
|
||||
syllables=syl_objects,
|
||||
)
|
||||
)
|
||||
@ -240,7 +482,6 @@ class PitchStage(Stage):
|
||||
try:
|
||||
from unmix.schema.vocals_f0 import VocalsF0Document
|
||||
|
||||
hop_sec = hop_length / crepe_sr
|
||||
f0_hz: list[float | None] = [
|
||||
round(float(h), 2) if p >= voicing_thresh and h > 50 else None
|
||||
for h, p in zip(pitch_hz, periodicity, strict=False)
|
||||
|
||||
56
src/unmix/pipeline/source_modes.py
Normal file
56
src/unmix/pipeline/source_modes.py
Normal file
@ -0,0 +1,56 @@
|
||||
"""Input modes of a song package.
|
||||
|
||||
Mode 1 (audio only): Whisper transcribes the lyrics. vocals_source = "whisper"
|
||||
Mode 2 (UltraStar): notes and timings of the .txt are the result. vocals_source = "reference_ultrastar"
|
||||
Mode 3 (lyrics): given text is aligned to the audio. vocals_source = "lyrics_aligned"
|
||||
|
||||
Mode 2 overwrites vocals.json with the ground truth. Without the helpers below, a later run would take that
|
||||
ground truth for the AI prediction and keep a stale pitch cache.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
|
||||
PITCH_CACHE = "s4_pitch.json"
|
||||
AI_BACKUP = "vocals_ai.json"
|
||||
GROUND_TRUTH = "reference_ultrastar"
|
||||
|
||||
|
||||
def mode_label(lyrics_given: bool) -> str:
|
||||
return "lyrics_aligned" if lyrics_given else "whisper"
|
||||
|
||||
|
||||
def previous_vocals_source(meta_file: Path) -> str | None:
|
||||
if not meta_file.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(meta_file.read_text(encoding="utf-8")).get("vocals_source")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
def prepare_ai_vocals(output_dir: Path, cache_dir: Path, vocals_source: str) -> VocalsDocument | None:
|
||||
"""Return the AI prediction for evaluation, never a ground truth written by an earlier run.
|
||||
|
||||
While vocals.json holds the AI result, a copy is kept in the cache. Once it holds the ground truth,
|
||||
only that copy is valid. Returns None if no AI result is available.
|
||||
"""
|
||||
backup = cache_dir / AI_BACKUP
|
||||
if vocals_source == GROUND_TRUTH:
|
||||
if not backup.exists():
|
||||
return None
|
||||
return VocalsDocument.model_validate(json.loads(backup.read_text(encoding="utf-8")))
|
||||
vocals_json = output_dir / "vocals.json"
|
||||
if not vocals_json.exists():
|
||||
return None
|
||||
doc = VocalsDocument.model_validate(json.loads(vocals_json.read_text(encoding="utf-8")))
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
backup.write_text(doc.model_dump_json(indent=2), encoding="utf-8")
|
||||
return doc
|
||||
|
||||
|
||||
def invalidate_pitch_cache(cache_dir: Path) -> None:
|
||||
"""Drop the cached pitch stage so the next run recomputes vocals.json instead of reusing a ground truth."""
|
||||
(cache_dir / PITCH_CACHE).unlink(missing_ok=True)
|
||||
@ -90,6 +90,10 @@ class MetaDocument(SongPackageBase):
|
||||
stages_done: list[str] = Field(default_factory=list)
|
||||
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
|
||||
|
||||
|
||||
# Backward compatibility helper
|
||||
@property
|
||||
|
||||
130
tests/test_align.py
Normal file
130
tests/test_align.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""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")
|
||||
@ -84,3 +84,10 @@ def test_config_device_detection(monkeypatch):
|
||||
# Test explicit CUDA requested on non-CUDA system falls back to cpu
|
||||
monkeypatch.setenv("UNMIX_DEVICE_S2", "cuda:99")
|
||||
assert cfg.get_device("s2_stems") == "cpu"
|
||||
|
||||
|
||||
def test_cli_import_ultrastar_help():
|
||||
result = runner.invoke(app, ["import-ultrastar", "--help"])
|
||||
assert result.exit_code == 0
|
||||
assert "Import an UltraStar song.txt" in result.stdout
|
||||
|
||||
|
||||
@ -37,3 +37,57 @@ def test_split_word_into_syllables_timed():
|
||||
# Syllables should be "Hel" and "lo "
|
||||
assert timed[0]["text"] == "Hel"
|
||||
assert timed[1]["text"] == "lo "
|
||||
|
||||
|
||||
def test_split_into_vocal_lines_by_gap_and_length():
|
||||
from unmix.pipeline.s3_lyrics import split_into_vocal_lines
|
||||
|
||||
def syl(text, start, end, word_end=True):
|
||||
return {"text": text, "start": start, "end": end, "word_end": word_end}
|
||||
|
||||
# Pause of 1.0 s between words -> two lines
|
||||
sylls = [syl("a ", 0.0, 0.5), syl("b ", 0.5, 1.0), syl("c ", 2.0, 2.5)]
|
||||
assert [len(c) for c in split_into_vocal_lines(sylls)] == [2, 1]
|
||||
|
||||
# No pause but > max_line_sec -> split at word boundary, never inside a word
|
||||
long_line = [syl("x", 0.0, 2.0, word_end=False), syl("y ", 2.0, 4.0), syl("z ", 4.0, 6.0), syl("w ", 6.0, 8.0)]
|
||||
chunks = split_into_vocal_lines(long_line)
|
||||
assert len(chunks) >= 2
|
||||
assert chunks[0][-1]["word_end"] is True
|
||||
assert sum(len(c) for c in chunks) == 4
|
||||
|
||||
assert split_into_vocal_lines([]) == []
|
||||
|
||||
|
||||
def test_orphan_trailing_word_moves_to_next_segment():
|
||||
from unmix.pipeline.s3_lyrics import pop_trailing_orphan, prepend_orphan
|
||||
|
||||
def syl(text, start, end, word_end=True):
|
||||
return {"text": text, "start": start, "end": end, "word_end": word_end}
|
||||
|
||||
chunks = [[syl("any ", 34.7, 36.1)], [syl("If ", 37.0, 37.8)]]
|
||||
rest, orphan = pop_trailing_orphan(chunks)
|
||||
assert len(rest) == 1 and orphan is not None
|
||||
|
||||
nxt = prepend_orphan(orphan, [[syl("I ", 40.9, 41.1), syl("lay ", 41.1, 41.4)]])
|
||||
assert [s["text"] for s in nxt[0]] == ["If ", "I ", "lay "]
|
||||
assert nxt[0][0]["start"] == 40.9
|
||||
assert nxt[0][1]["start"] >= nxt[0][0]["end"]
|
||||
|
||||
# Long single word (> 1 s) stays a line of its own
|
||||
chunks2 = [[syl("a ", 1.0, 2.0)], [syl("b ", 5.0, 7.5)]]
|
||||
assert pop_trailing_orphan(chunks2) == (chunks2, None)
|
||||
|
||||
|
||||
def test_merge_leading_orphan():
|
||||
from unmix.pipeline.s3_lyrics import merge_leading_orphan
|
||||
|
||||
def syl(text, start, end, word_end=True):
|
||||
return {"text": text, "start": start, "end": end, "word_end": word_end}
|
||||
|
||||
chunks = [[syl("If ", 37.0, 37.8)], [syl("I ", 40.9, 41.1), syl("lay ", 41.1, 41.4)]]
|
||||
merged = merge_leading_orphan(chunks)
|
||||
assert len(merged) == 1
|
||||
assert [s["text"] for s in merged[0]] == ["If ", "I ", "lay "]
|
||||
assert merged[0][0]["start"] == 40.9
|
||||
assert len(merge_leading_orphan([[syl("a ", 0.0, 0.5)]])) == 1
|
||||
|
||||
@ -6,6 +6,7 @@ from unmix.eval.metrics import (
|
||||
evaluate_vocals,
|
||||
extract_text_from_reference,
|
||||
extract_text_from_vocals,
|
||||
generate_training_diff,
|
||||
normalize_text_for_wer,
|
||||
)
|
||||
from unmix.export.ultrastar import UltraStarNote, UltraStarSong
|
||||
@ -134,3 +135,59 @@ def test_evaluate_vocals_octave_error_and_timing_offset():
|
||||
# Median octave offset should be -1.0
|
||||
assert metrics["median_octave_offset"] == pytest.approx(-1.0)
|
||||
assert metrics["wer"] == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_generate_training_diff():
|
||||
ref_song = UltraStarSong(
|
||||
headers={"BPM": "120", "GAP": "1000"},
|
||||
lines=[
|
||||
[
|
||||
UltraStarNote(":", 0, 4, 0, "First ", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||
UltraStarNote(":", 4, 4, 2, "Second ", start_sec=1.5, end_sec=2.0, midi=62.0),
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
pred_doc = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=1.02,
|
||||
end=1.52,
|
||||
syllables=[
|
||||
VocalSyllable(text="First", start=1.02, end=1.52, midi=60.0, word_end=True),
|
||||
VocalSyllable(text="Extra", start=5.0, end=5.5, midi=65.0, word_end=True),
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
diff = generate_training_diff(pred_doc, ref_song)
|
||||
assert "summary" in diff
|
||||
assert "systematic_biases" in diff
|
||||
assert "matched_notes" in diff
|
||||
assert "unmatched_reference_notes" in diff
|
||||
assert "unmatched_predictions" in diff
|
||||
|
||||
# Matched note checks
|
||||
assert len(diff["matched_notes"]) == 1
|
||||
m0 = diff["matched_notes"][0]
|
||||
assert m0["ref_text"] == "First"
|
||||
assert m0["pred_text"] == "First"
|
||||
assert m0["timing_error_ms"] == pytest.approx(20.0, abs=1.0)
|
||||
assert m0["pitch_error_semitones"] == pytest.approx(0.0)
|
||||
|
||||
# Unmatched reference note: "Second" was missed by AI
|
||||
assert len(diff["unmatched_reference_notes"]) == 1
|
||||
assert diff["unmatched_reference_notes"][0]["text"] == "Second"
|
||||
|
||||
# Unmatched prediction: "Extra" was hallucinated / extra
|
||||
assert len(diff["unmatched_predictions"]) == 1
|
||||
assert diff["unmatched_predictions"][0]["text"] == "Extra"
|
||||
|
||||
# Systematic biases
|
||||
biases = diff["systematic_biases"]
|
||||
assert biases["matched_notes_count"] == 1
|
||||
assert biases["unmatched_ref_notes_count"] == 1
|
||||
assert biases["unmatched_predictions_count"] == 1
|
||||
assert biases["mean_timing_bias_ms"] == pytest.approx(20.0, abs=1.0)
|
||||
|
||||
|
||||
@ -39,3 +39,37 @@ def test_no_correction_for_legitimate_contour():
|
||||
]
|
||||
corrected = correct_octave_errors(syllables)
|
||||
assert corrected[1]["midi"] == 64.0
|
||||
|
||||
|
||||
def test_voiced_run_end_bridges_short_gaps():
|
||||
import numpy as np
|
||||
|
||||
from unmix.pipeline.s4_pitch import voiced_run_end
|
||||
|
||||
hop = 0.01
|
||||
v = np.zeros(300, dtype=bool)
|
||||
v[100:150] = True # 1.00-1.50 s
|
||||
v[155:200] = True # gap of 0.05 s, then voiced until 2.00 s
|
||||
v[260:290] = True # separate run after a 0.6 s gap
|
||||
|
||||
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=5.0) == pytest.approx(2.0)
|
||||
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.0, cap_t=5.0) == pytest.approx(1.5)
|
||||
# cap stops the run
|
||||
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=1.3) <= 1.31
|
||||
|
||||
|
||||
def test_voiced_run_end_bridges_longer_gap_only_if_voicing_resumes():
|
||||
import numpy as np
|
||||
|
||||
from unmix.pipeline.s4_pitch import voiced_run_end
|
||||
|
||||
hop = 0.01
|
||||
v = np.zeros(400, dtype=bool)
|
||||
v[100:150] = True # 1.00-1.50 s
|
||||
v[170:230] = True # gap 0.20 s, then a long run (0.60 s) until 2.30 s
|
||||
v[250:260] = True # gap 0.20 s, then a short run (0.10 s)
|
||||
|
||||
kwargs = {"resume_max_gap_sec": 0.3, "resume_min_run_sec": 0.3}
|
||||
assert voiced_run_end(v, 1.0, hop, 0.1, 5.0, **kwargs) == pytest.approx(2.3)
|
||||
# without the resume rule the 0.2 s gap ends the run
|
||||
assert voiced_run_end(v, 1.0, hop, 0.1, 5.0) == pytest.approx(1.5)
|
||||
|
||||
76
tests/test_source_modes.py
Normal file
76
tests/test_source_modes.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Tests for the input modes: AI backup vs. ground truth in vocals.json, pitch cache invalidation."""
|
||||
|
||||
import json
|
||||
|
||||
from unmix.pipeline.source_modes import (
|
||||
invalidate_pitch_cache,
|
||||
mode_label,
|
||||
prepare_ai_vocals,
|
||||
previous_vocals_source,
|
||||
)
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def _doc(text: str, start: float = 1.0) -> VocalsDocument:
|
||||
syl = VocalSyllable(text=text, start=start, end=start + 0.5, midi=60.0, word_end=True)
|
||||
return VocalsDocument(lines=[VocalLine(start=start, end=start + 0.5, syllables=[syl])])
|
||||
|
||||
|
||||
def _text(doc: VocalsDocument) -> str:
|
||||
return doc.lines[0].syllables[0].text
|
||||
|
||||
|
||||
def test_first_run_returns_ai_and_backs_it_up(tmp_path):
|
||||
out = tmp_path / "out"
|
||||
out.mkdir()
|
||||
(out / "vocals.json").write_text(_doc("ai").model_dump_json(), encoding="utf-8")
|
||||
|
||||
ai = prepare_ai_vocals(out, out / ".cache", "whisper")
|
||||
|
||||
assert _text(ai) == "ai"
|
||||
assert (out / ".cache" / "vocals_ai.json").exists()
|
||||
|
||||
|
||||
def test_run_after_ground_truth_write_uses_backup_not_reference(tmp_path):
|
||||
out = tmp_path / "out"
|
||||
cache = out / ".cache"
|
||||
out.mkdir()
|
||||
(out / "vocals.json").write_text(_doc("ai").model_dump_json(), encoding="utf-8")
|
||||
prepare_ai_vocals(out, cache, "whisper") # first --ultrastar run backs up the AI result
|
||||
(out / "vocals.json").write_text(_doc("ground-truth").model_dump_json(), encoding="utf-8")
|
||||
|
||||
# second run in the same folder: vocals.json now holds the reference
|
||||
ai = prepare_ai_vocals(out, cache, "reference_ultrastar")
|
||||
|
||||
assert _text(ai) == "ai"
|
||||
|
||||
|
||||
def test_reference_source_without_backup_gives_no_ai(tmp_path):
|
||||
out = tmp_path / "out"
|
||||
out.mkdir()
|
||||
(out / "vocals.json").write_text(_doc("ground-truth").model_dump_json(), encoding="utf-8")
|
||||
|
||||
assert prepare_ai_vocals(out, out / ".cache", "reference_ultrastar") is None
|
||||
|
||||
|
||||
def test_invalidate_pitch_cache_removes_only_pitch_stage(tmp_path):
|
||||
(tmp_path / "s4_pitch.json").write_text("{}", encoding="utf-8")
|
||||
(tmp_path / "s3_lyrics.json").write_text("{}", encoding="utf-8")
|
||||
|
||||
invalidate_pitch_cache(tmp_path)
|
||||
invalidate_pitch_cache(tmp_path) # no error when already gone
|
||||
|
||||
assert not (tmp_path / "s4_pitch.json").exists()
|
||||
assert (tmp_path / "s3_lyrics.json").exists()
|
||||
|
||||
|
||||
def test_previous_vocals_source_and_mode_label(tmp_path):
|
||||
meta = tmp_path / "meta.json"
|
||||
assert previous_vocals_source(meta) is None
|
||||
meta.write_text(json.dumps({"vocals_source": "reference_ultrastar"}), encoding="utf-8")
|
||||
assert previous_vocals_source(meta) == "reference_ultrastar"
|
||||
meta.write_text("not json", encoding="utf-8")
|
||||
assert previous_vocals_source(meta) is None
|
||||
|
||||
assert mode_label(False) == "whisper"
|
||||
assert mode_label(True) == "lyrics_aligned"
|
||||
@ -4,7 +4,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from unmix.export.ultrastar import export_ultrastar, import_ultrastar, parse_ultrastar, ultrastar_to_vocals
|
||||
from unmix.schema.meta import MetaDocument, SourceFileInfo
|
||||
from unmix.schema.tempo import TempoAnchor, TempoDocument
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
@ -155,3 +155,64 @@ def test_ultrastar_metadata_and_language_english(tmp_path: Path):
|
||||
last_note = parsed.lines[1][0]
|
||||
assert last_note.start_sec == pytest.approx(250.0, abs=0.15)
|
||||
assert last_note.end_sec == pytest.approx(258.7, abs=0.15)
|
||||
|
||||
|
||||
def test_ultrastar_to_vocals_and_import(tmp_path: Path):
|
||||
txt_content = """#TITLE:Imported Song
|
||||
#ARTIST:Imported Artist
|
||||
#BPM:120
|
||||
#GAP:1000
|
||||
: 0 4 0 Hel-
|
||||
: 4 4 2 lo
|
||||
* 8 8 4 World
|
||||
- 16
|
||||
: 20 4 0 Again
|
||||
E
|
||||
"""
|
||||
txt_file = tmp_path / "song.txt"
|
||||
txt_file.write_text(txt_content, encoding="utf-8")
|
||||
|
||||
song = parse_ultrastar(txt_file)
|
||||
doc = ultrastar_to_vocals(song)
|
||||
|
||||
assert len(doc.lines) == 2
|
||||
l0 = doc.lines[0]
|
||||
assert len(l0.syllables) == 3
|
||||
assert l0.syllables[0].text == "Hel-"
|
||||
assert l0.syllables[0].word_end is False
|
||||
assert l0.syllables[1].text == "lo"
|
||||
assert l0.syllables[1].word_end is True
|
||||
assert l0.syllables[2].text == "World"
|
||||
assert l0.syllables[2].golden is True
|
||||
assert l0.syllables[2].type == "golden"
|
||||
|
||||
# Test import_ultrastar creates vocals.json
|
||||
out_dir = tmp_path / "imported_pkg"
|
||||
vocals_json = import_ultrastar(txt_file, out_dir)
|
||||
assert vocals_json.exists()
|
||||
|
||||
with open(vocals_json, encoding="utf-8") as vf:
|
||||
loaded = VocalsDocument.model_validate_json(vf.read())
|
||||
assert len(loaded.lines) == 2
|
||||
assert loaded.lines[0].syllables[2].type == "golden"
|
||||
|
||||
|
||||
|
||||
def test_parse_ultrastar_leading_space_word_convention(tmp_path):
|
||||
from unmix.eval.metrics import extract_text_from_reference
|
||||
from unmix.export.ultrastar import parse_ultrastar
|
||||
|
||||
f = tmp_path / "lead.txt"
|
||||
f.write_text(
|
||||
"#TITLE:T\n#ARTIST:A\n#BPM:120\n#GAP:0\n"
|
||||
": 0 4 4 She\n: 8 6 9 came\n: 18 2 9 to\n: 22 4 9 ~r\n- 30\n: 32 4 2 me\nE\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
song = parse_ultrastar(f)
|
||||
assert extract_text_from_reference(song) == "She came to~r me"
|
||||
assert song.lines[0][0].text == "She "
|
||||
assert song.lines[0][1].text == "came "
|
||||
# trailing-space convention is unchanged
|
||||
g = tmp_path / "trail.txt"
|
||||
g.write_text("#BPM:120\n#GAP:0\n: 0 4 4 We \n: 5 4 4 do \nE\n", encoding="utf-8")
|
||||
assert extract_text_from_reference(parse_ultrastar(g)) == "We do"
|
||||
|
||||
9
testset.example.toml
Normal file
9
testset.example.toml
Normal file
@ -0,0 +1,9 @@
|
||||
# Beispiel-Konfiguration für unmix eval
|
||||
# Lokale Testsets können als testset.local.toml angelegt werden (in .gitignore).
|
||||
|
||||
[[songs]]
|
||||
name = "Demo Song"
|
||||
# audio ist optional: wenn weggelassen, wird die Audio-Quelle automatisch über den #VIDEO: Tag der Referenz-Datei via yt-dlp bezogen.
|
||||
# audio = "songs/demo.mp3"
|
||||
reference = "songs/reference_ultrastar.txt"
|
||||
lang = "de"
|
||||
Reference in New Issue
Block a user