Compare commits
13 Commits
feat/songp
...
3fdd639f47
| Author | SHA1 | Date | |
|---|---|---|---|
| 3fdd639f47 | |||
| 4024b74953 | |||
| 769910286f | |||
| c73ad8d66b | |||
| dcde066772 | |||
| c93d2c696e | |||
| d4745a48e0 | |||
| 8ea78914ac | |||
| 6b3c82738c | |||
| cb3047ddae | |||
| 58ff3fe59a | |||
| c327d5c4c4 | |||
| 7bbc6b78df |
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
|
||||
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Stephan Wilkins / wlkns-dev
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
220
README.md
220
README.md
@ -1,57 +1,203 @@
|
||||
# songsplit
|
||||
# unmix
|
||||
|
||||
`songsplit` zerlegt Songs (Video oder Audio) in ein **Song-Paket**: getrennte Stems, Text mit Wort-/Silben-Timing, Gesangsnoten, Tempo-Map, Akkorde und Strumming-Vorschlag. Das Paket dient als Schnittstelle für Trainer-Apps und Editoren.
|
||||
Audio-Analyse-Pipeline, die Songs (Audio/Video) in strukturierte Songpacks zerlegt: getrennte Stems, Text mit Silbentiming, Noten, Tempo-Map, Akkorde und Instrumenten-Tracks für Übungs-Apps und Editoren.
|
||||
|
||||
Verbindliche Spezifikation: siehe [umsetzungskonzept.md](umsetzungskonzept.md).
|
||||
## Why unmix exists
|
||||
|
||||
## Installation & Setup
|
||||
Bestehende Audio-KI-Tools lösen meist nur ein isoliertes Einzelproblem: Demucs trennt Spuren, Whisper transkribiert Text ohne Tonhöhen, CREPE liefert unstrukturierte Rohfrequenzen und Beat-Tracker berechnen oft starre BPM-Durchschnitte.
|
||||
|
||||
Entwicklungsumgebung mit Python 3.12 und `uv`:
|
||||
Um Songs für interaktive Musiktrainer (Gesang, Gitarre, Klavier) und Editoren nutzbar zu machen, braucht man jedoch ein verlässliches, typisiertes Datenpaket, in dem Gesangszeiten (Sekunden), Rhythmus/Akkorde (Beats) und isolierte Audio-Stems exakt aufeinander abgestimmt sind. `unmix` verbindet die besten State-of-the-Art-Open-Source-KI-Modelle in einer robusten, modular gecachten Pipeline mit dem standardisierten [Songpack-Format](songpack-spec.md).
|
||||
|
||||
*Contributions:* Fehlerberichte und Feature-Wünsche sind als Issues und Pull Requests herzlich willkommen.
|
||||
|
||||
## 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.
|
||||
|
||||
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`.
|
||||
|
||||
## 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>`.
|
||||
|
||||
**Urheberrecht & Weitergabe:** Das Weitergeben von Songpacks in der Variante `full` (inklusive getrennter Original-Audiospuren) unterliegt dem Urheberrecht der jeweiligen Musikaufnahme. Für das Weitergeben von Noten, Text und Akkorden fremder Songs steht die Variante `unmix pack <ordner> --variant data` zur Verfügung (enthält keine Audiospuren; Empfänger ordnen ihre eigene Aufnahme über `meta.audio_ref` zu).
|
||||
|
||||
**Disclaimer:** `unmix` ist ein unabhängiges Open-Source-Projekt und nicht verbunden mit den Urhebern der analysierten Musiktitel oder den Entwicklern von UltraStar Deluxe.
|
||||
|
||||
## How this was built
|
||||
|
||||
`unmix` wurde nach den Grundsätzen moderner Softwarearchitektur entwickelt:
|
||||
- Strenge Typisierung und Validierung aller Schnittstellen mittels **Pydantic v2**
|
||||
- Deterministische Hash-Invalidierung und Zwischenergebnis-Caching in `.cache/`
|
||||
- Vollständige Entkopplung von Gesangs- und Instrumentenzweig
|
||||
- Umfassende automatisierte Testabdeckung mit synthetischen, lizenzfreien Audiodaten
|
||||
- Entwickelt im Pair-Programming mit Google DeepMind Advanced Agentic Coding
|
||||
|
||||
## Install
|
||||
|
||||
Das Tool wird mit dem schnellen Python-Paketmanager `uv` installiert:
|
||||
|
||||
### Mit uv (empfohlen)
|
||||
|
||||
```bash
|
||||
# Virtuelle Umgebung erstellen und Abhängigkeiten installieren
|
||||
# Repository klonen
|
||||
git clone ssh://git@git.wlkns.org:2222/wlkns-dev/unmix.git unmix
|
||||
cd unmix
|
||||
|
||||
# Virtuelle Umgebung mit Python 3.12 erstellen und Abhängigkeiten installieren
|
||||
uv venv --python 3.12
|
||||
source .venv/bin/activate
|
||||
uv pip install -e ".[dev]"
|
||||
|
||||
# System- und Hardwareprüfung durchführen
|
||||
uv run songsplit doctor
|
||||
unmix doctor
|
||||
```
|
||||
|
||||
## CLI-Verwendung
|
||||
|
||||
```bash
|
||||
# System- und GPU-Check
|
||||
songsplit doctor
|
||||
|
||||
# Gesamte Analyse oder bestimmte Stufen ausführen
|
||||
songsplit analyze <datei> -o <ordner> [--lang de] [--stems 4|6] [--quality fast|best]
|
||||
songsplit analyze <datei> -o <ordner> --stage tracks:strumming [--force]
|
||||
|
||||
# Songpack packen und sicher entpacken
|
||||
songsplit pack <ordner> [-o <datei.songpack>] [--variant full|data]
|
||||
songsplit unpack <datei.songpack> [-o <ordner>]
|
||||
|
||||
# Export nach UltraStar (ab M2)
|
||||
songsplit export-ultrastar <ordner>
|
||||
|
||||
# Qualitätsmessung (ab M2)
|
||||
songsplit eval <testset.toml>
|
||||
```
|
||||
|
||||
## Tests
|
||||
## Requirements
|
||||
|
||||
* **Betriebssystem:** Linux, macOS oder Windows (64-Bit)
|
||||
* **Python:** Version 3.12
|
||||
* **System-Binaries:** `ffmpeg` und `ffprobe` müssen im `PATH` vorhanden sein
|
||||
* **Arbeitsspeicher:** Mindestens 8 GB RAM (16 GB+ empfohlen)
|
||||
* **Hardware-Beschleunigung (optional):** CUDA- oder ROCm-fähige GPU für schnellere Berechnungen
|
||||
|
||||
## Build and run
|
||||
|
||||
```bash
|
||||
# Tests ausführen
|
||||
uv run pytest
|
||||
|
||||
# Code-Qualität und Formatierung prüfen
|
||||
uv run ruff check
|
||||
uv run ruff format --check
|
||||
```
|
||||
|
||||
## Meilensteine
|
||||
## What it does
|
||||
|
||||
- [x] **M0 – Gerüst**: Projektstruktur, Pydantic-Schemas (`meta.json`, `tempo.json`, `vocals.json`, `chords.json`, `strumming.json`), `tempo.py` mit `sec_to_beat`/`beat_to_sec`, Pipeline-Runner mit Cache und Hash-Invalidierung, CLI-Skelett mit `doctor`, Testsuite.
|
||||
- [x] **M1 – Extraktion und Stems**: Stufen 1 (ffmpeg 44.1 kHz stereo) und 2 (Demucs `htdemucs_ft` / `htdemucs_6s`, low-VRAM chunking mit segment/shifts, `instrumental.wav` und `vocals.wav`, SNR-Prüfung).
|
||||
- [x] **M2 – Gesang**: Stufe 3 (`whisper-large-v3` + `pyphen`-Silbentrennung mit proportionalem Timing), Stufe 4 (`torchcrepe-full` mit Medianhöhe & Oktavfehler-Korrektur), UltraStar-Export (`song.txt`) & Reader, Eval-Framework mit Timing-MAE, Pitch-Genauigkeit (strikt & oktav-äquivalent) und WER via `jiwer`.
|
||||
- [x] **M3 – Tempo-Map**: Stufe 5 (`beat_this` Beat- & Downbeat-Tracking mit `librosa`-Fallback), intelligente Segmentierung (Anker nur bei echten Tempowechseln), Metronom-Klick-Track-Synthese (`.cache/click_track.wav`), BPM/GAP-Ableitung für UltraStar.
|
||||
- [x] **M4 – Akkorde**: Stufe 6 (Harte-Notation, Beat-synchrone Quantisierung über Tempo-Map, `chordino` & `template` Backends, Tonarterkennung nach Krumhansl-Schmuckler in `meta.json`).
|
||||
- [x] **M5 – Strumming**: Stufe 7 (Onset-Erkennung auf Gitarren-/Instrumental-Stem, Spektralschwerpunkt- & Beatphasen-Gradient für Down/Up-Richtungsvorschlag, Beat-Raster-Quantisierung, Muster-Verdichtung `D . D U . U D U`, als `experimental` markiert).
|
||||
- [x] **M6 – Härtung**: Fehlerbehandlung, strukturiertes Logging, Formatspezifikation ([docs/format.md](docs/format.md)), lizenzfreies synthetisches Beispielpaket ([examples/demo_song/](examples/demo_song/)).
|
||||
`unmix` nimmt eine Musikdatei (Audio oder Video) entgegen und erzeugt daraus ein vollständiges, validiertes **Songpack** (als Ordner oder komprimiertes `.songpack`-Archiv).
|
||||
|
||||
### Core Features
|
||||
|
||||
| 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. |
|
||||
| **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`). |
|
||||
| **Sicherer Songpack-Container** | Packt und entpackt `.songpack`-Container mit Whitelist-Filterung, Pfadtraversierungs- und Zip-Bomben-Schutz. |
|
||||
|
||||
## How it works
|
||||
|
||||
Die Pipeline ist modular aufgebaut und in zwei parallele Stränge unterteilt:
|
||||
|
||||
```
|
||||
[ Audio- / Videodatei ]
|
||||
│
|
||||
Stufe 1: Extraktion (ffmpeg)
|
||||
│
|
||||
Stufe 2: Stems (Demucs v4)
|
||||
┌────────────┴────────────┐
|
||||
▼ ▼
|
||||
[ Gesangszweig ] [ Instrumentenzweig ]
|
||||
│ │
|
||||
Stufe 3: Lyrics Stufe 5: Tempo-Map
|
||||
(Whisper + Pyphen) (beat_this)
|
||||
│ │
|
||||
Stufe 4: Pitch Stufe 6: Akkorde
|
||||
(torchcrepe) (Chordino / Template)
|
||||
│ │
|
||||
│ Stufe 7: Instrumenten-Tracks
|
||||
│ (Strumming: Onsets + Grid)
|
||||
└────────────┬────────────┘
|
||||
▼
|
||||
[ Songpack v1.0 / Export ]
|
||||
manifest.json, meta.json, tempo.json,
|
||||
vocals.json, chords.json, tracks/guitar.json,
|
||||
stems/, export/song.txt
|
||||
```
|
||||
|
||||
Jede Stufe prüft vor der Ausführung, ob die Eingangsdaten und Parameter unverändert sind, und lädt das Ergebnis bei Bedarf blitzschnell aus dem `.cache/`.
|
||||
|
||||
## How to use / CLI & Configuration
|
||||
|
||||
Nach der Installation steht der CLI-Befehl `unmix` bereit:
|
||||
|
||||
### 1. Systemdiagnose
|
||||
```bash
|
||||
unmix doctor
|
||||
```
|
||||
|
||||
### 2. Gesamte Analyse ausführen
|
||||
```bash
|
||||
# Standardanalyse (beste Qualität, 4 Stems, deutsche Sprache)
|
||||
unmix analyze song.mp3 -o output_song/ --lang de
|
||||
|
||||
# Schnelle Analyse mit 6 Stems
|
||||
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 Dual-Track Referenzmodus (erzeugt perfektes Songpack + Trainings-Differenzprotokoll)
|
||||
unmix analyze song.mp3 -o output_song/ --lang en --reference ground_truth_song.txt
|
||||
|
||||
# Schneller Direkt-Import (übernimmt UltraStar-Gesang, rechnet nur Stems/Akkorde/Tempo)
|
||||
unmix import-ultrastar ground_truth_song.txt song.mp3 -o output_song/
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **Dual-Track & Training-Feedback (`--reference`):**
|
||||
> Wird `--reference <file.txt>` übergeben, nutzt `unmix` die verifizierten Referenznoten für das fertige Songpack (`vocals.json`) und vergleicht gleichzeitig die KI-Vorhersage Note für Note mit der Referenz. Die genaue Fehleranalyse wird in `training_diff.json` gespeichert (systematischer Timing- und Dauern-Drift, übersehene Noten, Melismen), um die Pipeline kontinuierlich datengetrieben zu verbessern.
|
||||
|
||||
|
||||
> [!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.
|
||||
|
||||
### 3. Gezielte Teilstufen ausführen
|
||||
```bash
|
||||
# Nur Akkorderkennung und deren Voraussetzungen rechnen
|
||||
unmix analyze song.mp3 -o output_song/ --stage chords
|
||||
|
||||
# Nur den Gitarren-Strumming-Track neu berechnen (ignoriert Cache mit --force)
|
||||
unmix analyze song.mp3 -o output_song/ --stage tracks:strumming --force
|
||||
```
|
||||
|
||||
### 4. Songpack packen und sicher entpacken
|
||||
```bash
|
||||
# Song-Ordner als vollständiges .songpack packen (inkl. Stems)
|
||||
unmix pack output_song/ -o my_song.songpack
|
||||
|
||||
# Nur Noten und Metadaten packen (ohne urheberrechtlich geschützte Audiodateien)
|
||||
unmix pack output_song/ -o my_song_data.songpack --variant data
|
||||
|
||||
# .songpack-Archiv mit Sicherheitsprüfungen entpacken
|
||||
unmix unpack my_song.songpack -o unpacked_song/
|
||||
```
|
||||
|
||||
### 5. UltraStar-Export & Qualitäts-Benchmarks
|
||||
```bash
|
||||
# UltraStar-Datei export/song.txt aktualisieren
|
||||
unmix export-ultrastar output_song/
|
||||
|
||||
# Evaluierungs-Benchmark gegen Referenzdaten laufen lassen
|
||||
unmix eval testset.toml
|
||||
```
|
||||
|
||||
## References & Links
|
||||
|
||||
* **[Songpack-Spezifikation](songpack-spec.md)** – Vollständige Spezifikation des Songpack-Containers v1.0.
|
||||
* **[Format-Dokumentation](docs/format.md)** – Detaillierte Felderklärung aller JSON-Schemas.
|
||||
* **[Demucs](https://github.com/facebookresearch/demucs)** – State-of-the-Art Musikquellentrennung (Meta Research).
|
||||
* **[faster-whisper](https://github.com/SYSTRAN/faster-whisper)** – Schnelle Sprach- und Texterkennung mit CTranslate2.
|
||||
* **[torchcrepe](https://github.com/maxrmorrison/torchcrepe)** – Neuronale Tonhöhenerkennung (CREPE in PyTorch).
|
||||
* **[beat_this](https://github.com/CPJKU/beat_this)** – Modernes Transformer-basiertes Beat- und Downbeat-Tracking.
|
||||
* **[UltraStar Deluxe](https://usdx.eu/)** – Offenes Karaoke-Format und Spiel.
|
||||
|
||||
## License
|
||||
|
||||
Der Quellcode von `unmix` steht unter der [MIT-Lizenz](LICENSE).
|
||||
|
||||
Die verwendeten Drittanbieter-Modelle und Bibliotheken (Demucs, Whisper, CREPE, librosa, Pyphen) unterliegen ihren jeweiligen Lizenzen (MIT, Apache-2.0, BSD, LGPL).
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# Song-Paket Format Spezifikation (v1.0)
|
||||
|
||||
Dieses Dokument definiert das Dateiformat des **Song-Pakets** als verbindliche Schnittstelle zwischen der Analyse-Pipeline (`songsplit`) und nachgelagerten Anwendungen (z. B. der Rust-Gesangstrainer-App und Editoren).
|
||||
Dieses Dokument definiert das Dateiformat des **Song-Pakets** als verbindliche Schnittstelle zwischen der Analyse-Pipeline (`unmix`) und nachgelagerten Anwendungen (z. B. der Rust-Gesangstrainer-App und Editoren).
|
||||
|
||||
---
|
||||
|
||||
@ -270,8 +270,9 @@ Anschlagereignisse und Rhythmusmuster für Begleitinstrumente.
|
||||
---
|
||||
|
||||
### 3.6 `song.txt` (UltraStar Deluxe)
|
||||
Exportformat für Karaoke-Software:
|
||||
- Header: `#TITLE`, `#ARTIST`, `#MP3`, `#BPM` ($4 \times$ Viertelnoten-BPM), `#GAP` (Offset in ms), `#LANGUAGE`.
|
||||
Exportformat für Karaoke-Software (UltraStar Deluxe / USDX):
|
||||
- Header: `#TITLE`, `#ARTIST`, `#MP3` (Audiodatei), `#BPM` (Viertelnoten-BPM), `#GAP` (Audio-Offset in Millisekunden vor Beat 0), `#LANGUAGE`.
|
||||
- Zeitachse: 1 Beat entspricht $\frac{15}{\text{BPM}}$ Sekunden (4 Ticks pro Viertelnote: $t = \frac{\text{GAP}}{1000} + \text{Beat} \times \frac{15}{\text{BPM}}$).
|
||||
- Notenzeilen: `: <start_beat> <duration> <pitch_rel_c4> <text>`
|
||||
- Pausen/Umbruch: `- <beat>`
|
||||
- Ende: `E`
|
||||
|
||||
@ -3,9 +3,9 @@
|
||||
"schema_version": "1.0",
|
||||
"id": "88fa27d4-d39f-4eae-8b15-14585248a1c9",
|
||||
"created": "2026-11-02T11:16:09.795264+00:00",
|
||||
"modified": "2026-11-02T11:21:17.734955+00:00",
|
||||
"modified": "2026-11-02T13:41:47.130704+00:00",
|
||||
"generator": {
|
||||
"name": "songsplit",
|
||||
"name": "unmix",
|
||||
"version": "0.1.0"
|
||||
},
|
||||
"variant": "full",
|
||||
@ -108,14 +108,6 @@
|
||||
"size": 529244,
|
||||
"stem": "vocals"
|
||||
},
|
||||
{
|
||||
"path": "tracks/guitar.json",
|
||||
"role": "track",
|
||||
"schema_version": "1.0",
|
||||
"sha256": "64f072e2bb2d17cca3ea18798d3c9448089f204e3ef40b04fab1ab8203b1eeea",
|
||||
"size": 1091,
|
||||
"stem": null
|
||||
},
|
||||
{
|
||||
"path": "export/song.txt",
|
||||
"role": "ultrastar",
|
||||
@ -123,6 +115,14 @@
|
||||
"sha256": "1989999030e4d14bd7feee99899cf0eedc7efd0b2dcd0edbefb529e664230dc4",
|
||||
"size": 152,
|
||||
"stem": null
|
||||
},
|
||||
{
|
||||
"path": "tracks/guitar.json",
|
||||
"role": "track",
|
||||
"schema_version": "1.0",
|
||||
"sha256": "64f072e2bb2d17cca3ea18798d3c9448089f204e3ef40b04fab1ab8203b1eeea",
|
||||
"size": 1091,
|
||||
"stem": null
|
||||
}
|
||||
],
|
||||
"stages": {}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
[project]
|
||||
name = "songsplit"
|
||||
name = "unmix"
|
||||
version = "0.1.0"
|
||||
description = "Song-Paket Audioanalyse-Pipeline (Stems, Lyrics, Vocals, Tempo, Chords, Strumming)"
|
||||
readme = "README.md"
|
||||
@ -16,6 +16,7 @@ dependencies = [
|
||||
"pyphen>=0.14.0",
|
||||
"torchcrepe>=0.0.23",
|
||||
"faster-whisper>=1.0.0",
|
||||
"av==18.1.0",
|
||||
"scipy>=1.12.0",
|
||||
"jiwer>=3.0.0",
|
||||
"beat-this>=1.1.0",
|
||||
@ -30,14 +31,15 @@ dev = [
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
songsplit = "songsplit.cli:app"
|
||||
unmix = "unmix.cli:app"
|
||||
songsplit = "unmix.cli:app"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/songsplit"]
|
||||
packages = ["src/unmix"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
||||
@ -53,7 +53,7 @@ Der Ordner `.cache/` (Zwischenergebnisse der Pipeline) gehört nicht zum Songpac
|
||||
"id": "5f0c9b0e-3c1e-4a56-9b8c-1d7f6c2a9a10",
|
||||
"created": "2026-11-02T11:40:00+01:00",
|
||||
"modified": "2026-11-02T11:55:12+01:00",
|
||||
"generator": {"name": "songsplit", "version": "0.1.0"},
|
||||
"generator": {"name": "unmix", "version": "0.1.0"},
|
||||
"variant": "full",
|
||||
"audio_included": true,
|
||||
"license": null,
|
||||
@ -369,7 +369,7 @@ Fehler verhindern das Laden, Warnungen werden in der Oberfläche angezeigt.
|
||||
## 14. Versionierung
|
||||
|
||||
- Minor-Erhöhung = nur neue optionale Felder. Alte Leser funktionieren weiter.
|
||||
- Major-Erhöhung = inkompatible Änderung. Das Analyse-Tool bietet `songsplit migrate` für ältere Songpacks an.
|
||||
- Major-Erhöhung = inkompatible Änderung. Das Analyse-Tool bietet `unmix migrate` für ältere Songpacks an.
|
||||
- Die Schema-Version steht pro Datei, damit sich Dateien unabhängig weiterentwickeln können.
|
||||
|
||||
## 15. Offene Punkte
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
"""songsplit: Audio analysis pipeline for song package decomposition."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@ -1,198 +0,0 @@
|
||||
"""CLI interface for songsplit."""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from songsplit import __version__
|
||||
from songsplit.config import config
|
||||
from songsplit.pipeline import PipelineContext, get_default_pipeline
|
||||
|
||||
app = typer.Typer(
|
||||
name="songsplit",
|
||||
help="Audio analysis pipeline decomposing songs into song packages.",
|
||||
add_completion=False,
|
||||
)
|
||||
console = Console(stderr=True)
|
||||
|
||||
|
||||
@app.command()
|
||||
def analyze(
|
||||
file: Path = typer.Argument(..., help="Path to input audio or video file", exists=True, readable=True),
|
||||
output_dir: Path = typer.Option(..., "-o", "--output", help="Output song package directory"),
|
||||
lang: str = typer.Option("de", "--lang", help="Lyrics language (e.g. 'de', 'en')"),
|
||||
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')"),
|
||||
stage: str | None = typer.Option(None, "--stage", help="Run only a specific stage and its missing dependencies"),
|
||||
force: bool = typer.Option(False, "--force", help="Force recalculation ignoring cached results"),
|
||||
json_output: bool = typer.Option(False, "--json", help="Output machine-readable JSON result path"),
|
||||
) -> None:
|
||||
"""Analyze an audio or video file and produce a Song-Paket."""
|
||||
ctx = PipelineContext(
|
||||
source_file=file,
|
||||
output_dir=output_dir,
|
||||
lang=lang,
|
||||
stems=stems,
|
||||
quality=quality,
|
||||
force=force,
|
||||
target_stage=stage,
|
||||
)
|
||||
runner = get_default_pipeline()
|
||||
meta = runner.run(ctx)
|
||||
|
||||
if json_output:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"output_dir": str(output_dir.resolve()),
|
||||
"stages_done": meta.stages_done,
|
||||
"stages_failed": meta.stages_failed,
|
||||
}
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(str(output_dir.resolve()))
|
||||
|
||||
|
||||
@app.command(name="export-ultrastar")
|
||||
def export_ultrastar_cmd(
|
||||
song_dir: Path = typer.Argument(..., help="Song-Paket directory to export", exists=True),
|
||||
) -> None:
|
||||
"""Export an existing Song-Paket directory to UltraStar song.txt."""
|
||||
from songsplit.export.ultrastar import export_ultrastar
|
||||
|
||||
res = export_ultrastar(song_dir)
|
||||
print(str(res))
|
||||
|
||||
|
||||
@app.command(name="eval")
|
||||
def eval_cmd(
|
||||
testset_config: Path = typer.Argument(..., help="Path to testset.toml", exists=True),
|
||||
) -> None:
|
||||
"""Run quality benchmarks against UltraStar ground-truth references."""
|
||||
from songsplit.eval.run_eval import run_evaluation
|
||||
|
||||
run_evaluation(testset_config)
|
||||
|
||||
|
||||
@app.command(name="pack")
|
||||
def pack_cmd(
|
||||
song_dir: Path = typer.Argument(..., help="Songpack directory to pack", exists=True),
|
||||
output: Path | None = typer.Option(None, "-o", "--output", help="Output .songpack file path"),
|
||||
variant: str = typer.Option(
|
||||
"full", "--variant", help="Package variant: 'full' (with stems) or 'data' (without stems)"
|
||||
),
|
||||
) -> None:
|
||||
"""Pack a songpack directory into a .songpack archive."""
|
||||
from songsplit.container import pack_songpack
|
||||
|
||||
res = pack_songpack(song_dir, output_path=output, variant=variant) # type: ignore[arg-type]
|
||||
print(str(res))
|
||||
|
||||
|
||||
@app.command(name="unpack")
|
||||
def unpack_cmd(
|
||||
songpack_file: Path = typer.Argument(..., help="Path to .songpack archive", exists=True),
|
||||
output_dir: Path | None = typer.Option(None, "-o", "--output", help="Destination folder for unpacked songpack"),
|
||||
) -> None:
|
||||
"""Securely unpack a .songpack archive into a song directory."""
|
||||
from songsplit.container import unpack_songpack
|
||||
|
||||
dest = output_dir or songpack_file.with_suffix("")
|
||||
res = unpack_songpack(songpack_file, dest)
|
||||
print(str(res))
|
||||
|
||||
|
||||
@app.command()
|
||||
def doctor() -> None:
|
||||
"""Check environment, ffmpeg installation, GPUs, and PyTorch availability."""
|
||||
table = Table(title=f"songsplit v{__version__} Doctor System Check")
|
||||
table.add_column("Component", style="cyan", no_wrap=True)
|
||||
table.add_column("Status", style="bold")
|
||||
table.add_column("Details", style="white")
|
||||
|
||||
# 1. Python version
|
||||
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
|
||||
if sys.version_info.major == 3 and 11 <= sys.version_info.minor <= 12:
|
||||
table.add_row("Python", "[green]OK[/green]", f"{py_ver} ({sys.executable})")
|
||||
else:
|
||||
table.add_row("Python", "[yellow]WARN[/yellow]", f"{py_ver} (Empfohlen: Python 3.11 / 3.12)")
|
||||
|
||||
# 2. ffmpeg
|
||||
ffmpeg_path = shutil.which("ffmpeg")
|
||||
if ffmpeg_path:
|
||||
try:
|
||||
res = subprocess.run([ffmpeg_path, "-version"], capture_output=True, text=True, check=True)
|
||||
first_line = res.stdout.splitlines()[0] if res.stdout else "Available"
|
||||
table.add_row("ffmpeg", "[green]OK[/green]", f"{ffmpeg_path} ({first_line})")
|
||||
except Exception as e:
|
||||
table.add_row("ffmpeg", "[yellow]WARN[/yellow]", f"Found at {ffmpeg_path} but error running: {e}")
|
||||
else:
|
||||
table.add_row("ffmpeg", "[red]FAIL[/red]", "ffmpeg not found in PATH")
|
||||
|
||||
# 3. PyTorch
|
||||
try:
|
||||
import torch # type: ignore
|
||||
|
||||
backend_info = []
|
||||
if getattr(torch.version, "cuda", None):
|
||||
backend_info.append(f"CUDA {torch.version.cuda}")
|
||||
if getattr(torch.version, "hip", None):
|
||||
backend_info.append(f"ROCm/HIP {torch.version.hip}")
|
||||
backend_str = ", ".join(backend_info) if backend_info else "CPU-only"
|
||||
|
||||
table.add_row("PyTorch", "[green]OK[/green]", f"v{torch.__version__} ({backend_str})")
|
||||
|
||||
# Check PyTorch visible GPUs
|
||||
if torch.cuda.is_available():
|
||||
count = torch.cuda.device_count()
|
||||
devices_desc = []
|
||||
for i in range(count):
|
||||
devices_desc.append(f"[{i}] {torch.cuda.get_device_name(i)}")
|
||||
table.add_row("Torch GPUs", "[green]OK[/green]", f"{count} device(s): " + "; ".join(devices_desc))
|
||||
else:
|
||||
table.add_row("Torch GPUs", "[yellow]INFO[/yellow]", "No CUDA/ROCm device active in PyTorch")
|
||||
except ImportError:
|
||||
table.add_row("PyTorch", "[yellow]NOT INSTALLED[/yellow]", "PyTorch is not yet installed in virtualenv")
|
||||
|
||||
# 4. System GPUs / Hardware Devices
|
||||
# AMD ROCm / KFD
|
||||
kfd_path = Path("/dev/kfd")
|
||||
if kfd_path.exists():
|
||||
table.add_row(
|
||||
"AMD ROCm (/dev/kfd)", "[green]DETECTED[/green]", f"{kfd_path} present (AMD GPU kernel driver active)"
|
||||
)
|
||||
else:
|
||||
table.add_row("AMD ROCm (/dev/kfd)", "[dim]NONE[/dim]", "No /dev/kfd device found")
|
||||
|
||||
# NVIDIA device nodes
|
||||
nvidia_nodes = list(Path("/dev").glob("nvidia*"))
|
||||
if nvidia_nodes:
|
||||
table.add_row("NVIDIA Devices", "[green]DETECTED[/green]", f"Found: {', '.join(p.name for p in nvidia_nodes)}")
|
||||
else:
|
||||
table.add_row("NVIDIA Devices", "[dim]NONE[/dim]", "No /dev/nvidia* device nodes found")
|
||||
|
||||
# CLI tools
|
||||
rocm_smi = shutil.which("rocm-smi")
|
||||
table.add_row("rocm-smi", "[green]OK[/green]" if rocm_smi else "[dim]NONE[/dim]", rocm_smi or "Not found in PATH")
|
||||
|
||||
nvidia_smi = shutil.which("nvidia-smi")
|
||||
table.add_row(
|
||||
"nvidia-smi", "[green]OK[/green]" if nvidia_smi else "[dim]NONE[/dim]", nvidia_smi or "Not found in PATH"
|
||||
)
|
||||
|
||||
# 5. Model Cache Directory
|
||||
model_dir = config.models_cache_dir
|
||||
table.add_row("Model Cache", "[green]OK[/green]", str(model_dir))
|
||||
|
||||
console.print(table)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app()
|
||||
@ -1,43 +0,0 @@
|
||||
"""Configuration management for songsplit (devices, models, paths)."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class Config(BaseModel):
|
||||
"""Runtime configuration for pipeline stages, devices, and directories."""
|
||||
|
||||
models_cache_dir: Path = Field(
|
||||
default_factory=lambda: Path(
|
||||
os.getenv("SONGSPLIT_MODELS_DIR", Path.home() / ".cache" / "songsplit" / "models")
|
||||
).expanduser()
|
||||
)
|
||||
|
||||
default_device: str = Field(default_factory=lambda: os.getenv("SONGSPLIT_DEFAULT_DEVICE", "cuda:0"))
|
||||
|
||||
stage_devices: dict[str, str] = Field(
|
||||
default_factory=lambda: {
|
||||
"s1_extract": os.getenv("SONGSPLIT_DEVICE_S1", "cpu"),
|
||||
"s2_stems": os.getenv("SONGSPLIT_DEVICE_S2", "cuda:0"),
|
||||
"s3_lyrics": os.getenv("SONGSPLIT_DEVICE_S3", "cuda:0"),
|
||||
"s4_pitch": os.getenv("SONGSPLIT_DEVICE_S4", "cuda:0"),
|
||||
"s5_tempo": os.getenv("SONGSPLIT_DEVICE_S5", "cpu"),
|
||||
"s6_chords": os.getenv("SONGSPLIT_DEVICE_S6", "cpu"),
|
||||
"s7_strumming": os.getenv("SONGSPLIT_DEVICE_S7", "cpu"),
|
||||
}
|
||||
)
|
||||
|
||||
def get_device(self, stage: str) -> str:
|
||||
"""Get target compute device for a specific stage."""
|
||||
return self.stage_devices.get(stage, self.default_device)
|
||||
|
||||
def get_models_dir(self) -> Path:
|
||||
"""Ensure and return the model cache directory."""
|
||||
self.models_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
return self.models_cache_dir
|
||||
|
||||
|
||||
# Global singleton instance
|
||||
config = Config()
|
||||
@ -1,6 +0,0 @@
|
||||
"""Evaluation package."""
|
||||
|
||||
from songsplit.eval.metrics import evaluate_vocals, normalize_text_for_wer
|
||||
from songsplit.eval.run_eval import run_evaluation
|
||||
|
||||
__all__ = ["evaluate_vocals", "normalize_text_for_wer", "run_evaluation"]
|
||||
@ -1,122 +0,0 @@
|
||||
"""Quality metrics comparing predicted vocals against UltraStar reference ground-truth."""
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import jiwer
|
||||
import numpy as np
|
||||
|
||||
from songsplit.export.ultrastar import UltraStarSong
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def normalize_text_for_wer(text: str) -> str:
|
||||
"""Normalize text: remove punctuation, lowercase, normalize whitespace."""
|
||||
# Remove UltraStar formatting tokens (~, -, etc.) and standard punctuation
|
||||
text = re.sub(r"[^\w\s]", "", text)
|
||||
text = re.sub(r"\s+", " ", text)
|
||||
return text.strip().lower()
|
||||
|
||||
|
||||
def evaluate_vocals(
|
||||
predicted: VocalsDocument,
|
||||
reference: UltraStarSong,
|
||||
max_match_distance_sec: float = 0.5,
|
||||
) -> dict[str, Any]:
|
||||
"""Calculate comprehensive timing, pitch, and WER metrics against UltraStar reference."""
|
||||
# Flatten reference syllables
|
||||
ref_notes = []
|
||||
for line in reference.lines:
|
||||
for note in line:
|
||||
# Skip empty whitespace notes
|
||||
if note.text.strip():
|
||||
ref_notes.append(note)
|
||||
|
||||
# Flatten predicted syllables
|
||||
pred_syllables = []
|
||||
for line in predicted.lines:
|
||||
for syl in line.syllables:
|
||||
if syl.text.strip():
|
||||
pred_syllables.append(syl)
|
||||
|
||||
if not ref_notes or not pred_syllables:
|
||||
return {
|
||||
"num_ref_syllables": len(ref_notes),
|
||||
"num_pred_syllables": len(pred_syllables),
|
||||
"mae_timing_ms": 0.0,
|
||||
"median_timing_ms": 0.0,
|
||||
"fraction_within_100ms": 0.0,
|
||||
"strict_pitch_accuracy": 0.0,
|
||||
"octave_equiv_pitch_accuracy": 0.0,
|
||||
"wer": 1.0 if not pred_syllables and ref_notes else 0.0,
|
||||
}
|
||||
|
||||
# Match each reference syllable to nearest predicted syllable within max_match_distance_sec
|
||||
timing_errors_ms = []
|
||||
strict_pitch_correct = []
|
||||
octave_pitch_correct = []
|
||||
|
||||
matched_pred_indices = set()
|
||||
for ref in ref_notes:
|
||||
best_idx = None
|
||||
best_diff = float("inf")
|
||||
|
||||
for idx, pred in enumerate(pred_syllables):
|
||||
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_syllables[best_idx]
|
||||
timing_errors_ms.append(best_diff * 1000.0)
|
||||
|
||||
# Pitch check
|
||||
pitch_diff = abs(pred.midi - ref.midi)
|
||||
is_strict = pitch_diff <= 0.5
|
||||
strict_pitch_correct.append(1.0 if is_strict else 0.0)
|
||||
|
||||
# Octave equivalent pitch check (mod 12)
|
||||
mod_diff = pitch_diff % 12.0
|
||||
octave_diff = min(mod_diff, 12.0 - mod_diff)
|
||||
is_octave = octave_diff <= 0.5
|
||||
octave_pitch_correct.append(1.0 if is_octave else 0.0)
|
||||
else:
|
||||
# Unmatched reference note -> penalty
|
||||
timing_errors_ms.append(max_match_distance_sec * 1000.0)
|
||||
strict_pitch_correct.append(0.0)
|
||||
octave_pitch_correct.append(0.0)
|
||||
|
||||
# 1. Timing metrics
|
||||
mae_timing_ms = float(np.mean(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||
median_timing_ms = float(np.median(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||
fraction_within_100ms = (
|
||||
float(np.mean([1.0 if err <= 100.0 else 0.0 for err in timing_errors_ms])) if timing_errors_ms else 0.0
|
||||
)
|
||||
|
||||
# 2. Pitch metrics
|
||||
strict_pitch_acc = float(np.mean(strict_pitch_correct)) if strict_pitch_correct else 0.0
|
||||
octave_pitch_acc = float(np.mean(octave_pitch_correct)) if octave_pitch_correct else 0.0
|
||||
|
||||
# 3. WER metric
|
||||
ref_words_raw = "".join(r.text for r in ref_notes)
|
||||
pred_words_raw = "".join(p.text for p in pred_syllables)
|
||||
norm_ref = normalize_text_for_wer(ref_words_raw)
|
||||
norm_pred = normalize_text_for_wer(pred_words_raw)
|
||||
|
||||
if norm_ref:
|
||||
wer_score = float(jiwer.wer(norm_ref, norm_pred))
|
||||
else:
|
||||
wer_score = 0.0 if not norm_pred else 1.0
|
||||
|
||||
return {
|
||||
"num_ref_syllables": len(ref_notes),
|
||||
"num_pred_syllables": len(pred_syllables),
|
||||
"mae_timing_ms": mae_timing_ms,
|
||||
"median_timing_ms": median_timing_ms,
|
||||
"fraction_within_100ms": fraction_within_100ms,
|
||||
"strict_pitch_accuracy": strict_pitch_acc,
|
||||
"octave_equiv_pitch_accuracy": octave_pitch_acc,
|
||||
"wer": wer_score,
|
||||
}
|
||||
@ -1,102 +0,0 @@
|
||||
"""Evaluation runner parsing testset.toml and producing eval_report.md and json."""
|
||||
|
||||
import json
|
||||
import time
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from songsplit.eval.metrics import evaluate_vocals
|
||||
from songsplit.export.ultrastar import parse_ultrastar
|
||||
from songsplit.pipeline import PipelineContext, get_default_pipeline
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def run_evaluation(testset_config: Path, output_report_dir: Path | None = None) -> dict[str, Any]:
|
||||
"""Run evaluation over songs defined in testset.toml."""
|
||||
testset_config = testset_config.resolve()
|
||||
with open(testset_config, "rb") as f:
|
||||
config_data = tomllib.load(f)
|
||||
|
||||
report_dir = output_report_dir or testset_config.parent
|
||||
report_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
songs = config_data.get("songs", [])
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
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")
|
||||
|
||||
song_out_dir = report_dir / "eval_runs" / name
|
||||
ctx = PipelineContext(
|
||||
source_file=audio_path,
|
||||
output_dir=song_out_dir,
|
||||
lang=lang,
|
||||
target_stage="s4_pitch",
|
||||
)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
runner = get_default_pipeline()
|
||||
meta = runner.run(ctx)
|
||||
elapsed_sec = time.perf_counter() - t0
|
||||
|
||||
vocals_json = song_out_dir / "vocals.json"
|
||||
if not vocals_json.exists():
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"status": "failed",
|
||||
"error": "vocals.json not produced",
|
||||
"elapsed_sec": elapsed_sec,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
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"
|
||||
metrics["elapsed_sec"] = elapsed_sec
|
||||
metrics["stages_done"] = meta.stages_done
|
||||
results.append(metrics)
|
||||
|
||||
# Generate Markdown Report
|
||||
md_lines = [
|
||||
"# songsplit Evaluationsbericht (Eval Report)",
|
||||
"",
|
||||
f"Konfiguration: `{testset_config.name}`",
|
||||
f"Getestete Songs: {len(results)}",
|
||||
"",
|
||||
"| Song | Status | Timing MAE (ms) | Timing <= 100ms | Noten (strikt) | Noten (+-Oktav) | WER | Laufzeit (s) |",
|
||||
"|---|---|---|---|---|---|---|---|",
|
||||
]
|
||||
|
||||
for r in results:
|
||||
if r.get("status") == "success":
|
||||
md_lines.append(
|
||||
f"| {r['name']} | OK | {r['mae_timing_ms']:.1f} | "
|
||||
f"{r['fraction_within_100ms'] * 100:.1f}% | {r['strict_pitch_accuracy'] * 100:.1f}% | "
|
||||
f"{r['octave_equiv_pitch_accuracy'] * 100:.1f}% | {r['wer']:.2f} | {r['elapsed_sec']:.1f}s |"
|
||||
)
|
||||
else:
|
||||
md_lines.append(
|
||||
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"
|
||||
report_json_path = report_dir / "eval_report.json"
|
||||
|
||||
with open(report_md_path, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(md_lines) + "\n")
|
||||
|
||||
report_data = {"songs": results, "timestamp": time.time()}
|
||||
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||
json.dump(report_data, f, indent=2)
|
||||
|
||||
return report_data
|
||||
@ -1,271 +0,0 @@
|
||||
"""UltraStar format export (Writer) and import/parsing (Reader).
|
||||
|
||||
Format specifications:
|
||||
- Headers: #TITLE, #ARTIST, #MP3, #BPM, #GAP, #LANGUAGE
|
||||
- Note types:
|
||||
': ' regular note
|
||||
'* ' golden note
|
||||
'F ' freestyle note
|
||||
'- ' line break
|
||||
'E' end of song
|
||||
- Beat resolution in UltraStar: 4 ticks per beat (16th notes).
|
||||
- Pitch in UltraStar: Halftones relative to C4 (MIDI 60).
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from songsplit.schema.meta import MetaDocument
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
from songsplit.tempo import sec_to_beat
|
||||
|
||||
|
||||
def export_ultrastar(song_dir: Path) -> Path:
|
||||
"""Export song package directory to UltraStar song.txt.
|
||||
|
||||
Reads meta.json, vocals.json, and tempo.json if present.
|
||||
"""
|
||||
song_dir = song_dir.resolve()
|
||||
meta_file = song_dir / "meta.json"
|
||||
vocals_file = song_dir / "vocals.json"
|
||||
tempo_file = song_dir / "tempo.json"
|
||||
output_txt = song_dir / "song.txt"
|
||||
|
||||
if not vocals_file.exists():
|
||||
raise FileNotFoundError(f"vocals.json not found in {song_dir}")
|
||||
|
||||
with open(vocals_file, encoding="utf-8") as f:
|
||||
vocals = VocalsDocument.model_validate(json.load(f))
|
||||
|
||||
meta = None
|
||||
if meta_file.exists():
|
||||
with open(meta_file, encoding="utf-8") as f:
|
||||
meta = MetaDocument.model_validate(json.load(f))
|
||||
|
||||
tempo = None
|
||||
if tempo_file.exists():
|
||||
with open(tempo_file, encoding="utf-8") as f:
|
||||
tempo = TempoDocument.model_validate(json.load(f))
|
||||
|
||||
title = meta.title if meta and meta.title else song_dir.name
|
||||
artist = meta.artist if meta and meta.artist else "Unknown Artist"
|
||||
language = meta.language if meta and meta.language else "German"
|
||||
|
||||
# Find earliest vocal syllable for GAP
|
||||
first_syllable_sec = 0.0
|
||||
for line in vocals.lines:
|
||||
if line.syllables:
|
||||
first_syllable_sec = line.syllables[0].start
|
||||
break
|
||||
|
||||
# Determine reference BPM
|
||||
if tempo and tempo.anchors:
|
||||
base_bpm = tempo.anchors[0].bpm
|
||||
else:
|
||||
base_bpm = 120.0
|
||||
|
||||
# In UltraStar, #BPM is 4x standard BPM (4 beats per quarter note)
|
||||
ultrastar_bpm = base_bpm * 4.0
|
||||
gap_ms = int(max(0.0, first_syllable_sec) * 1000.0)
|
||||
|
||||
# Audio reference file: vocals.wav if present, else original file
|
||||
mp3_name = "stems/vocals.wav" if (song_dir / "stems" / "vocals.wav").exists() else "extracted.wav"
|
||||
|
||||
out_lines = [
|
||||
f"#TITLE:{title}",
|
||||
f"#ARTIST:{artist}",
|
||||
f"#MP3:{mp3_name}",
|
||||
f"#BPM:{ultrastar_bpm:.2f}",
|
||||
f"#GAP:{gap_ms}",
|
||||
f"#LANGUAGE:{language}",
|
||||
]
|
||||
|
||||
# Pass through additional header fields from meta.ultrastar
|
||||
if meta and hasattr(meta, "ultrastar") and meta.ultrastar:
|
||||
for k, v in meta.ultrastar.items():
|
||||
if k.upper() not in ["TITLE", "ARTIST", "MP3", "BPM", "GAP", "LANGUAGE"]:
|
||||
out_lines.append(f"#{k.upper()}:{v}")
|
||||
|
||||
def sec_to_ultrastar_beat(sec: float) -> int:
|
||||
rel_sec = max(0.0, sec - (gap_ms / 1000.0))
|
||||
if tempo and tempo.anchors:
|
||||
quarter_beats = sec_to_beat(rel_sec, tempo)
|
||||
return max(0, int(round(quarter_beats * 4.0)))
|
||||
else:
|
||||
beats_per_sec = base_bpm / 60.0
|
||||
return max(0, int(round(rel_sec * beats_per_sec * 4.0)))
|
||||
|
||||
tag_map = {"normal": ":", "golden": "*", "freestyle": "F", "rap": "R"}
|
||||
|
||||
current_beat = 0
|
||||
for line_idx, line in enumerate(vocals.lines):
|
||||
if not line.syllables:
|
||||
continue
|
||||
|
||||
for syl_idx, syl in enumerate(line.syllables):
|
||||
syl_start_beat = sec_to_ultrastar_beat(syl.start)
|
||||
syl_end_beat = sec_to_ultrastar_beat(syl.end)
|
||||
duration_beats = max(1, syl_end_beat - syl_start_beat)
|
||||
|
||||
# Prevent overlap with previous syllable in same line
|
||||
if syl_start_beat < current_beat:
|
||||
syl_start_beat = current_beat
|
||||
|
||||
current_beat = syl_start_beat + duration_beats
|
||||
|
||||
# UltraStar pitch relative to C4 (MIDI 60)
|
||||
midi_val = syl.midi if syl.midi is not None else 60.0
|
||||
pitch = int(round(midi_val - 60.0))
|
||||
tag = tag_map.get(getattr(syl, "type", "normal"), "*" if getattr(syl, "golden", False) else ":")
|
||||
|
||||
# Preserve trailing space or text (don't add trailing space to the last syllable of a line)
|
||||
txt = syl.text
|
||||
is_last_in_line = syl_idx == len(line.syllables) - 1
|
||||
if getattr(syl, "word_end", False) and not txt.endswith(" ") and not is_last_in_line:
|
||||
txt += " "
|
||||
out_lines.append(f"{tag} {syl_start_beat} {duration_beats} {pitch} {txt}")
|
||||
|
||||
# Add line break if not the last line
|
||||
if line_idx < len(vocals.lines) - 1:
|
||||
line_break_beat = current_beat + 2
|
||||
out_lines.append(f"- {line_break_beat}")
|
||||
current_beat = line_break_beat + 1
|
||||
|
||||
out_lines.append("E")
|
||||
out_lines.append("")
|
||||
|
||||
content_str = "\n".join(out_lines)
|
||||
|
||||
# Save to export/song.txt per Songpack specification v1.0
|
||||
export_dir = song_dir / "export"
|
||||
export_dir.mkdir(parents=True, exist_ok=True)
|
||||
export_txt = export_dir / "song.txt"
|
||||
with open(export_txt, "w", encoding="utf-8") as f:
|
||||
f.write(content_str)
|
||||
|
||||
# Also save to root song.txt for backward compatibility
|
||||
with open(output_txt, "w", encoding="utf-8") as f:
|
||||
f.write(content_str)
|
||||
|
||||
return export_txt
|
||||
|
||||
|
||||
class UltraStarNote:
|
||||
"""A parsed note from an UltraStar file."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
note_type: str,
|
||||
start_beat: int,
|
||||
duration: int,
|
||||
pitch: int,
|
||||
text: str,
|
||||
start_sec: float = 0.0,
|
||||
end_sec: float = 0.0,
|
||||
midi: float = 60.0,
|
||||
):
|
||||
self.note_type = note_type
|
||||
self.start_beat = start_beat
|
||||
self.duration = duration
|
||||
self.pitch = pitch
|
||||
self.text = text
|
||||
self.start_sec = start_sec
|
||||
self.end_sec = end_sec
|
||||
self.midi = midi
|
||||
|
||||
|
||||
class UltraStarSong:
|
||||
"""A complete parsed UltraStar song structure."""
|
||||
|
||||
def __init__(self, headers: dict[str, str], lines: list[list[UltraStarNote]]):
|
||||
self.headers = headers
|
||||
self.lines = lines
|
||||
|
||||
@property
|
||||
def title(self) -> str:
|
||||
return self.headers.get("TITLE", "")
|
||||
|
||||
@property
|
||||
def artist(self) -> str:
|
||||
return self.headers.get("ARTIST", "")
|
||||
|
||||
@property
|
||||
def bpm(self) -> float:
|
||||
# Standard quarter-note BPM
|
||||
return float(self.headers.get("BPM", "480").replace(",", ".")) / 4.0
|
||||
|
||||
@property
|
||||
def gap_ms(self) -> float:
|
||||
return float(self.headers.get("GAP", "0").replace(",", "."))
|
||||
|
||||
|
||||
def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
||||
"""Parse an UltraStar .txt file into structured notes and absolute times in seconds."""
|
||||
headers: dict[str, str] = {}
|
||||
lines: list[list[UltraStarNote]] = []
|
||||
current_line: list[UltraStarNote] = []
|
||||
|
||||
with open(file_path, encoding="utf-8", errors="replace") as f:
|
||||
content = f.read()
|
||||
|
||||
raw_lines = content.splitlines()
|
||||
|
||||
for raw in raw_lines:
|
||||
line = raw.rstrip("\r\n")
|
||||
if not line or not line.strip():
|
||||
continue
|
||||
|
||||
if line.startswith("#"):
|
||||
# Header line: #KEY:VALUE
|
||||
match = re.match(r"^#([A-Za-z0-9_-]+):(.*)$", line.strip())
|
||||
if match:
|
||||
k, v = match.group(1).upper(), match.group(2).strip()
|
||||
headers[k] = v
|
||||
continue
|
||||
|
||||
if line.startswith("E"):
|
||||
# End of song
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
current_line = []
|
||||
break
|
||||
|
||||
if line.startswith("-"):
|
||||
# Line break
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
current_line = []
|
||||
continue
|
||||
|
||||
# Note line: : 10 4 2 text
|
||||
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line)
|
||||
if match:
|
||||
ntype, s_beat, dur, pitch, text = match.groups()
|
||||
note = UltraStarNote(
|
||||
note_type=ntype,
|
||||
start_beat=int(s_beat),
|
||||
duration=int(dur),
|
||||
pitch=int(pitch),
|
||||
text=text,
|
||||
)
|
||||
current_line.append(note)
|
||||
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
|
||||
# Calculate absolute timings in seconds for each note
|
||||
raw_bpm = float(headers.get("BPM", "480").replace(",", "."))
|
||||
gap_sec = float(headers.get("GAP", "0").replace(",", ".")) / 1000.0
|
||||
|
||||
# UltraStar tick duration in seconds = 60.0 / BPM
|
||||
sec_per_tick = 60.0 / raw_bpm if raw_bpm > 0 else 0.125
|
||||
|
||||
for line_notes in lines:
|
||||
for note in line_notes:
|
||||
note.start_sec = gap_sec + (note.start_beat * sec_per_tick)
|
||||
note.end_sec = note.start_sec + (note.duration * sec_per_tick)
|
||||
note.midi = float(note.pitch + 60)
|
||||
|
||||
return UltraStarSong(headers=headers, lines=lines)
|
||||
@ -1,187 +0,0 @@
|
||||
"""Stage 3: Lyrics transcription & alignment (Whisper + pyphen hyphenation)."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pyphen
|
||||
|
||||
from songsplit.config import config
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
|
||||
|
||||
def hyphenate_word(word_text: str, dic: pyphen.Pyphen) -> list[str]:
|
||||
"""Split a word into syllables using pyphen while preserving punctuation and spacing."""
|
||||
stripped = word_text.strip()
|
||||
if not stripped:
|
||||
return [word_text]
|
||||
|
||||
# Separate leading/trailing punctuation from core word
|
||||
match = re.match(r"^(\W*)([\w\-]+)(\W*)$", stripped)
|
||||
if not match:
|
||||
return [word_text]
|
||||
|
||||
prefix, core, suffix = match.groups()
|
||||
|
||||
# Hyphenate core word
|
||||
hyphenated = dic.inserted(core)
|
||||
parts = hyphenated.split("-") if "-" in hyphenated else [core]
|
||||
|
||||
if len(parts) == 1:
|
||||
return [word_text]
|
||||
|
||||
# Attach prefix to first syllable, suffix (and trailing space if original had one) to last
|
||||
has_trailing_space = word_text.endswith(" ")
|
||||
res = []
|
||||
for i, p in enumerate(parts):
|
||||
s = p
|
||||
if i == 0 and prefix:
|
||||
s = prefix + s
|
||||
if i == len(parts) - 1:
|
||||
if suffix:
|
||||
s = s + suffix
|
||||
if has_trailing_space:
|
||||
s = s + " "
|
||||
res.append(s)
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def split_word_into_syllables_timed(
|
||||
word_text: str, start: float, end: float, dic: pyphen.Pyphen
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Hyphenate word and distribute duration proportionally to syllable length."""
|
||||
syllables = hyphenate_word(word_text, dic)
|
||||
duration = max(0.01, end - start)
|
||||
|
||||
if len(syllables) == 1:
|
||||
return [{"text": syllables[0], "start": start, "end": end, "word_end": True}]
|
||||
|
||||
total_chars = sum(max(1, len(s.strip())) for s in syllables)
|
||||
timed = []
|
||||
cur_t = start
|
||||
|
||||
for i, syl in enumerate(syllables):
|
||||
char_len = max(1, len(syl.strip()))
|
||||
is_last = i == len(syllables) - 1
|
||||
if is_last:
|
||||
syl_end = end
|
||||
else:
|
||||
syl_dur = duration * (char_len / total_chars)
|
||||
syl_end = cur_t + syl_dur
|
||||
|
||||
timed.append(
|
||||
{
|
||||
"text": syl,
|
||||
"start": cur_t,
|
||||
"end": syl_end,
|
||||
"word_end": is_last,
|
||||
}
|
||||
)
|
||||
cur_t = syl_end
|
||||
|
||||
return timed
|
||||
|
||||
|
||||
class LyricsStage(Stage):
|
||||
"""Stage 3 transcribes vocals into word-aligned syllables using Whisper and pyphen."""
|
||||
|
||||
name = "s3_lyrics"
|
||||
version = "1.0.0"
|
||||
model_name = "whisper-large-v3"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s2_stems"]
|
||||
|
||||
def __init__(self, model_name: str = "whisper-large-v3"):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.stems_dir / "vocals.wav"]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.cache_dir / "lyrics_raw.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {
|
||||
"lang": ctx.lang or "de",
|
||||
"model_size": "base" if ctx.quality == "fast" else "large-v3",
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
vocals_wav = self.get_inputs(ctx)[0]
|
||||
if not vocals_wav.exists():
|
||||
raise FileNotFoundError(f"Vocals stem not found: {vocals_wav}")
|
||||
|
||||
params = self.get_params(ctx)
|
||||
lang = params["lang"]
|
||||
model_size = params["model_size"]
|
||||
self.model_name = f"whisper-{model_size}"
|
||||
|
||||
# Setup pyphen dictionary
|
||||
pyphen_lang = "de_DE" if lang.lower().startswith("de") else "en_US"
|
||||
try:
|
||||
dic = pyphen.Pyphen(lang=pyphen_lang)
|
||||
except Exception:
|
||||
dic = pyphen.Pyphen(lang="en_US")
|
||||
|
||||
# Determine compute device
|
||||
device_str = config.get_device(self.name)
|
||||
compute_type = "float16" if device_str.startswith("cuda") else "int8"
|
||||
device = "cuda" if device_str.startswith("cuda") else "cpu"
|
||||
|
||||
models_dir = config.get_models_dir()
|
||||
model = WhisperModel(
|
||||
model_size,
|
||||
device=device,
|
||||
compute_type=compute_type,
|
||||
download_root=str(models_dir),
|
||||
)
|
||||
|
||||
segments, info = model.transcribe(
|
||||
str(vocals_wav),
|
||||
language=lang,
|
||||
word_timestamps=True,
|
||||
vad_filter=True,
|
||||
)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
|
||||
for seg in segments:
|
||||
seg_syllables: list[dict[str, Any]] = []
|
||||
if seg.words:
|
||||
for idx, w in enumerate(seg.words):
|
||||
# Attach space to word text if not the last word in segment
|
||||
w_text = w.word.strip()
|
||||
if idx < len(seg.words) - 1:
|
||||
w_text += " "
|
||||
|
||||
w_sylls = split_word_into_syllables_timed(w_text, w.start, w.end, dic)
|
||||
seg_syllables.extend(w_sylls)
|
||||
else:
|
||||
# Segment without word timestamps fallback
|
||||
w_sylls = split_word_into_syllables_timed(seg.text.strip(), seg.start, seg.end, dic)
|
||||
seg_syllables.extend(w_sylls)
|
||||
|
||||
if seg_syllables:
|
||||
lines.append(
|
||||
{
|
||||
"start": seg.start,
|
||||
"end": seg.end,
|
||||
"text": seg.text.strip(),
|
||||
"syllables": seg_syllables,
|
||||
}
|
||||
)
|
||||
|
||||
output_data = {
|
||||
"language": lang,
|
||||
"detected_language": info.language if hasattr(info, "language") else lang,
|
||||
"lines": lines,
|
||||
}
|
||||
|
||||
output_file = self.get_outputs(ctx)[0]
|
||||
output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
json.dump(output_data, f, indent=2, ensure_ascii=False)
|
||||
@ -1,260 +0,0 @@
|
||||
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
|
||||
from songsplit.config import config
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
from songsplit.schema.base import GeneratedBy
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def hz_to_midi(hz: np.ndarray) -> np.ndarray:
|
||||
"""Convert frequency in Hz to fractional MIDI note numbers."""
|
||||
valid = hz > 0
|
||||
midi = np.zeros_like(hz, dtype=np.float32)
|
||||
midi[valid] = 69.0 + 12.0 * np.log2(hz[valid] / 440.0)
|
||||
return midi
|
||||
|
||||
|
||||
def correct_octave_errors(syllables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Correct isolated octave doubling/halving jumps relative to melodic context."""
|
||||
if len(syllables) < 3:
|
||||
return syllables
|
||||
|
||||
pitches = [s["midi"] for s in syllables]
|
||||
corrected = list(pitches)
|
||||
|
||||
for i in range(1, len(syllables) - 1):
|
||||
prev_p = corrected[i - 1]
|
||||
next_p = pitches[i + 1]
|
||||
cur_p = pitches[i]
|
||||
|
||||
local_mean = (prev_p + next_p) / 2.0
|
||||
diff = cur_p - local_mean
|
||||
|
||||
# Check for +12 (octave too high)
|
||||
if 10.5 <= diff <= 13.5:
|
||||
corrected[i] = cur_p - 12.0
|
||||
# Check for -12 (octave too low)
|
||||
elif -13.5 <= diff <= -10.5:
|
||||
corrected[i] = cur_p + 12.0
|
||||
# Check for +24 (two octaves too high)
|
||||
elif 22.5 <= diff <= 25.5:
|
||||
corrected[i] = cur_p - 24.0
|
||||
# Check for -24 (two octaves too low)
|
||||
elif -25.5 <= diff <= -22.5:
|
||||
corrected[i] = cur_p + 24.0
|
||||
|
||||
for s, p in zip(syllables, corrected, strict=False):
|
||||
s["midi"] = float(p)
|
||||
|
||||
return syllables
|
||||
|
||||
|
||||
class PitchStage(Stage):
|
||||
"""Stage 4 extracts vocal fundamental frequency and assigns median pitch per syllable."""
|
||||
|
||||
name = "s4_pitch"
|
||||
version = "1.0.0"
|
||||
model_name = "torchcrepe-full"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s3_lyrics"]
|
||||
|
||||
def __init__(self, model_name: str = "torchcrepe-full"):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [
|
||||
ctx.stems_dir / "vocals.wav",
|
||||
ctx.cache_dir / "lyrics_raw.json",
|
||||
]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.output_dir / "vocals.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {
|
||||
"hop_length_ms": 10,
|
||||
"voicing_threshold": 0.25,
|
||||
"crepe_model": "tiny" if ctx.quality == "fast" else "full",
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
import torchcrepe
|
||||
|
||||
vocals_wav, lyrics_json = self.get_inputs(ctx)
|
||||
if not vocals_wav.exists():
|
||||
raise FileNotFoundError(f"Vocals stem not found: {vocals_wav}")
|
||||
if not lyrics_json.exists():
|
||||
raise FileNotFoundError(f"Lyrics file not found: {lyrics_json}")
|
||||
|
||||
with open(lyrics_json, encoding="utf-8") as f:
|
||||
lyrics_data = json.load(f)
|
||||
|
||||
params = self.get_params(ctx)
|
||||
hop_length_ms = params["hop_length_ms"]
|
||||
voicing_thresh = params["voicing_threshold"]
|
||||
crepe_model = params["crepe_model"]
|
||||
self.model_name = f"torchcrepe-{crepe_model}"
|
||||
|
||||
# Load audio using soundfile (resample to 16000 Hz for CREPE)
|
||||
audio_data, sr = sf.read(str(vocals_wav), dtype="float32")
|
||||
if audio_data.ndim > 1:
|
||||
# Downmix to mono
|
||||
audio_data = audio_data.mean(axis=-1)
|
||||
|
||||
crepe_sr = 16000
|
||||
hop_length = int(crepe_sr * (hop_length_ms / 1000.0))
|
||||
|
||||
# Convert to torch tensor
|
||||
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)
|
||||
|
||||
# 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,
|
||||
)
|
||||
|
||||
pitch_hz = pitch_hz.squeeze(0).cpu().numpy()
|
||||
periodicity = periodicity.squeeze(0).cpu().numpy()
|
||||
|
||||
# Frame timestamps: t_k = k * (hop_length / crepe_sr)
|
||||
frame_times = np.arange(len(pitch_hz)) * (hop_length / crepe_sr)
|
||||
midi_frames = hz_to_midi(pitch_hz)
|
||||
|
||||
# Process each line and syllable
|
||||
vocal_lines: list[VocalLine] = []
|
||||
line_counter = 0
|
||||
syl_counter = 0
|
||||
|
||||
for line_dict in lyrics_data.get("lines", []):
|
||||
line_counter += 1
|
||||
line_syllables_raw = []
|
||||
|
||||
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)
|
||||
|
||||
# Frames within syllable
|
||||
mask = (frame_times >= s_start) & (frame_times <= s_end)
|
||||
voiced_mask = mask & (periodicity >= voicing_thresh) & (pitch_hz > 50)
|
||||
|
||||
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,
|
||||
}
|
||||
)
|
||||
|
||||
# Apply octave error correction within phrase
|
||||
corrected_sylls = correct_octave_errors(line_syllables_raw)
|
||||
|
||||
syl_objects = []
|
||||
for s in corrected_sylls:
|
||||
syl_counter += 1
|
||||
raw_text = s["text"]
|
||||
has_space = raw_text.endswith(" ")
|
||||
clean_text = raw_text.rstrip()
|
||||
is_word_end = s.get("word_end", has_space)
|
||||
syl_objects.append(
|
||||
VocalSyllable(
|
||||
id=f"s_{syl_counter:04d}",
|
||||
text=clean_text,
|
||||
start=s["start"],
|
||||
end=s["end"],
|
||||
midi=s["midi"],
|
||||
confidence=s["confidence"],
|
||||
word_end=is_word_end,
|
||||
source="auto",
|
||||
)
|
||||
)
|
||||
|
||||
if syl_objects:
|
||||
vocal_lines.append(
|
||||
VocalLine(
|
||||
id=f"l_{line_counter:04d}",
|
||||
voice=0,
|
||||
start=line_dict["start"],
|
||||
end=line_dict["end"],
|
||||
syllables=syl_objects,
|
||||
)
|
||||
)
|
||||
|
||||
doc = VocalsDocument(
|
||||
schema_version="1.0",
|
||||
generated_by=GeneratedBy(
|
||||
stage=self.name,
|
||||
model=self.model_name,
|
||||
model_version=self.version,
|
||||
params=params,
|
||||
),
|
||||
lines=vocal_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:
|
||||
f.write(doc.model_dump_json(indent=2))
|
||||
|
||||
# Write optional vocals_f0.json per Section 6
|
||||
try:
|
||||
from songsplit.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)
|
||||
]
|
||||
f0_conf = [round(float(p), 2) for p in periodicity]
|
||||
f0_doc = VocalsF0Document(
|
||||
schema_version="1.0",
|
||||
hop_sec=round(hop_sec, 4),
|
||||
start_sec=0.0,
|
||||
hz=f0_hz,
|
||||
confidence=f0_conf,
|
||||
)
|
||||
f0_path = ctx.output_dir / "vocals_f0.json"
|
||||
with open(f0_path, "w", encoding="utf-8") as f:
|
||||
f.write(f0_doc.model_dump_json())
|
||||
except Exception:
|
||||
pass
|
||||
3
src/unmix/__init__.py
Normal file
3
src/unmix/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""unmix: Audio analysis pipeline for song package decomposition."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
460
src/unmix/cli.py
Normal file
460
src/unmix/cli.py
Normal file
@ -0,0 +1,460 @@
|
||||
"""CLI interface for unmix."""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from unmix import __version__
|
||||
from unmix.config import config
|
||||
from unmix.pipeline import PipelineContext, get_default_pipeline
|
||||
from unmix.sources import download_url_audio, is_url
|
||||
|
||||
app = typer.Typer(
|
||||
name="unmix",
|
||||
help="Audio analysis pipeline decomposing songs into song packages.",
|
||||
add_completion=False,
|
||||
)
|
||||
console = Console(stderr=True)
|
||||
|
||||
|
||||
def version_callback(value: bool) -> None:
|
||||
if value:
|
||||
print(f"unmix v{__version__}")
|
||||
raise typer.Exit()
|
||||
|
||||
|
||||
@app.callback()
|
||||
def main(
|
||||
version: bool | None = typer.Option(
|
||||
None,
|
||||
"--version",
|
||||
"-v",
|
||||
help="Show version and exit.",
|
||||
callback=version_callback,
|
||||
is_eager=True,
|
||||
),
|
||||
) -> None:
|
||||
"""Audio analysis pipeline decomposing songs into song packages."""
|
||||
|
||||
|
||||
@app.command()
|
||||
def analyze(
|
||||
file: str = typer.Argument(..., help="Path to input audio/video file or YouTube URL"),
|
||||
output_dir: Path = typer.Option(..., "-o", "--output", help="Output song package directory"),
|
||||
lang: str = typer.Option("de", "--lang", help="Lyrics language (e.g. 'de', 'en')"),
|
||||
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')"),
|
||||
stage: str | None = typer.Option(None, "--stage", help="Run only a specific stage and its missing dependencies"),
|
||||
force: bool = typer.Option(False, "--force", help="Force recalculation ignoring cached results"),
|
||||
json_output: bool = typer.Option(False, "--json", help="Output machine-readable JSON result path"),
|
||||
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"),
|
||||
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/"
|
||||
),
|
||||
) -> None:
|
||||
"""Analyze an audio or video file or YouTube URL and produce a Song-Paket."""
|
||||
temp_dir_obj = None
|
||||
input_title = title
|
||||
input_artist = artist
|
||||
|
||||
if is_url(file):
|
||||
console.print(f"[cyan][INFO][/cyan] Detected URL source: {file}")
|
||||
console.print("[cyan][INFO][/cyan] Downloading audio stream via yt-dlp...")
|
||||
temp_dir_obj = tempfile.TemporaryDirectory(prefix="unmix_yt_")
|
||||
temp_dir = Path(temp_dir_obj.name)
|
||||
source_path, url_meta = download_url_audio(file, temp_dir)
|
||||
console.print(f"[green][OK][/green] Downloaded audio: {source_path.name}")
|
||||
if not input_title and url_meta.get("title"):
|
||||
input_title = url_meta["title"]
|
||||
if not input_artist and url_meta.get("artist"):
|
||||
input_artist = url_meta["artist"]
|
||||
else:
|
||||
source_path = Path(file).resolve()
|
||||
if not source_path.exists():
|
||||
console.print(f"[red][ERROR][/red] Input file not found: {source_path}")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
ctx = PipelineContext(
|
||||
source_file=source_path,
|
||||
output_dir=output_dir,
|
||||
lang=lang,
|
||||
stems=stems,
|
||||
quality=quality,
|
||||
force=force,
|
||||
target_stage=stage,
|
||||
)
|
||||
runner = get_default_pipeline()
|
||||
meta = runner.run(ctx)
|
||||
|
||||
# Persist title/artist overrides if provided
|
||||
updated_meta = False
|
||||
if input_title and not meta.title:
|
||||
meta.title = input_title
|
||||
updated_meta = True
|
||||
if input_artist and not meta.artist:
|
||||
meta.artist = input_artist
|
||||
updated_meta = True
|
||||
if lang and not meta.language:
|
||||
meta.language = lang
|
||||
updated_meta = True
|
||||
if updated_meta:
|
||||
ctx.save_meta(meta)
|
||||
|
||||
# Automatic UltraStar export if vocals were extracted
|
||||
vocals_json = output_dir / "vocals.json"
|
||||
if export_ultrastar_flag and vocals_json.exists():
|
||||
from unmix.export.ultrastar import export_ultrastar
|
||||
|
||||
export_ultrastar(
|
||||
output_dir,
|
||||
title=meta.title,
|
||||
artist=meta.artist,
|
||||
language=meta.language,
|
||||
)
|
||||
|
||||
# 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}")
|
||||
else:
|
||||
from unmix.eval.metrics import generate_training_diff
|
||||
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar, ultrastar_to_vocals
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
|
||||
# 1. AI Vocals evaluation & Training Diff (Track B)
|
||||
training_diff = None
|
||||
if vocals_json.exists():
|
||||
with open(vocals_json, encoding="utf-8") as vf:
|
||||
ai_vocals = VocalsDocument.model_validate(json.load(vf))
|
||||
|
||||
# Preserve AI prediction in .cache
|
||||
cache_ai_vocals = ctx.cache_dir / "vocals_ai.json"
|
||||
cache_ai_vocals.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(cache_ai_vocals, "w", encoding="utf-8") as caf:
|
||||
caf.write(ai_vocals.model_dump_json(indent=2))
|
||||
|
||||
# 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))
|
||||
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 = "ai"
|
||||
|
||||
ctx.save_meta(meta)
|
||||
|
||||
# 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]"
|
||||
)
|
||||
|
||||
|
||||
# Cleanup temporary download directory
|
||||
if temp_dir_obj is not None:
|
||||
try:
|
||||
temp_dir_obj.cleanup()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if meta.stages_failed:
|
||||
failed_list = list(meta.stages_failed.keys())
|
||||
console.print(f"[red][ERROR][/red] Pipeline finished with {len(failed_list)} failed stage(s): {failed_list}")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
if json_output:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"output_dir": str(output_dir.resolve()),
|
||||
"stages_done": meta.stages_done,
|
||||
"stages_failed": meta.stages_failed,
|
||||
"reference_eval": meta.reference_eval,
|
||||
}
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(str(output_dir.resolve()))
|
||||
|
||||
|
||||
@app.command(name="export-ultrastar")
|
||||
def export_ultrastar_cmd(
|
||||
song_dir: Path = typer.Argument(..., help="Song-Paket directory to export", exists=True),
|
||||
title: str | None = typer.Option(None, "--title", help="Override song title"),
|
||||
artist: str | None = typer.Option(None, "--artist", help="Override artist name"),
|
||||
lang: str | None = typer.Option(None, "--lang", help="Override language (e.g. 'de', 'en')"),
|
||||
) -> None:
|
||||
"""Export an existing Song-Paket directory to UltraStar song.txt."""
|
||||
from unmix.export.ultrastar import export_ultrastar
|
||||
|
||||
res = export_ultrastar(song_dir, title=title, artist=artist, language=lang)
|
||||
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),
|
||||
) -> None:
|
||||
"""Run quality benchmarks against UltraStar ground-truth references."""
|
||||
from unmix.eval.run_eval import run_evaluation
|
||||
|
||||
run_evaluation(testset_config)
|
||||
|
||||
|
||||
@app.command(name="pack")
|
||||
def pack_cmd(
|
||||
song_dir: Path = typer.Argument(..., help="Songpack directory to pack", exists=True),
|
||||
output: Path | None = typer.Option(None, "-o", "--output", help="Output .songpack file path"),
|
||||
variant: str = typer.Option(
|
||||
"full", "--variant", help="Package variant: 'full' (with stems) or 'data' (without stems)"
|
||||
),
|
||||
) -> None:
|
||||
"""Pack a songpack directory into a .songpack archive."""
|
||||
from unmix.container import pack_songpack
|
||||
|
||||
res = pack_songpack(song_dir, output_path=output, variant=variant) # type: ignore[arg-type]
|
||||
print(str(res))
|
||||
|
||||
|
||||
@app.command(name="unpack")
|
||||
def unpack_cmd(
|
||||
songpack_file: Path = typer.Argument(..., help="Path to .songpack archive", exists=True),
|
||||
output_dir: Path | None = typer.Option(None, "-o", "--output", help="Destination folder for unpacked songpack"),
|
||||
) -> None:
|
||||
"""Securely unpack a .songpack archive into a song directory."""
|
||||
from unmix.container import unpack_songpack
|
||||
|
||||
dest = output_dir or songpack_file.with_suffix("")
|
||||
res = unpack_songpack(songpack_file, dest)
|
||||
print(str(res))
|
||||
|
||||
|
||||
@app.command()
|
||||
def doctor() -> None:
|
||||
"""Check environment, ffmpeg installation, GPUs, and PyTorch availability."""
|
||||
table = Table(title=f"unmix v{__version__} Doctor System Check")
|
||||
table.add_column("Component", style="cyan", no_wrap=True)
|
||||
table.add_column("Status", style="bold")
|
||||
table.add_column("Details", style="white")
|
||||
|
||||
# 1. Python version
|
||||
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
|
||||
if sys.version_info.major == 3 and 11 <= sys.version_info.minor <= 12:
|
||||
table.add_row("Python", "[green]OK[/green]", f"{py_ver} ({sys.executable})")
|
||||
else:
|
||||
table.add_row("Python", "[yellow]WARN[/yellow]", f"{py_ver} (Empfohlen: Python 3.11 / 3.12)")
|
||||
|
||||
# 2. ffmpeg
|
||||
ffmpeg_path = shutil.which("ffmpeg")
|
||||
if ffmpeg_path:
|
||||
try:
|
||||
res = subprocess.run([ffmpeg_path, "-version"], capture_output=True, text=True, check=True)
|
||||
first_line = res.stdout.splitlines()[0] if res.stdout else "Available"
|
||||
table.add_row("ffmpeg", "[green]OK[/green]", f"{ffmpeg_path} ({first_line})")
|
||||
except Exception as e:
|
||||
table.add_row("ffmpeg", "[yellow]WARN[/yellow]", f"Found at {ffmpeg_path} but error running: {e}")
|
||||
else:
|
||||
table.add_row("ffmpeg", "[red]FAIL[/red]", "ffmpeg not found in PATH")
|
||||
|
||||
# 3. PyTorch
|
||||
try:
|
||||
import torch # type: ignore
|
||||
|
||||
backend_info = []
|
||||
if getattr(torch.version, "cuda", None):
|
||||
backend_info.append(f"CUDA {torch.version.cuda}")
|
||||
if getattr(torch.version, "hip", None):
|
||||
backend_info.append(f"ROCm/HIP {torch.version.hip}")
|
||||
backend_str = ", ".join(backend_info) if backend_info else "CPU-only"
|
||||
|
||||
table.add_row("PyTorch", "[green]OK[/green]", f"v{torch.__version__} ({backend_str})")
|
||||
|
||||
# Check PyTorch visible GPUs
|
||||
if torch.cuda.is_available():
|
||||
count = torch.cuda.device_count()
|
||||
devices_desc = []
|
||||
for i in range(count):
|
||||
devices_desc.append(f"[{i}] {torch.cuda.get_device_name(i)}")
|
||||
table.add_row("Torch GPUs", "[green]OK[/green]", f"{count} device(s): " + "; ".join(devices_desc))
|
||||
else:
|
||||
table.add_row("Torch GPUs", "[yellow]INFO[/yellow]", "No CUDA/ROCm device active in PyTorch")
|
||||
except ImportError:
|
||||
table.add_row("PyTorch", "[yellow]NOT INSTALLED[/yellow]", "PyTorch is not yet installed in virtualenv")
|
||||
|
||||
# 4. System GPUs / Hardware Devices
|
||||
# AMD ROCm / KFD
|
||||
kfd_path = Path("/dev/kfd")
|
||||
if kfd_path.exists():
|
||||
table.add_row(
|
||||
"AMD ROCm (/dev/kfd)", "[green]DETECTED[/green]", f"{kfd_path} present (AMD GPU kernel driver active)"
|
||||
)
|
||||
else:
|
||||
table.add_row("AMD ROCm (/dev/kfd)", "[dim]NONE[/dim]", "No /dev/kfd device found")
|
||||
|
||||
# NVIDIA device nodes
|
||||
nvidia_nodes = list(Path("/dev").glob("nvidia*"))
|
||||
if nvidia_nodes:
|
||||
table.add_row("NVIDIA Devices", "[green]DETECTED[/green]", f"Found: {', '.join(p.name for p in nvidia_nodes)}")
|
||||
else:
|
||||
table.add_row("NVIDIA Devices", "[dim]NONE[/dim]", "No /dev/nvidia* device nodes found")
|
||||
|
||||
# CLI tools
|
||||
rocm_smi = shutil.which("rocm-smi")
|
||||
table.add_row("rocm-smi", "[green]OK[/green]" if rocm_smi else "[dim]NONE[/dim]", rocm_smi or "Not found in PATH")
|
||||
|
||||
nvidia_smi = shutil.which("nvidia-smi")
|
||||
table.add_row(
|
||||
"nvidia-smi", "[green]OK[/green]" if nvidia_smi else "[dim]NONE[/dim]", nvidia_smi or "Not found in PATH"
|
||||
)
|
||||
|
||||
# 5. Model Cache Directory
|
||||
model_dir = config.models_cache_dir
|
||||
table.add_row("Model Cache", "[green]OK[/green]", str(model_dir))
|
||||
|
||||
console.print(table)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app()
|
||||
66
src/unmix/config.py
Normal file
66
src/unmix/config.py
Normal file
@ -0,0 +1,66 @@
|
||||
"""Configuration management for unmix (devices, models, paths)."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
def _detect_default_device() -> str:
|
||||
env_dev = os.getenv("UNMIX_DEFAULT_DEVICE")
|
||||
if env_dev:
|
||||
return env_dev
|
||||
try:
|
||||
import torch
|
||||
|
||||
if torch.cuda.is_available():
|
||||
return "cuda:0"
|
||||
except Exception:
|
||||
pass
|
||||
return "cpu"
|
||||
|
||||
|
||||
class Config(BaseModel):
|
||||
"""Runtime configuration for pipeline stages, devices, and directories."""
|
||||
|
||||
models_cache_dir: Path = Field(
|
||||
default_factory=lambda: Path(
|
||||
os.getenv("UNMIX_MODELS_DIR", Path.home() / ".cache" / "unmix" / "models")
|
||||
).expanduser()
|
||||
)
|
||||
|
||||
default_device: str = Field(default_factory=_detect_default_device)
|
||||
|
||||
stage_devices: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
def get_device(self, stage: str) -> str:
|
||||
"""Get target compute device for a specific stage, with automatic CPU fallback."""
|
||||
stage_env_key = f"UNMIX_DEVICE_{stage.upper()}"
|
||||
# Also check common shorthand like UNMIX_DEVICE_S2
|
||||
stage_prefix = stage.split("_")[0].upper()
|
||||
shorthand_key = f"UNMIX_DEVICE_{stage_prefix}"
|
||||
|
||||
dev = (
|
||||
os.getenv(stage_env_key) or os.getenv(shorthand_key) or self.stage_devices.get(stage) or self.default_device
|
||||
)
|
||||
|
||||
# Fallback if CUDA requested but not available
|
||||
if dev.startswith("cuda"):
|
||||
try:
|
||||
import torch
|
||||
|
||||
if not torch.cuda.is_available():
|
||||
return "cpu"
|
||||
except Exception:
|
||||
return "cpu"
|
||||
|
||||
return dev
|
||||
|
||||
def get_models_dir(self) -> Path:
|
||||
"""Ensure and return the model cache directory."""
|
||||
self.models_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
return self.models_cache_dir
|
||||
|
||||
|
||||
# Global singleton instance
|
||||
config = Config()
|
||||
@ -14,10 +14,10 @@ from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from songsplit.pipeline.runner import compute_file_sha256
|
||||
from songsplit.schema.manifest import ManifestDocument, ManifestFileInfo
|
||||
from unmix.pipeline.runner import compute_file_sha256
|
||||
from unmix.schema.manifest import ManifestDocument, ManifestFileInfo
|
||||
|
||||
logger = logging.getLogger("songsplit.container")
|
||||
logger = logging.getLogger("unmix.container")
|
||||
|
||||
# Security limits according to Section 12
|
||||
MAX_ENTRIES = 64
|
||||
6
src/unmix/eval/__init__.py
Normal file
6
src/unmix/eval/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
"""Evaluation package."""
|
||||
|
||||
from unmix.eval.metrics import evaluate_vocals, normalize_text_for_wer
|
||||
from unmix.eval.run_eval import run_evaluation
|
||||
|
||||
__all__ = ["evaluate_vocals", "normalize_text_for_wer", "run_evaluation"]
|
||||
348
src/unmix/eval/metrics.py
Normal file
348
src/unmix/eval/metrics.py
Normal file
@ -0,0 +1,348 @@
|
||||
"""Quality metrics comparing predicted vocals against UltraStar reference ground-truth."""
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import jiwer
|
||||
import numpy as np
|
||||
|
||||
from unmix.export.ultrastar import UltraStarSong
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def normalize_text_for_wer(text: str) -> str:
|
||||
"""Normalize text: remove punctuation, lowercase, normalize whitespace."""
|
||||
# Remove UltraStar formatting tokens (~, -, etc.) and standard punctuation
|
||||
text = re.sub(r"[^\w\s]", "", text)
|
||||
text = re.sub(r"\s+", " ", text)
|
||||
return text.strip().lower()
|
||||
|
||||
|
||||
def extract_text_from_reference(reference: UltraStarSong) -> str:
|
||||
"""Extract reconstructed text from UltraStar lines, respecting word boundaries."""
|
||||
line_texts = []
|
||||
for line in reference.lines:
|
||||
line_str = "".join(note.text for note in line).strip()
|
||||
if line_str:
|
||||
line_texts.append(line_str)
|
||||
return " ".join(line_texts)
|
||||
|
||||
|
||||
def extract_text_from_vocals(predicted: VocalsDocument) -> str:
|
||||
"""Extract reconstructed text from VocalsDocument, respecting word boundaries."""
|
||||
line_texts = []
|
||||
for line in predicted.lines:
|
||||
words = []
|
||||
cur_word = ""
|
||||
for syl in line.syllables:
|
||||
txt = syl.text
|
||||
cur_word += txt
|
||||
# Word boundary is marked by word_end=True or trailing whitespace
|
||||
if getattr(syl, "word_end", False) or txt.endswith(" "):
|
||||
words.append(cur_word.strip())
|
||||
cur_word = ""
|
||||
if cur_word:
|
||||
words.append(cur_word.strip())
|
||||
line_str = " ".join(w for w in words if w)
|
||||
if line_str:
|
||||
line_texts.append(line_str)
|
||||
return " ".join(line_texts)
|
||||
|
||||
|
||||
def evaluate_vocals(
|
||||
predicted: VocalsDocument,
|
||||
reference: UltraStarSong,
|
||||
max_match_distance_sec: float = 0.5,
|
||||
) -> dict[str, Any]:
|
||||
"""Calculate comprehensive timing, pitch, and WER metrics against UltraStar reference."""
|
||||
# Flatten reference syllables
|
||||
ref_notes = []
|
||||
for line in reference.lines:
|
||||
for note in line:
|
||||
if note.text.strip():
|
||||
ref_notes.append(note)
|
||||
|
||||
# Flatten predicted syllables
|
||||
pred_syllables = []
|
||||
for line in predicted.lines:
|
||||
for syl in line.syllables:
|
||||
if syl.text.strip():
|
||||
pred_syllables.append(syl)
|
||||
|
||||
num_ref_lines = len([line_item for line_item in reference.lines if any(n.text.strip() for n in line_item)])
|
||||
num_pred_lines = len(
|
||||
[line_item for line_item in predicted.lines if any(s.text.strip() for s in line_item.syllables)]
|
||||
)
|
||||
|
||||
if not ref_notes or not pred_syllables:
|
||||
return {
|
||||
"num_ref_syllables": len(ref_notes),
|
||||
"num_pred_syllables": len(pred_syllables),
|
||||
"num_ref_lines": num_ref_lines,
|
||||
"num_pred_lines": num_pred_lines,
|
||||
"mae_timing_ms": 0.0,
|
||||
"median_timing_ms": 0.0,
|
||||
"fraction_within_50ms": 0.0,
|
||||
"fraction_within_100ms": 0.0,
|
||||
"fraction_within_200ms": 0.0,
|
||||
"duration_mae_ms": 0.0,
|
||||
"strict_pitch_accuracy": 0.0,
|
||||
"pitch_class_accuracy": 0.0,
|
||||
"octave_equiv_pitch_accuracy": 0.0,
|
||||
"median_octave_offset": 0.0,
|
||||
"line_start_mae_ms": 0.0,
|
||||
"line_end_mae_ms": 0.0,
|
||||
"wer": 1.0 if not pred_syllables and ref_notes else 0.0,
|
||||
}
|
||||
|
||||
# Match each reference syllable to nearest predicted syllable within max_match_distance_sec
|
||||
timing_errors_ms = []
|
||||
strict_pitch_correct = []
|
||||
pitch_class_correct = []
|
||||
matched_pairs = []
|
||||
|
||||
matched_pred_indices = set()
|
||||
for ref in ref_notes:
|
||||
best_idx = None
|
||||
best_diff = float("inf")
|
||||
|
||||
for idx, pred in enumerate(pred_syllables):
|
||||
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_syllables[best_idx]
|
||||
matched_pairs.append((ref, pred))
|
||||
timing_errors_ms.append(best_diff * 1000.0)
|
||||
|
||||
# Pitch check (rounded to nearest halftone)
|
||||
ref_m = int(round(ref.midi))
|
||||
pred_m = int(round(pred.midi)) if pred.midi is not None else -999
|
||||
|
||||
is_strict = pred_m == ref_m
|
||||
strict_pitch_correct.append(1.0 if is_strict else 0.0)
|
||||
|
||||
# Pitch class check (chroma equality: mod 12)
|
||||
is_class = (pred_m % 12) == (ref_m % 12)
|
||||
pitch_class_correct.append(1.0 if is_class else 0.0)
|
||||
else:
|
||||
# Unmatched reference note -> penalty
|
||||
timing_errors_ms.append(max_match_distance_sec * 1000.0)
|
||||
strict_pitch_correct.append(0.0)
|
||||
pitch_class_correct.append(0.0)
|
||||
|
||||
# 1. Timing metrics
|
||||
mae_timing_ms = float(np.mean(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||
median_timing_ms = float(np.median(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||
fraction_within_50ms = (
|
||||
float(np.mean([1.0 if err <= 50.0 else 0.0 for err in timing_errors_ms])) if timing_errors_ms else 0.0
|
||||
)
|
||||
fraction_within_100ms = (
|
||||
float(np.mean([1.0 if err <= 100.0 else 0.0 for err in timing_errors_ms])) if timing_errors_ms else 0.0
|
||||
)
|
||||
fraction_within_200ms = (
|
||||
float(np.mean([1.0 if err <= 200.0 else 0.0 for err in timing_errors_ms])) if timing_errors_ms else 0.0
|
||||
)
|
||||
|
||||
# Note duration MAE on matched notes
|
||||
if matched_pairs:
|
||||
dur_diffs = [abs((p.end - p.start) - (r.end_sec - r.start_sec)) * 1000.0 for r, p in matched_pairs]
|
||||
duration_mae_ms = float(np.mean(dur_diffs))
|
||||
else:
|
||||
duration_mae_ms = 0.0
|
||||
|
||||
# 2. Pitch metrics
|
||||
strict_pitch_acc = float(np.mean(strict_pitch_correct)) if strict_pitch_correct else 0.0
|
||||
pitch_class_acc = float(np.mean(pitch_class_correct)) if pitch_class_correct else 0.0
|
||||
|
||||
# Octave offset median
|
||||
if matched_pairs:
|
||||
octave_offsets = [round((p.midi - r.midi) / 12.0) for r, p in matched_pairs if p.midi is not None]
|
||||
median_octave_offset = float(np.median(octave_offsets)) if octave_offsets else 0.0
|
||||
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)]
|
||||
|
||||
line_start_diffs_ms = []
|
||||
line_end_diffs_ms = []
|
||||
for r_line in ref_lines_valid:
|
||||
r_start = r_line[0].start_sec
|
||||
r_end = r_line[-1].end_sec
|
||||
best_diff = float("inf")
|
||||
best_p_line = None
|
||||
for p_line in pred_lines_valid:
|
||||
p_start = p_line.syllables[0].start
|
||||
diff = abs(p_start - r_start)
|
||||
if diff < best_diff:
|
||||
best_diff = diff
|
||||
best_p_line = p_line
|
||||
if best_p_line is not None and best_diff <= 2.0:
|
||||
line_start_diffs_ms.append(best_diff * 1000.0)
|
||||
p_end = best_p_line.syllables[-1].end
|
||||
line_end_diffs_ms.append(abs(p_end - r_end) * 1000.0)
|
||||
else:
|
||||
line_start_diffs_ms.append(2000.0)
|
||||
line_end_diffs_ms.append(2000.0)
|
||||
|
||||
line_start_mae_ms = float(np.mean(line_start_diffs_ms)) if line_start_diffs_ms else 0.0
|
||||
line_end_mae_ms = float(np.mean(line_end_diffs_ms)) if line_end_diffs_ms else 0.0
|
||||
|
||||
# 4. WER metric with proper word boundaries
|
||||
raw_ref = extract_text_from_reference(reference)
|
||||
raw_pred = extract_text_from_vocals(predicted)
|
||||
norm_ref = normalize_text_for_wer(raw_ref)
|
||||
norm_pred = normalize_text_for_wer(raw_pred)
|
||||
|
||||
if norm_ref:
|
||||
wer_score = float(jiwer.wer(norm_ref, norm_pred))
|
||||
else:
|
||||
wer_score = 0.0 if not norm_pred else 1.0
|
||||
|
||||
return {
|
||||
"num_ref_syllables": len(ref_notes),
|
||||
"num_pred_syllables": len(pred_syllables),
|
||||
"num_ref_lines": num_ref_lines,
|
||||
"num_pred_lines": num_pred_lines,
|
||||
"mae_timing_ms": mae_timing_ms,
|
||||
"median_timing_ms": median_timing_ms,
|
||||
"fraction_within_50ms": fraction_within_50ms,
|
||||
"fraction_within_100ms": fraction_within_100ms,
|
||||
"fraction_within_200ms": fraction_within_200ms,
|
||||
"duration_mae_ms": duration_mae_ms,
|
||||
"strict_pitch_accuracy": strict_pitch_acc,
|
||||
"pitch_class_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,
|
||||
}
|
||||
|
||||
155
src/unmix/eval/run_eval.py
Normal file
155
src/unmix/eval/run_eval.py
Normal file
@ -0,0 +1,155 @@
|
||||
"""Evaluation runner parsing testset.toml and producing eval_report.md and json."""
|
||||
|
||||
import json
|
||||
import time
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from unmix.eval.metrics import evaluate_vocals
|
||||
from unmix.export.ultrastar import parse_ultrastar
|
||||
from unmix.pipeline import PipelineContext, get_default_pipeline
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def run_evaluation(testset_config: Path, output_report_dir: Path | None = None) -> dict[str, Any]:
|
||||
"""Run evaluation over songs defined in testset.toml."""
|
||||
testset_config = testset_config.resolve()
|
||||
with open(testset_config, "rb") as f:
|
||||
config_data = tomllib.load(f)
|
||||
|
||||
report_dir = output_report_dir or testset_config.parent
|
||||
report_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
songs = config_data.get("songs", [])
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
for song_entry in songs:
|
||||
name = song_entry.get("name", "Unnamed")
|
||||
ref_path = Path(song_entry["reference"]).resolve()
|
||||
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
|
||||
|
||||
song_out_dir = report_dir / "eval_runs" / name
|
||||
ctx = PipelineContext(
|
||||
source_file=audio_path,
|
||||
output_dir=song_out_dir,
|
||||
lang=lang,
|
||||
target_stage="s4_pitch",
|
||||
)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
runner = get_default_pipeline()
|
||||
meta = runner.run(ctx)
|
||||
elapsed_sec = time.perf_counter() - t0
|
||||
|
||||
vocals_json = song_out_dir / "vocals.json"
|
||||
if not vocals_json.exists():
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"status": "failed",
|
||||
"error": "vocals.json not produced",
|
||||
"elapsed_sec": elapsed_sec,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
with open(vocals_json, encoding="utf-8") as vf:
|
||||
pred_vocals = VocalsDocument.model_validate(json.load(vf))
|
||||
|
||||
metrics = evaluate_vocals(pred_vocals, ref_song)
|
||||
metrics["name"] = name
|
||||
metrics["status"] = "success"
|
||||
metrics["elapsed_sec"] = elapsed_sec
|
||||
metrics["stages_done"] = meta.stages_done
|
||||
results.append(metrics)
|
||||
|
||||
# Generate Markdown Report
|
||||
md_lines = [
|
||||
"# unmix Evaluationsbericht (Eval Report)",
|
||||
"",
|
||||
f"Konfiguration: `{testset_config.name}`",
|
||||
f"Getestete Songs: {len(results)}",
|
||||
"",
|
||||
"| 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:
|
||||
if r.get("status") == "success":
|
||||
md_lines.append(
|
||||
f"| {r['name']} | OK | {r['mae_timing_ms']:.1f} | "
|
||||
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 | "
|
||||
f"{r['wer']:.2f} | "
|
||||
f"{r.get('num_pred_lines', 0)}/{r.get('num_ref_lines', 0)} | "
|
||||
f"{r['elapsed_sec']:.1f}s |"
|
||||
)
|
||||
else:
|
||||
md_lines.append(
|
||||
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"
|
||||
report_json_path = report_dir / "eval_report.json"
|
||||
|
||||
with open(report_md_path, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(md_lines) + "\n")
|
||||
|
||||
report_data = {"songs": results, "timestamp": time.time()}
|
||||
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||
json.dump(report_data, f, indent=2)
|
||||
|
||||
return report_data
|
||||
@ -1,5 +1,5 @@
|
||||
"""Export modules."""
|
||||
|
||||
from songsplit.export.ultrastar import UltraStarNote, UltraStarSong, export_ultrastar, parse_ultrastar
|
||||
from unmix.export.ultrastar import UltraStarNote, UltraStarSong, export_ultrastar, parse_ultrastar
|
||||
|
||||
__all__ = ["export_ultrastar", "parse_ultrastar", "UltraStarSong", "UltraStarNote"]
|
||||
471
src/unmix/export/ultrastar.py
Normal file
471
src/unmix/export/ultrastar.py
Normal file
@ -0,0 +1,471 @@
|
||||
"""UltraStar format export (Writer) and import/parsing (Reader).
|
||||
|
||||
Format specifications:
|
||||
- Headers: #TITLE, #ARTIST, #MP3, #BPM, #GAP, #LANGUAGE
|
||||
- Note types:
|
||||
': ' regular note
|
||||
'* ' golden note
|
||||
'F ' freestyle note
|
||||
'- ' line break
|
||||
'E' end of song
|
||||
- Beat resolution in UltraStar: 4 ticks per beat (16th notes).
|
||||
- Pitch in UltraStar: Halftones relative to C4 (MIDI 60).
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from unmix.schema.meta import MetaDocument
|
||||
from unmix.schema.tempo import TempoDocument
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
|
||||
LANG_MAP = {
|
||||
"de": "German",
|
||||
"en": "English",
|
||||
"es": "Spanish",
|
||||
"fr": "French",
|
||||
"it": "Italian",
|
||||
"ja": "Japanese",
|
||||
"ko": "Korean",
|
||||
"zh": "Chinese",
|
||||
}
|
||||
|
||||
|
||||
def export_ultrastar(
|
||||
song_dir: Path,
|
||||
title: str | None = None,
|
||||
artist: str | None = None,
|
||||
language: str | None = None,
|
||||
audio_filename: str | None = None,
|
||||
) -> Path:
|
||||
"""Export song package directory to UltraStar song.txt.
|
||||
|
||||
Reads meta.json, vocals.json, and tempo.json if present.
|
||||
"""
|
||||
song_dir = song_dir.resolve()
|
||||
meta_file = song_dir / "meta.json"
|
||||
vocals_file = song_dir / "vocals.json"
|
||||
tempo_file = song_dir / "tempo.json"
|
||||
output_txt = song_dir / "song.txt"
|
||||
|
||||
if not vocals_file.exists():
|
||||
raise FileNotFoundError(f"vocals.json not found in {song_dir}")
|
||||
|
||||
with open(vocals_file, encoding="utf-8") as f:
|
||||
vocals = VocalsDocument.model_validate(json.load(f))
|
||||
|
||||
meta = None
|
||||
if meta_file.exists():
|
||||
with open(meta_file, encoding="utf-8") as f:
|
||||
meta = MetaDocument.model_validate(json.load(f))
|
||||
|
||||
tempo = None
|
||||
if tempo_file.exists():
|
||||
with open(tempo_file, encoding="utf-8") as f:
|
||||
tempo = TempoDocument.model_validate(json.load(f))
|
||||
|
||||
final_title = title or (meta.title if meta and meta.title else song_dir.name)
|
||||
final_artist = artist or (meta.artist if meta and meta.artist else "Unknown Artist")
|
||||
raw_lang = language or (meta.language if meta and meta.language else "German")
|
||||
final_language = LANG_MAP.get(raw_lang.lower(), raw_lang)
|
||||
|
||||
# Find earliest vocal syllable for GAP
|
||||
first_syllable_sec = 0.0
|
||||
for line in vocals.lines:
|
||||
if line.syllables:
|
||||
first_syllable_sec = line.syllables[0].start
|
||||
break
|
||||
|
||||
# Determine reference BPM (standard quarter-note BPM)
|
||||
if tempo and tempo.anchors:
|
||||
base_bpm = float(tempo.anchors[0].bpm)
|
||||
else:
|
||||
base_bpm = 120.0
|
||||
|
||||
gap_ms = int(max(0.0, first_syllable_sec) * 1000.0)
|
||||
gap_sec = gap_ms / 1000.0
|
||||
|
||||
# Determine audio reference filename (#MP3)
|
||||
mp3_name = audio_filename
|
||||
if not mp3_name and meta:
|
||||
src = getattr(meta, "source", None) or getattr(meta, "source_file", None)
|
||||
if src and hasattr(src, "filename") and src.filename:
|
||||
mp3_name = src.filename
|
||||
elif src and hasattr(src, "path") and src.path:
|
||||
mp3_name = Path(src.path).name
|
||||
if not mp3_name:
|
||||
for ext in [".mp3", ".ogg", ".flac", ".m4a", ".wav"]:
|
||||
candidates = [p for p in song_dir.glob(f"*{ext}") if p.name not in ["vocals.wav", "instrumental.wav"]]
|
||||
if candidates:
|
||||
mp3_name = candidates[0].name
|
||||
break
|
||||
if not mp3_name:
|
||||
if (song_dir / "extracted.wav").exists():
|
||||
mp3_name = "extracted.wav"
|
||||
elif (song_dir / ".cache" / "extracted.wav").exists():
|
||||
mp3_name = "extracted.wav"
|
||||
else:
|
||||
mp3_name = "audio.mp3"
|
||||
|
||||
out_lines = [
|
||||
f"#TITLE:{final_title}",
|
||||
f"#ARTIST:{final_artist}",
|
||||
f"#MP3:{mp3_name}",
|
||||
f"#BPM:{base_bpm:.2f}",
|
||||
f"#GAP:{gap_ms}",
|
||||
f"#LANGUAGE:{final_language}",
|
||||
]
|
||||
|
||||
# Pass through additional header fields from meta.ultrastar
|
||||
if meta and hasattr(meta, "ultrastar") and meta.ultrastar:
|
||||
for k, v in meta.ultrastar.items():
|
||||
if k.upper() not in ["TITLE", "ARTIST", "MP3", "BPM", "GAP", "LANGUAGE"]:
|
||||
out_lines.append(f"#{k.upper()}:{v}")
|
||||
|
||||
# UltraStar timing: 1 tick = 15.0 / BPM seconds -> beats = rel_sec * (BPM / 15.0)
|
||||
ticks_per_sec = base_bpm / 15.0
|
||||
|
||||
def sec_to_ultrastar_beat(sec: float) -> int:
|
||||
rel_sec = max(0.0, sec - gap_sec)
|
||||
return max(0, int(round(rel_sec * ticks_per_sec)))
|
||||
|
||||
def duration_to_ultrastar_beats(dur: float) -> int:
|
||||
return max(1, int(round(dur * ticks_per_sec)))
|
||||
|
||||
tag_map = {"normal": ":", "golden": "*", "freestyle": "F", "rap": "R"}
|
||||
|
||||
current_beat = 0
|
||||
for line_idx, line in enumerate(vocals.lines):
|
||||
if not line.syllables:
|
||||
continue
|
||||
|
||||
for syl_idx, syl in enumerate(line.syllables):
|
||||
syl_start_beat = sec_to_ultrastar_beat(syl.start)
|
||||
duration_beats = duration_to_ultrastar_beats(syl.end - syl.start)
|
||||
|
||||
# Prevent overlap with previous syllable in same line
|
||||
if syl_start_beat < current_beat:
|
||||
syl_start_beat = current_beat
|
||||
|
||||
current_beat = syl_start_beat + duration_beats
|
||||
|
||||
# UltraStar pitch relative to C4 (MIDI 60)
|
||||
midi_val = syl.midi if syl.midi is not None else 60.0
|
||||
pitch = int(round(midi_val - 60.0))
|
||||
tag = tag_map.get(getattr(syl, "type", "normal"), "*" if getattr(syl, "golden", False) else ":")
|
||||
|
||||
# Preserve trailing space or text (don't add trailing space to the last syllable of a line)
|
||||
txt = syl.text
|
||||
is_last_in_line = syl_idx == len(line.syllables) - 1
|
||||
if getattr(syl, "word_end", False) and not txt.endswith(" ") and not is_last_in_line:
|
||||
txt += " "
|
||||
out_lines.append(f"{tag} {syl_start_beat} {duration_beats} {pitch} {txt}")
|
||||
|
||||
# Add line break if not the last line
|
||||
if line_idx < len(vocals.lines) - 1:
|
||||
next_line_start = None
|
||||
for next_l in vocals.lines[line_idx + 1 :]:
|
||||
if next_l.syllables:
|
||||
next_line_start = sec_to_ultrastar_beat(next_l.syllables[0].start)
|
||||
break
|
||||
if next_line_start is not None and next_line_start > current_beat + 1:
|
||||
line_break_beat = current_beat + (next_line_start - current_beat) // 2
|
||||
else:
|
||||
line_break_beat = current_beat + 1
|
||||
out_lines.append(f"- {line_break_beat}")
|
||||
current_beat = line_break_beat + 1
|
||||
|
||||
out_lines.append("E")
|
||||
out_lines.append("")
|
||||
|
||||
content_str = "\n".join(out_lines)
|
||||
|
||||
# Save to export/song.txt per Songpack specification v1.0
|
||||
export_dir = song_dir / "export"
|
||||
export_dir.mkdir(parents=True, exist_ok=True)
|
||||
export_txt = export_dir / "song.txt"
|
||||
with open(export_txt, "w", encoding="utf-8") as f:
|
||||
f.write(content_str)
|
||||
|
||||
# Also save to root song.txt for backward compatibility
|
||||
with open(output_txt, "w", encoding="utf-8") as f:
|
||||
f.write(content_str)
|
||||
|
||||
return export_txt
|
||||
|
||||
|
||||
class UltraStarNote:
|
||||
"""A parsed note from an UltraStar file."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
note_type: str,
|
||||
start_beat: int,
|
||||
duration: int,
|
||||
pitch: int,
|
||||
text: str,
|
||||
start_sec: float = 0.0,
|
||||
end_sec: float = 0.0,
|
||||
midi: float = 60.0,
|
||||
):
|
||||
self.note_type = note_type
|
||||
self.start_beat = start_beat
|
||||
self.duration = duration
|
||||
self.pitch = pitch
|
||||
self.text = text
|
||||
self.start_sec = start_sec
|
||||
self.end_sec = end_sec
|
||||
self.midi = midi
|
||||
|
||||
|
||||
class UltraStarSong:
|
||||
"""A complete parsed UltraStar song structure."""
|
||||
|
||||
def __init__(self, headers: dict[str, str], lines: list[list[UltraStarNote]]):
|
||||
self.headers = headers
|
||||
self.lines = lines
|
||||
|
||||
@property
|
||||
def title(self) -> str:
|
||||
return self.headers.get("TITLE", "")
|
||||
|
||||
@property
|
||||
def artist(self) -> str:
|
||||
return self.headers.get("ARTIST", "")
|
||||
|
||||
@property
|
||||
def bpm(self) -> float:
|
||||
# Standard quarter-note BPM from header
|
||||
return float(self.headers.get("BPM", "120").replace(",", "."))
|
||||
|
||||
@property
|
||||
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."""
|
||||
headers: dict[str, str] = {}
|
||||
lines: list[list[UltraStarNote]] = []
|
||||
current_line: list[UltraStarNote] = []
|
||||
|
||||
with open(file_path, encoding="utf-8", errors="replace") as f:
|
||||
content = f.read()
|
||||
|
||||
raw_lines = content.splitlines()
|
||||
|
||||
for raw in raw_lines:
|
||||
line = raw.rstrip("\r\n")
|
||||
if not line or not line.strip():
|
||||
continue
|
||||
|
||||
if line.startswith("#"):
|
||||
# Header line: #KEY:VALUE
|
||||
match = re.match(r"^#([A-Za-z0-9_-]+):(.*)$", line.strip())
|
||||
if match:
|
||||
k, v = match.group(1).upper(), match.group(2).strip()
|
||||
headers[k] = v
|
||||
continue
|
||||
|
||||
if line.startswith("E"):
|
||||
# End of song
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
current_line = []
|
||||
break
|
||||
|
||||
if line.startswith("-"):
|
||||
# Line break
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
current_line = []
|
||||
continue
|
||||
|
||||
# Note line: : 10 4 2 text
|
||||
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line)
|
||||
if match:
|
||||
ntype, s_beat, dur, pitch, text = match.groups()
|
||||
note = UltraStarNote(
|
||||
note_type=ntype,
|
||||
start_beat=int(s_beat),
|
||||
duration=int(dur),
|
||||
pitch=int(pitch),
|
||||
text=text,
|
||||
)
|
||||
current_line.append(note)
|
||||
|
||||
if current_line:
|
||||
lines.append(current_line)
|
||||
|
||||
# Calculate absolute timings in seconds for each note
|
||||
raw_bpm = float(headers.get("BPM", "120").replace(",", "."))
|
||||
gap_sec = float(headers.get("GAP", "0").replace(",", ".")) / 1000.0
|
||||
|
||||
# UltraStar tick duration in seconds = 15.0 / BPM (4 ticks per quarter note)
|
||||
sec_per_tick = 15.0 / raw_bpm if raw_bpm > 0 else 0.03125
|
||||
|
||||
for line_notes in lines:
|
||||
for note in line_notes:
|
||||
note.start_sec = gap_sec + (note.start_beat * sec_per_tick)
|
||||
note.end_sec = note.start_sec + (note.duration * sec_per_tick)
|
||||
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
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
"""Pipeline stages and runner."""
|
||||
|
||||
from songsplit.pipeline.runner import PipelineContext, PipelineRunner, Stage
|
||||
from songsplit.pipeline.s1_extract import ExtractStage
|
||||
from songsplit.pipeline.s2_stems import StemsStage
|
||||
from songsplit.pipeline.s3_lyrics import LyricsStage
|
||||
from songsplit.pipeline.s4_pitch import PitchStage
|
||||
from songsplit.pipeline.s5_tempo import TempoStage
|
||||
from songsplit.pipeline.s6_chords import ChordsStage
|
||||
from songsplit.pipeline.s7_strumming import StrummingStage
|
||||
from unmix.pipeline.runner import PipelineContext, PipelineRunner, Stage
|
||||
from unmix.pipeline.s1_extract import ExtractStage
|
||||
from unmix.pipeline.s2_stems import StemsStage
|
||||
from unmix.pipeline.s3_lyrics import LyricsStage
|
||||
from unmix.pipeline.s4_pitch import PitchStage
|
||||
from unmix.pipeline.s5_tempo import TempoStage
|
||||
from unmix.pipeline.s6_chords import ChordsStage
|
||||
from unmix.pipeline.s7_strumming import StrummingStage
|
||||
|
||||
|
||||
def get_default_pipeline() -> PipelineRunner:
|
||||
"""Instantiate the default 7-stage songsplit pipeline."""
|
||||
"""Instantiate the default 7-stage unmix pipeline."""
|
||||
return PipelineRunner(
|
||||
[
|
||||
ExtractStage(),
|
||||
@ -9,9 +9,9 @@ from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from songsplit.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
|
||||
from unmix.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
|
||||
|
||||
logger = logging.getLogger("songsplit.pipeline")
|
||||
logger = logging.getLogger("unmix.pipeline")
|
||||
|
||||
|
||||
def compute_file_sha256(file_path: Path, chunk_size: int = 65536) -> str:
|
||||
@ -59,13 +59,17 @@ class PipelineContext:
|
||||
if self.meta_file.exists():
|
||||
with open(self.meta_file, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return MetaDocument.model_validate(data)
|
||||
meta = MetaDocument.model_validate(data)
|
||||
if self.lang and not meta.language:
|
||||
meta.language = self.lang
|
||||
return meta
|
||||
|
||||
source_hash = compute_file_sha256(self.source_file) if self.source_file.exists() else ""
|
||||
size_bytes = self.source_file.stat().st_size if self.source_file.exists() else 0
|
||||
|
||||
return MetaDocument(
|
||||
duration_sec=0.0,
|
||||
language=self.lang,
|
||||
source=SourceFileInfo(
|
||||
filename=self.source_file.name,
|
||||
path=str(self.source_file),
|
||||
@ -259,6 +263,9 @@ class PipelineRunner:
|
||||
meta = ctx.load_or_init_meta()
|
||||
|
||||
stages_to_run = self.get_stages_to_run(ctx)
|
||||
# Clear previous failure entries for stages that are being executed in this run
|
||||
for s in stages_to_run:
|
||||
meta.stages_failed.pop(s.name, None)
|
||||
failed_stages: set[str] = set(meta.stages_failed.keys())
|
||||
|
||||
for stage in stages_to_run:
|
||||
@ -311,7 +318,7 @@ class PipelineRunner:
|
||||
ctx.save_meta(meta)
|
||||
|
||||
try:
|
||||
from songsplit.container import build_manifest_for_dir
|
||||
from unmix.container import build_manifest_for_dir
|
||||
|
||||
manifest = build_manifest_for_dir(ctx.output_dir)
|
||||
(ctx.output_dir / "manifest.json").write_text(manifest.model_dump_json(indent=2), encoding="utf-8")
|
||||
@ -6,22 +6,21 @@ import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.pipeline.runner import PipelineContext, Stage
|
||||
|
||||
|
||||
def get_audio_duration(file_path: Path) -> float:
|
||||
"""Get audio duration in seconds using ffprobe."""
|
||||
def get_audio_metadata(file_path: Path) -> dict[str, Any]:
|
||||
"""Get audio duration and metadata tags using ffprobe."""
|
||||
ffprobe_path = shutil.which("ffprobe")
|
||||
if not ffprobe_path:
|
||||
# Fallback to ffmpeg
|
||||
return 0.0
|
||||
return {}
|
||||
|
||||
cmd = [
|
||||
ffprobe_path,
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=duration",
|
||||
"format=duration:format_tags=title,artist,album",
|
||||
"-of",
|
||||
"json",
|
||||
str(file_path),
|
||||
@ -29,9 +28,23 @@ def get_audio_duration(file_path: Path) -> float:
|
||||
try:
|
||||
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||
data = json.loads(res.stdout)
|
||||
return float(data.get("format", {}).get("duration", 0.0))
|
||||
fmt = data.get("format", {})
|
||||
tags = fmt.get("tags", {})
|
||||
tags_lower = {k.lower(): v for k, v in tags.items()}
|
||||
return {
|
||||
"duration": float(fmt.get("duration", 0.0)),
|
||||
"title": tags_lower.get("title"),
|
||||
"artist": tags_lower.get("artist"),
|
||||
"album": tags_lower.get("album"),
|
||||
}
|
||||
except Exception:
|
||||
return 0.0
|
||||
return {}
|
||||
|
||||
|
||||
def get_audio_duration(file_path: Path) -> float:
|
||||
"""Get audio duration in seconds using ffprobe."""
|
||||
meta = get_audio_metadata(file_path)
|
||||
return meta.get("duration", 0.0)
|
||||
|
||||
|
||||
class ExtractStage(Stage):
|
||||
@ -64,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>
|
||||
@ -90,9 +108,15 @@ class ExtractStage(Stage):
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"ffmpeg extraction failed: {res.stderr}")
|
||||
|
||||
# Update duration in meta document if available
|
||||
duration = get_audio_duration(output_wav)
|
||||
if duration > 0.0:
|
||||
meta = ctx.load_or_init_meta()
|
||||
meta.duration_sec = duration
|
||||
ctx.save_meta(meta)
|
||||
# Update metadata (duration and ID3/container tags) if available
|
||||
meta_info = get_audio_metadata(ctx.source_file) or get_audio_metadata(output_wav)
|
||||
meta = ctx.load_or_init_meta()
|
||||
if meta_info.get("duration", 0.0) > 0.0:
|
||||
meta.duration_sec = meta_info["duration"]
|
||||
if not meta.title and meta_info.get("title"):
|
||||
meta.title = meta_info["title"]
|
||||
if not meta.artist and meta_info.get("artist"):
|
||||
meta.artist = meta_info["artist"]
|
||||
if not meta.album and meta_info.get("album"):
|
||||
meta.album = meta_info["album"]
|
||||
ctx.save_meta(meta)
|
||||
@ -7,8 +7,8 @@ import julius
|
||||
import soundfile as sf
|
||||
import torch
|
||||
|
||||
from songsplit.config import config
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.config import config
|
||||
from unmix.pipeline.runner import PipelineContext, Stage
|
||||
|
||||
|
||||
class StemsStage(Stage):
|
||||
343
src/unmix/pipeline/s3_lyrics.py
Normal file
343
src/unmix/pipeline/s3_lyrics.py
Normal file
@ -0,0 +1,343 @@
|
||||
"""Stage 3: Lyrics transcription & alignment (Whisper + pyphen hyphenation)."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pyphen
|
||||
|
||||
from unmix.config import config
|
||||
from unmix.pipeline.runner import PipelineContext, Stage
|
||||
|
||||
|
||||
def hyphenate_word(word_text: str, dic: pyphen.Pyphen) -> list[str]:
|
||||
"""Split a word into syllables using pyphen while preserving punctuation and spacing."""
|
||||
stripped = word_text.strip()
|
||||
if not stripped:
|
||||
return [word_text]
|
||||
|
||||
# Separate leading/trailing punctuation from core word
|
||||
match = re.match(r"^(\W*)([\w\-]+)(\W*)$", stripped)
|
||||
if not match:
|
||||
return [word_text]
|
||||
|
||||
prefix, core, suffix = match.groups()
|
||||
|
||||
# Hyphenate core word
|
||||
hyphenated = dic.inserted(core)
|
||||
parts = hyphenated.split("-") if "-" in hyphenated else [core]
|
||||
|
||||
if len(parts) == 1:
|
||||
return [word_text]
|
||||
|
||||
# Attach prefix to first syllable, suffix (and trailing space if original had one) to last
|
||||
has_trailing_space = word_text.endswith(" ")
|
||||
res = []
|
||||
for i, p in enumerate(parts):
|
||||
s = p
|
||||
if i == 0 and prefix:
|
||||
s = prefix + s
|
||||
if i == len(parts) - 1:
|
||||
if suffix:
|
||||
s = s + suffix
|
||||
if has_trailing_space:
|
||||
s = s + " "
|
||||
res.append(s)
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def split_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]]:
|
||||
"""Hyphenate word and distribute duration proportionally to syllable length."""
|
||||
syllables = hyphenate_word(word_text, dic)
|
||||
duration = max(0.01, end - start)
|
||||
|
||||
if len(syllables) == 1:
|
||||
return [{"text": syllables[0], "start": start, "end": end, "word_end": True}]
|
||||
|
||||
total_chars = sum(max(1, len(s.strip())) for s in syllables)
|
||||
timed = []
|
||||
cur_t = start
|
||||
|
||||
for i, syl in enumerate(syllables):
|
||||
char_len = max(1, len(syl.strip()))
|
||||
is_last = i == len(syllables) - 1
|
||||
if is_last:
|
||||
syl_end = end
|
||||
else:
|
||||
syl_dur = duration * (char_len / total_chars)
|
||||
syl_end = cur_t + syl_dur
|
||||
|
||||
timed.append(
|
||||
{
|
||||
"text": syl,
|
||||
"start": cur_t,
|
||||
"end": syl_end,
|
||||
"word_end": is_last,
|
||||
}
|
||||
)
|
||||
cur_t = syl_end
|
||||
|
||||
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.1.0"
|
||||
model_name = "whisper-large-v3"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s2_stems"]
|
||||
|
||||
def __init__(self, model_name: str = "whisper-large-v3"):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.stems_dir / "vocals.wav"]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.cache_dir / "lyrics_raw.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {
|
||||
"lang": ctx.lang or "de",
|
||||
"model_size": "base" if ctx.quality == "fast" else "large-v3",
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
vocals_wav = self.get_inputs(ctx)[0]
|
||||
if not vocals_wav.exists():
|
||||
raise FileNotFoundError(f"Vocals stem not found: {vocals_wav}")
|
||||
|
||||
params = self.get_params(ctx)
|
||||
lang = params["lang"]
|
||||
model_size = params["model_size"]
|
||||
self.model_name = f"whisper-{model_size}"
|
||||
|
||||
# Setup pyphen dictionary
|
||||
pyphen_lang = "de_DE" if lang.lower().startswith("de") else "en_US"
|
||||
try:
|
||||
dic = pyphen.Pyphen(lang=pyphen_lang)
|
||||
except Exception:
|
||||
dic = pyphen.Pyphen(lang="en_US")
|
||||
|
||||
# Determine compute device
|
||||
device_str = config.get_device(self.name)
|
||||
compute_type = "float16" if device_str.startswith("cuda") else "int8"
|
||||
device = "cuda" if device_str.startswith("cuda") else "cpu"
|
||||
|
||||
models_dir = config.get_models_dir()
|
||||
model = WhisperModel(
|
||||
model_size,
|
||||
device=device,
|
||||
compute_type=compute_type,
|
||||
download_root=str(models_dir),
|
||||
)
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
lines = segments_to_lines(raw_segments, dic, split_lines=True)
|
||||
|
||||
output_data = {
|
||||
"language": lang,
|
||||
"detected_language": info.language if hasattr(info, "language") else lang,
|
||||
"lines": lines,
|
||||
}
|
||||
|
||||
output_file = self.get_outputs(ctx)[0]
|
||||
output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
json.dump(output_data, f, indent=2, ensure_ascii=False)
|
||||
432
src/unmix/pipeline/s4_pitch.py
Normal file
432
src/unmix/pipeline/s4_pitch.py
Normal file
@ -0,0 +1,432 @@
|
||||
"""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
|
||||
|
||||
from unmix.config import config
|
||||
from unmix.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.schema.base import GeneratedBy
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def hz_to_midi(hz: np.ndarray) -> np.ndarray:
|
||||
"""Convert frequency in Hz to fractional MIDI note numbers."""
|
||||
valid = hz > 0
|
||||
midi = np.zeros_like(hz, dtype=np.float32)
|
||||
midi[valid] = 69.0 + 12.0 * np.log2(hz[valid] / 440.0)
|
||||
return midi
|
||||
|
||||
|
||||
def correct_octave_errors(syllables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Correct isolated octave doubling/halving jumps relative to melodic context."""
|
||||
if len(syllables) < 3:
|
||||
return syllables
|
||||
|
||||
pitches = [s["midi"] for s in syllables]
|
||||
corrected = list(pitches)
|
||||
|
||||
for i in range(1, len(syllables) - 1):
|
||||
prev_p = corrected[i - 1]
|
||||
next_p = pitches[i + 1]
|
||||
cur_p = pitches[i]
|
||||
|
||||
local_mean = (prev_p + next_p) / 2.0
|
||||
diff = cur_p - local_mean
|
||||
|
||||
# Check for +12 (octave too high)
|
||||
if 10.5 <= diff <= 13.5:
|
||||
corrected[i] = cur_p - 12.0
|
||||
# Check for -12 (octave too low)
|
||||
elif -13.5 <= diff <= -10.5:
|
||||
corrected[i] = cur_p + 12.0
|
||||
# Check for +24 (two octaves too high)
|
||||
elif 22.5 <= diff <= 25.5:
|
||||
corrected[i] = cur_p - 24.0
|
||||
# Check for -24 (two octaves too low)
|
||||
elif -25.5 <= diff <= -22.5:
|
||||
corrected[i] = cur_p + 24.0
|
||||
|
||||
for s, p in zip(syllables, corrected, strict=False):
|
||||
s["midi"] = float(p)
|
||||
|
||||
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.1.0"
|
||||
model_name = "torchcrepe-full"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s3_lyrics"]
|
||||
|
||||
def __init__(self, model_name: str = "torchcrepe-full"):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [
|
||||
ctx.stems_dir / "vocals.wav",
|
||||
ctx.cache_dir / "lyrics_raw.json",
|
||||
]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.output_dir / "vocals.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {
|
||||
"hop_length_ms": 10,
|
||||
"voicing_threshold": 0.25,
|
||||
"crepe_model": "tiny" if ctx.quality == "fast" else "full",
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
import torchcrepe
|
||||
|
||||
vocals_wav, lyrics_json = self.get_inputs(ctx)
|
||||
if not vocals_wav.exists():
|
||||
raise FileNotFoundError(f"Vocals stem not found: {vocals_wav}")
|
||||
if not lyrics_json.exists():
|
||||
raise FileNotFoundError(f"Lyrics file not found: {lyrics_json}")
|
||||
|
||||
with open(lyrics_json, encoding="utf-8") as f:
|
||||
lyrics_data = json.load(f)
|
||||
|
||||
params = self.get_params(ctx)
|
||||
hop_length_ms = params["hop_length_ms"]
|
||||
voicing_thresh = params["voicing_threshold"]
|
||||
crepe_model = params["crepe_model"]
|
||||
self.model_name = f"torchcrepe-{crepe_model}"
|
||||
|
||||
# Load audio using soundfile
|
||||
audio_data, sr = sf.read(str(vocals_wav), dtype="float32")
|
||||
if audio_data.ndim > 1:
|
||||
# Downmix to mono
|
||||
audio_data = audio_data.mean(axis=-1)
|
||||
|
||||
crepe_sr = 16000
|
||||
hop_length = int(crepe_sr * (hop_length_ms / 1000.0))
|
||||
hop_sec = hop_length / crepe_sr
|
||||
|
||||
# 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)
|
||||
|
||||
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_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_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_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", []):
|
||||
sylls = line_dict.get("syllables", [])
|
||||
if not sylls:
|
||||
continue
|
||||
|
||||
line_counter += 1
|
||||
line_syllables_raw = []
|
||||
prev_end = 0.0
|
||||
|
||||
for idx, s in enumerate(sylls):
|
||||
s_start = float(s["start"])
|
||||
s_end = float(s["end"])
|
||||
|
||||
w_min = max(prev_end, s_start - 0.12)
|
||||
w_max = s_start + (0.50 if idx == 0 else 0.20)
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
syl_objects = []
|
||||
for s in corrected_sylls:
|
||||
syl_counter += 1
|
||||
raw_text = s["text"]
|
||||
has_space = raw_text.endswith(" ")
|
||||
clean_text = raw_text.rstrip()
|
||||
is_word_end = s.get("word_end", has_space)
|
||||
syl_objects.append(
|
||||
VocalSyllable(
|
||||
id=f"s_{syl_counter:04d}",
|
||||
text=clean_text,
|
||||
start=s["start"],
|
||||
end=s["end"],
|
||||
midi=s["midi"],
|
||||
confidence=s["confidence"],
|
||||
word_end=is_word_end,
|
||||
source="auto",
|
||||
)
|
||||
)
|
||||
|
||||
if syl_objects:
|
||||
vocal_lines.append(
|
||||
VocalLine(
|
||||
id=f"l_{line_counter:04d}",
|
||||
voice=0,
|
||||
start=syl_objects[0].start,
|
||||
end=syl_objects[-1].end,
|
||||
syllables=syl_objects,
|
||||
)
|
||||
)
|
||||
|
||||
doc = VocalsDocument(
|
||||
schema_version="1.0",
|
||||
generated_by=GeneratedBy(
|
||||
stage=self.name,
|
||||
model=self.model_name,
|
||||
model_version=self.version,
|
||||
params=params,
|
||||
),
|
||||
lines=vocal_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:
|
||||
f.write(doc.model_dump_json(indent=2))
|
||||
|
||||
# Write optional vocals_f0.json per Section 6
|
||||
try:
|
||||
from unmix.schema.vocals_f0 import VocalsF0Document
|
||||
|
||||
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)
|
||||
]
|
||||
f0_conf = [round(float(p), 2) for p in periodicity]
|
||||
f0_doc = VocalsF0Document(
|
||||
schema_version="1.0",
|
||||
hop_sec=round(hop_sec, 4),
|
||||
start_sec=0.0,
|
||||
hz=f0_hz,
|
||||
confidence=f0_conf,
|
||||
)
|
||||
f0_path = ctx.output_dir / "vocals_f0.json"
|
||||
with open(f0_path, "w", encoding="utf-8") as f:
|
||||
f.write(f0_doc.model_dump_json())
|
||||
except Exception:
|
||||
pass
|
||||
@ -5,10 +5,10 @@ from typing import Any
|
||||
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.config import config
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
from songsplit.schema.base import GeneratedBy
|
||||
from songsplit.tempo import build_tempo_map_from_beats, generate_click_track
|
||||
from unmix.config import config
|
||||
from unmix.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.schema.base import GeneratedBy
|
||||
from unmix.tempo import build_tempo_map_from_beats, generate_click_track
|
||||
|
||||
|
||||
class TempoStage(Stage):
|
||||
@ -9,11 +9,11 @@ import librosa
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
from songsplit.schema.base import GeneratedBy
|
||||
from songsplit.schema.chords import ChordEvent, ChordsDocument
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.tempo import beat_to_sec, sec_to_beat
|
||||
from unmix.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.schema.base import GeneratedBy
|
||||
from unmix.schema.chords import ChordEvent, ChordsDocument
|
||||
from unmix.schema.tempo import TempoDocument
|
||||
from unmix.tempo import beat_to_sec, sec_to_beat
|
||||
|
||||
PITCH_CLASSES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
|
||||
|
||||
@ -200,7 +200,7 @@ class ChordsStage(Stage):
|
||||
chroma = librosa.feature.chroma_cqt(y=mono_audio, sr=sr)
|
||||
detected_key_str = estimate_key(chroma.mean(axis=1))
|
||||
|
||||
from songsplit.schema.meta import KeyInfo
|
||||
from unmix.schema.meta import KeyInfo
|
||||
|
||||
if detected_key_str.endswith("m"):
|
||||
key_tonic = detected_key_str[:-1]
|
||||
@ -1,6 +1,6 @@
|
||||
"""Stage 7: Strumming pattern analysis -> tracks/guitar.json (wrapper for s7_tracks/strumming)."""
|
||||
|
||||
from songsplit.pipeline.s7_tracks.strumming import (
|
||||
from unmix.pipeline.s7_tracks.strumming import (
|
||||
StrummingTrackStage,
|
||||
aggregate_strum_patterns,
|
||||
estimate_strum_direction,
|
||||
@ -1,5 +1,5 @@
|
||||
"""Instrument track stages (tracks/<name>.json)."""
|
||||
|
||||
from songsplit.pipeline.s7_tracks.strumming import StrummingTrackStage
|
||||
from unmix.pipeline.s7_tracks.strumming import StrummingTrackStage
|
||||
|
||||
__all__ = ["StrummingTrackStage"]
|
||||
@ -8,11 +8,11 @@ import librosa
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||
from songsplit.schema.base import GeneratedBy
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.schema.tracks import StrumDirection, StrumEvent, StrumGrid, StrumPattern, TrackDocument
|
||||
from songsplit.tempo import sec_to_beat
|
||||
from unmix.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.schema.base import GeneratedBy
|
||||
from unmix.schema.tempo import TempoDocument
|
||||
from unmix.schema.tracks import StrumDirection, StrumEvent, StrumGrid, StrumPattern, TrackDocument
|
||||
from unmix.tempo import sec_to_beat
|
||||
|
||||
|
||||
def estimate_strum_direction(
|
||||
@ -1,8 +1,8 @@
|
||||
"""Songpack data schemas."""
|
||||
|
||||
from songsplit.schema.base import DataSource, EditableItem, GeneratedBy, SongPackageBase
|
||||
from songsplit.schema.chords import ChordEvent, ChordsDocument
|
||||
from songsplit.schema.manifest import (
|
||||
from unmix.schema.base import DataSource, EditableItem, GeneratedBy, SongPackageBase
|
||||
from unmix.schema.chords import ChordEvent, ChordsDocument
|
||||
from unmix.schema.manifest import (
|
||||
FileRole,
|
||||
GeneratorInfo,
|
||||
ManifestDocument,
|
||||
@ -11,7 +11,7 @@ from songsplit.schema.manifest import (
|
||||
StageStatus,
|
||||
StemName,
|
||||
)
|
||||
from songsplit.schema.meta import (
|
||||
from unmix.schema.meta import (
|
||||
AudioRefInfo,
|
||||
CapoSuggestion,
|
||||
KeyInfo,
|
||||
@ -19,11 +19,11 @@ from songsplit.schema.meta import (
|
||||
ModelInfo,
|
||||
SourceFileInfo,
|
||||
)
|
||||
from songsplit.schema.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignatureEntry
|
||||
from songsplit.schema.tracks import DrumEvent, DrumPiece, NoteEvent, TrackDocument, TrackKind
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
from songsplit.schema.vocals_f0 import VocalsF0Document
|
||||
from unmix.schema.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
|
||||
from unmix.schema.tempo import TempoAnchor, TempoDocument, TimeSignatureEntry
|
||||
from unmix.schema.tracks import DrumEvent, DrumPiece, NoteEvent, TrackDocument, TrackKind
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
from unmix.schema.vocals_f0 import VocalsF0Document
|
||||
|
||||
# Backward compatibility alias
|
||||
TimeSignature = TimeSignatureEntry
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from songsplit.schema.base import EditableItem, SongPackageBase
|
||||
from unmix.schema.base import EditableItem, SongPackageBase
|
||||
|
||||
|
||||
class ChordEvent(EditableItem):
|
||||
@ -35,7 +35,7 @@ class GeneratorInfo(BaseModel):
|
||||
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
name: str = "songsplit"
|
||||
name: str = "unmix"
|
||||
version: str = "0.1.0"
|
||||
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
"""Schema for meta.json."""
|
||||
|
||||
from typing import Literal
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from songsplit.schema.base import SongPackageBase
|
||||
from unmix.schema.base import SongPackageBase
|
||||
|
||||
|
||||
class SourceFileInfo(BaseModel):
|
||||
@ -70,7 +70,7 @@ class ModelInfo(BaseModel):
|
||||
class MetaDocument(SongPackageBase):
|
||||
"""Songpack metadata document (meta.json)."""
|
||||
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
model_config = ConfigDict(extra="ignore", populate_by_name=True)
|
||||
|
||||
title: str | None = None
|
||||
artist: str | None = None
|
||||
@ -78,7 +78,7 @@ class MetaDocument(SongPackageBase):
|
||||
year: int | None = None
|
||||
language: str | None = None
|
||||
duration_sec: float = Field(default=0.0, ge=0.0)
|
||||
source: SourceFileInfo = Field(default_factory=SourceFileInfo)
|
||||
source: SourceFileInfo = Field(default_factory=SourceFileInfo, alias="source_file")
|
||||
audio_ref: AudioRefInfo | None = None
|
||||
audio_offset_sec: float = 0.0
|
||||
key: KeyInfo | str | None = None
|
||||
@ -89,6 +89,10 @@ class MetaDocument(SongPackageBase):
|
||||
created_at: str | None = None
|
||||
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["ai", "reference_ultrastar"] = "ai"
|
||||
training_diff: dict[str, Any] | None = None
|
||||
|
||||
|
||||
# Backward compatibility helper
|
||||
@property
|
||||
@ -1,6 +1,6 @@
|
||||
"""Backward-compatible re-export of strumming types from tracks."""
|
||||
|
||||
from songsplit.schema.tracks import (
|
||||
from unmix.schema.tracks import (
|
||||
StrumDirection,
|
||||
StrumEvent,
|
||||
StrumGrid,
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from songsplit.schema.base import EditableItem, SongPackageBase
|
||||
from unmix.schema.base import EditableItem, SongPackageBase
|
||||
|
||||
|
||||
class TempoAnchor(EditableItem):
|
||||
@ -4,7 +4,7 @@ from typing import Any, Literal
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from songsplit.schema.base import EditableItem, SongPackageBase
|
||||
from unmix.schema.base import EditableItem, SongPackageBase
|
||||
|
||||
TrackKind = Literal["strumming", "notes", "drums"]
|
||||
StrumDirection = Literal["down", "up", "mute", "unknown"]
|
||||
@ -4,7 +4,7 @@ from typing import Literal
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from songsplit.schema.base import EditableItem, SongPackageBase
|
||||
from unmix.schema.base import EditableItem, SongPackageBase
|
||||
|
||||
SyllableType = Literal["normal", "golden", "freestyle", "rap"]
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from songsplit.schema.base import SongPackageBase
|
||||
from unmix.schema.base import SongPackageBase
|
||||
|
||||
|
||||
class VocalsF0Document(SongPackageBase):
|
||||
5
src/unmix/sources/__init__.py
Normal file
5
src/unmix/sources/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
"""Sources package for external inputs (local files, URLs)."""
|
||||
|
||||
from unmix.sources.youtube import download_url_audio, is_url
|
||||
|
||||
__all__ = ["download_url_audio", "is_url"]
|
||||
84
src/unmix/sources/youtube.py
Normal file
84
src/unmix/sources/youtube.py
Normal file
@ -0,0 +1,84 @@
|
||||
"""YouTube and web audio download helper using yt-dlp."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("unmix.sources.youtube")
|
||||
|
||||
|
||||
def is_url(target: str) -> bool:
|
||||
"""Check if target is a web URL."""
|
||||
return bool(re.match(r"^https?://[^\s]+", target.strip()))
|
||||
|
||||
|
||||
def download_url_audio(url: str, temp_dir: Path) -> tuple[Path, dict[str, Any]]:
|
||||
"""Download audio track from a YouTube or web URL using yt-dlp.
|
||||
|
||||
Returns the path to the downloaded WAV file and extracted metadata (title, artist, etc.).
|
||||
"""
|
||||
yt_dlp_path = shutil.which("yt-dlp")
|
||||
if not yt_dlp_path:
|
||||
raise RuntimeError(
|
||||
"yt-dlp is required to analyze web URLs. "
|
||||
"Please install yt-dlp (e.g. 'pip install yt-dlp' or package manager)."
|
||||
)
|
||||
|
||||
temp_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Fetch metadata
|
||||
info_cmd = [
|
||||
yt_dlp_path,
|
||||
"--no-playlist",
|
||||
"--dump-single-json",
|
||||
url,
|
||||
]
|
||||
if shutil.which("node"):
|
||||
info_cmd.extend(["--js-runtimes", "node"])
|
||||
|
||||
meta: dict[str, Any] = {}
|
||||
try:
|
||||
res = subprocess.run(info_cmd, capture_output=True, text=True, check=True)
|
||||
info_json = json.loads(res.stdout)
|
||||
meta["title"] = info_json.get("track") or info_json.get("title")
|
||||
meta["artist"] = (
|
||||
info_json.get("artist") or info_json.get("creator") or info_json.get("channel") or info_json.get("uploader")
|
||||
)
|
||||
meta["duration"] = info_json.get("duration")
|
||||
meta["webpage_url"] = info_json.get("webpage_url", url)
|
||||
except Exception as e:
|
||||
logger.warning("Could not extract metadata from URL with yt-dlp: %s", e)
|
||||
|
||||
# 2. Download and extract audio to WAV
|
||||
out_template = str(temp_dir / "%(id)s.%(ext)s")
|
||||
dl_cmd = [
|
||||
yt_dlp_path,
|
||||
"--no-playlist",
|
||||
"-x",
|
||||
"--audio-format",
|
||||
"wav",
|
||||
"--audio-quality",
|
||||
"0",
|
||||
"-o",
|
||||
out_template,
|
||||
url,
|
||||
]
|
||||
if shutil.which("node"):
|
||||
dl_cmd.extend(["--js-runtimes", "node"])
|
||||
|
||||
res = subprocess.run(dl_cmd, capture_output=True, text=True)
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"yt-dlp audio download failed:\n{res.stderr}")
|
||||
|
||||
# Locate downloaded WAV file
|
||||
wav_files = list(temp_dir.glob("*.wav"))
|
||||
if not wav_files:
|
||||
raise FileNotFoundError(f"yt-dlp completed but no WAV file found in {temp_dir}")
|
||||
|
||||
# Return newest downloaded file
|
||||
target_file = max(wav_files, key=lambda p: p.stat().st_mtime)
|
||||
return target_file, meta
|
||||
@ -10,7 +10,7 @@ from bisect import bisect_right
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
|
||||
from unmix.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
|
||||
|
||||
|
||||
def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]:
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.pipeline.s6_chords import estimate_key, extract_chords_template, parse_harte_chord
|
||||
from unmix.pipeline.s6_chords import estimate_key, extract_chords_template, parse_harte_chord
|
||||
|
||||
|
||||
def test_parse_harte_chord_labels():
|
||||
|
||||
@ -1,8 +1,13 @@
|
||||
"""Unit tests for songsplit CLI."""
|
||||
"""Unit tests for unmix CLI."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from songsplit.cli import app
|
||||
from unmix.cli import app
|
||||
from unmix.config import Config
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
from unmix.sources import is_url
|
||||
|
||||
runner = CliRunner()
|
||||
|
||||
@ -18,8 +23,71 @@ def test_cli_help():
|
||||
def test_cli_doctor():
|
||||
result = runner.invoke(app, ["doctor"])
|
||||
assert result.exit_code == 0
|
||||
# Rich table output is printed to stderr as configured in cli.py
|
||||
output = result.stdout + result.stderr
|
||||
assert "Python" in output
|
||||
assert "ffmpeg" in output
|
||||
assert "Model Cache" in output
|
||||
|
||||
|
||||
def test_cli_is_url():
|
||||
assert is_url("https://www.youtube.com/watch?v=n8NIHnkZkeE") is True
|
||||
assert is_url("http://youtu.be/n8NIHnkZkeE") is True
|
||||
assert is_url("/home/user/song.mp3") is False
|
||||
assert is_url("relative/path/audio.wav") is False
|
||||
|
||||
|
||||
def test_cli_export_ultrastar_with_options(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
song_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
vocals = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=1.0,
|
||||
end=2.0,
|
||||
syllables=[VocalSyllable(text="Test", start=1.0, end=2.0, midi=60.0)],
|
||||
)
|
||||
]
|
||||
)
|
||||
(song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2))
|
||||
|
||||
result = runner.invoke(
|
||||
app,
|
||||
[
|
||||
"export-ultrastar",
|
||||
str(song_dir),
|
||||
"--title",
|
||||
"Custom Title",
|
||||
"--artist",
|
||||
"Custom Artist",
|
||||
"--lang",
|
||||
"en",
|
||||
],
|
||||
)
|
||||
assert result.exit_code == 0
|
||||
song_txt = song_dir / "export" / "song.txt"
|
||||
assert song_txt.exists()
|
||||
content = song_txt.read_text(encoding="utf-8")
|
||||
assert "#TITLE:Custom Title" in content
|
||||
assert "#ARTIST:Custom Artist" in content
|
||||
assert "#LANGUAGE:English" in content
|
||||
|
||||
|
||||
def test_config_device_detection(monkeypatch):
|
||||
# Test UNMIX_DEFAULT_DEVICE=cpu
|
||||
monkeypatch.setenv("UNMIX_DEFAULT_DEVICE", "cpu")
|
||||
monkeypatch.delenv("UNMIX_DEVICE_S2", raising=False)
|
||||
cfg = Config()
|
||||
assert cfg.get_device("s2_stems") == "cpu"
|
||||
assert cfg.get_device("s3_lyrics") == "cpu"
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
@ -5,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from songsplit.container import (
|
||||
from unmix.container import (
|
||||
SongpackSecurityError,
|
||||
build_manifest_for_dir,
|
||||
pack_songpack,
|
||||
|
||||
@ -5,16 +5,16 @@ from pathlib import Path
|
||||
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.container import pack_songpack, unpack_songpack
|
||||
from songsplit.export.ultrastar import parse_ultrastar
|
||||
from songsplit.schema.chords import ChordsDocument
|
||||
from songsplit.schema.manifest import ManifestDocument
|
||||
from songsplit.schema.meta import MetaDocument
|
||||
from songsplit.schema.strumming import StrummingDocument
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.schema.tracks import TrackDocument
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
from songsplit.schema.vocals_f0 import VocalsF0Document
|
||||
from unmix.container import pack_songpack, unpack_songpack
|
||||
from unmix.export.ultrastar import parse_ultrastar
|
||||
from unmix.schema.chords import ChordsDocument
|
||||
from unmix.schema.manifest import ManifestDocument
|
||||
from unmix.schema.meta import MetaDocument
|
||||
from unmix.schema.strumming import StrummingDocument
|
||||
from unmix.schema.tempo import TempoDocument
|
||||
from unmix.schema.tracks import TrackDocument
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
from unmix.schema.vocals_f0 import VocalsF0Document
|
||||
|
||||
|
||||
def test_demo_package_structure():
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import pyphen
|
||||
|
||||
from songsplit.pipeline.s3_lyrics import hyphenate_word, split_word_into_syllables_timed
|
||||
from unmix.pipeline.s3_lyrics import hyphenate_word, split_word_into_syllables_timed
|
||||
|
||||
|
||||
def test_hyphenate_word_german():
|
||||
@ -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
|
||||
|
||||
@ -1,10 +1,16 @@
|
||||
"""Unit tests for evaluation metrics (timing, pitch, WER)."""
|
||||
"""Unit tests for evaluation metrics (timing, pitch, pitch class, octave offset, WER)."""
|
||||
|
||||
import pytest
|
||||
|
||||
from songsplit.eval.metrics import evaluate_vocals, normalize_text_for_wer
|
||||
from songsplit.export.ultrastar import UltraStarNote, UltraStarSong
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
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
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def test_normalize_text_for_wer():
|
||||
@ -13,14 +19,50 @@ def test_normalize_text_for_wer():
|
||||
assert norm == "hallo welt wie gehts"
|
||||
|
||||
|
||||
def test_extract_words_and_wer_computation():
|
||||
# UltraStar notes format: word boundaries are marked by space after word
|
||||
ref_song = UltraStarSong(
|
||||
headers={"BPM": "120", "GAP": "1000"},
|
||||
lines=[
|
||||
[
|
||||
UltraStarNote(":", 0, 4, 0, "We ", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||
UltraStarNote(":", 4, 4, 2, "need ", start_sec=1.5, end_sec=2.0, midi=62.0),
|
||||
UltraStarNote(":", 8, 4, 4, "love", start_sec=2.0, end_sec=2.5, midi=64.0),
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
pred_doc = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=1.0,
|
||||
end=2.5,
|
||||
syllables=[
|
||||
VocalSyllable(text="We", start=1.0, end=1.5, midi=60.0, word_end=True),
|
||||
VocalSyllable(text="need", start=1.5, end=2.0, midi=62.0, word_end=True),
|
||||
VocalSyllable(text="love", start=2.0, end=2.5, midi=64.0, word_end=True),
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
ref_text = extract_text_from_reference(ref_song)
|
||||
pred_text = extract_text_from_vocals(pred_doc)
|
||||
assert ref_text == "We need love"
|
||||
assert pred_text == "We need love"
|
||||
|
||||
metrics = evaluate_vocals(pred_doc, ref_song)
|
||||
assert metrics["wer"] == 0.0
|
||||
|
||||
|
||||
def test_evaluate_vocals_perfect_match():
|
||||
# Ground truth: 2 syllables
|
||||
ref_song = UltraStarSong(
|
||||
headers={"BPM": "480", "GAP": "1000"},
|
||||
headers={"BPM": "120", "GAP": "1000"},
|
||||
lines=[
|
||||
[
|
||||
UltraStarNote(":", 0, 4, 0, "Hal", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||
UltraStarNote(":", 4, 4, 2, "lo", start_sec=1.5, end_sec=2.0, midi=62.0),
|
||||
UltraStarNote(":", 0, 4, 0, "Hal-", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||
UltraStarNote(":", 4, 4, 2, "lo ", start_sec=1.5, end_sec=2.0, midi=62.0),
|
||||
]
|
||||
],
|
||||
)
|
||||
@ -31,8 +73,8 @@ def test_evaluate_vocals_perfect_match():
|
||||
start=1.0,
|
||||
end=2.0,
|
||||
syllables=[
|
||||
VocalSyllable(text="Hal", start=1.0, end=1.5, midi=60.0),
|
||||
VocalSyllable(text="lo", start=1.5, end=2.0, midi=62.0),
|
||||
VocalSyllable(text="Hal-", start=1.0, end=1.5, midi=60.0),
|
||||
VocalSyllable(text="lo ", start=1.5, end=2.0, midi=62.0, word_end=True),
|
||||
],
|
||||
)
|
||||
]
|
||||
@ -41,41 +83,111 @@ def test_evaluate_vocals_perfect_match():
|
||||
metrics = evaluate_vocals(pred_doc, ref_song)
|
||||
assert metrics["mae_timing_ms"] == pytest.approx(0.0)
|
||||
assert metrics["median_timing_ms"] == pytest.approx(0.0)
|
||||
assert metrics["fraction_within_50ms"] == pytest.approx(1.0)
|
||||
assert metrics["fraction_within_100ms"] == pytest.approx(1.0)
|
||||
assert metrics["fraction_within_200ms"] == pytest.approx(1.0)
|
||||
assert metrics["duration_mae_ms"] == pytest.approx(0.0)
|
||||
assert metrics["strict_pitch_accuracy"] == pytest.approx(1.0)
|
||||
assert metrics["pitch_class_accuracy"] == pytest.approx(1.0)
|
||||
assert metrics["octave_equiv_pitch_accuracy"] == pytest.approx(1.0)
|
||||
assert metrics["median_octave_offset"] == pytest.approx(0.0)
|
||||
assert metrics["line_start_mae_ms"] == pytest.approx(0.0)
|
||||
assert metrics["line_end_mae_ms"] == pytest.approx(0.0)
|
||||
assert metrics["wer"] == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_evaluate_vocals_octave_error_and_timing_offset():
|
||||
ref_song = UltraStarSong(
|
||||
headers={"BPM": "480", "GAP": "1000"},
|
||||
headers={"BPM": "120", "GAP": "1000"},
|
||||
lines=[
|
||||
[
|
||||
# Note at 60.0, start 1.0
|
||||
# Note at 60.0 (C4), start 1.0, duration 0.5s
|
||||
UltraStarNote(":", 0, 4, 0, "Test", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
# Prediction is offset by 50ms and has octave error (72.0 vs 60.0)
|
||||
# Prediction is offset by 70ms, has octave error (-1 octave: 48.2 vs 60.0), duration 0.6s
|
||||
pred_doc = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=1.05,
|
||||
end=1.55,
|
||||
start=1.07,
|
||||
end=1.67,
|
||||
syllables=[
|
||||
VocalSyllable(text="Test", start=1.05, end=1.55, midi=72.0),
|
||||
VocalSyllable(text="Test", start=1.07, end=1.67, midi=48.2, word_end=True),
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
metrics = evaluate_vocals(pred_doc, ref_song)
|
||||
assert metrics["mae_timing_ms"] == pytest.approx(50.0, abs=1.0)
|
||||
assert metrics["mae_timing_ms"] == pytest.approx(70.0, abs=1.0)
|
||||
assert metrics["fraction_within_50ms"] == pytest.approx(0.0)
|
||||
assert metrics["fraction_within_100ms"] == pytest.approx(1.0)
|
||||
# Strict pitch should fail (72 != 60)
|
||||
assert metrics["fraction_within_200ms"] == pytest.approx(1.0)
|
||||
assert metrics["duration_mae_ms"] == pytest.approx(100.0, abs=1.0)
|
||||
|
||||
# Strict pitch should fail (48 != 60)
|
||||
assert metrics["strict_pitch_accuracy"] == pytest.approx(0.0)
|
||||
# Octave equivalent pitch should succeed (72 % 12 == 60 % 12)
|
||||
# Pitch class should succeed (48 % 12 == 60 % 12 == 0)
|
||||
assert metrics["pitch_class_accuracy"] == pytest.approx(1.0)
|
||||
assert metrics["octave_equiv_pitch_accuracy"] == pytest.approx(1.0)
|
||||
# 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)
|
||||
|
||||
|
||||
@ -8,7 +8,7 @@ import numpy as np
|
||||
import pytest
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline import PipelineContext, get_default_pipeline
|
||||
from unmix.pipeline import PipelineContext, get_default_pipeline
|
||||
|
||||
|
||||
def compute_snr(orig: np.ndarray, recon: np.ndarray) -> float:
|
||||
|
||||
@ -6,12 +6,12 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.eval.metrics import evaluate_vocals
|
||||
from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s4_pitch import PitchStage
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
from unmix.eval.metrics import evaluate_vocals
|
||||
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from unmix.pipeline import PipelineContext
|
||||
from unmix.pipeline.s4_pitch import PitchStage
|
||||
from unmix.schema.meta import MetaDocument, SourceFileInfo
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def test_m2_pitch_ultrastar_and_eval(tmp_path: Path):
|
||||
|
||||
@ -7,12 +7,12 @@ import numpy as np
|
||||
import pytest
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s5_tempo import TempoStage
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from unmix.pipeline import PipelineContext
|
||||
from unmix.pipeline.s5_tempo import TempoStage
|
||||
from unmix.schema.meta import MetaDocument, SourceFileInfo
|
||||
from unmix.schema.tempo import TempoDocument
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def test_m3_tempo_stage_and_click_track(tmp_path: Path):
|
||||
|
||||
@ -6,11 +6,11 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s6_chords import ChordsStage
|
||||
from songsplit.schema.chords import ChordsDocument
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
from unmix.pipeline import PipelineContext
|
||||
from unmix.pipeline.s6_chords import ChordsStage
|
||||
from unmix.schema.chords import ChordsDocument
|
||||
from unmix.schema.meta import MetaDocument, SourceFileInfo
|
||||
from unmix.schema.tempo import TempoAnchor, TempoDocument
|
||||
|
||||
|
||||
def test_m4_chords_stage_pipeline(tmp_path: Path):
|
||||
|
||||
@ -6,11 +6,11 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.pipeline import PipelineContext
|
||||
from songsplit.pipeline.s7_strumming import StrummingStage
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.strumming import StrummingDocument
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
from unmix.pipeline import PipelineContext
|
||||
from unmix.pipeline.s7_strumming import StrummingStage
|
||||
from unmix.schema.meta import MetaDocument, SourceFileInfo
|
||||
from unmix.schema.strumming import StrummingDocument
|
||||
from unmix.schema.tempo import TempoAnchor, TempoDocument
|
||||
|
||||
|
||||
def test_m5_strumming_pipeline(tmp_path: Path):
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from songsplit.pipeline.s4_pitch import correct_octave_errors, hz_to_midi
|
||||
from unmix.pipeline.s4_pitch import correct_octave_errors, hz_to_midi
|
||||
|
||||
|
||||
def test_hz_to_midi_standards():
|
||||
|
||||
@ -4,7 +4,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from songsplit.pipeline.runner import PipelineContext, PipelineRunner, Stage
|
||||
from unmix.pipeline.runner import PipelineContext, PipelineRunner, Stage
|
||||
|
||||
|
||||
class MockStageA(Stage):
|
||||
|
||||
@ -6,8 +6,8 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from songsplit.pipeline.runner import PipelineContext
|
||||
from songsplit.pipeline.s1_extract import ExtractStage, get_audio_duration
|
||||
from unmix.pipeline.runner import PipelineContext
|
||||
from unmix.pipeline.s1_extract import ExtractStage, get_audio_duration
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@ -4,8 +4,8 @@ from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.pipeline.runner import PipelineContext
|
||||
from songsplit.pipeline.s2_stems import StemsStage
|
||||
from unmix.pipeline.runner import PipelineContext
|
||||
from unmix.pipeline.s2_stems import StemsStage
|
||||
|
||||
|
||||
def calculate_snr(original: np.ndarray, reconstructed: np.ndarray) -> float:
|
||||
|
||||
@ -5,7 +5,7 @@ import json
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from songsplit.schema import (
|
||||
from unmix.schema import (
|
||||
ChordsDocument,
|
||||
MetaDocument,
|
||||
ModelInfo,
|
||||
@ -152,7 +152,7 @@ def test_strumming_document_roundtrip_and_spec_example():
|
||||
|
||||
|
||||
def test_manifest_document_roundtrip():
|
||||
from songsplit.schema.manifest import ManifestDocument, ManifestFileInfo, ManifestStageInfo
|
||||
from unmix.schema.manifest import ManifestDocument, ManifestFileInfo, ManifestStageInfo
|
||||
|
||||
manifest = ManifestDocument(
|
||||
created="2026-11-02T11:40:00+01:00",
|
||||
@ -177,7 +177,7 @@ def test_manifest_document_roundtrip():
|
||||
|
||||
|
||||
def test_tracks_document_kinds():
|
||||
from songsplit.schema.tracks import DrumEvent, NoteEvent, StrumEvent, StrumPattern, TrackDocument
|
||||
from unmix.schema.tracks import DrumEvent, NoteEvent, StrumEvent, StrumPattern, TrackDocument
|
||||
|
||||
# Strumming track
|
||||
t_strum = TrackDocument(
|
||||
@ -218,7 +218,7 @@ def test_tracks_document_kinds():
|
||||
|
||||
|
||||
def test_vocals_f0_document():
|
||||
from songsplit.schema.vocals_f0 import VocalsF0Document
|
||||
from unmix.schema.vocals_f0 import VocalsF0Document
|
||||
|
||||
f0 = VocalsF0Document(
|
||||
hop_sec=0.01,
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
import numpy as np
|
||||
|
||||
from songsplit.pipeline.s7_strumming import aggregate_strum_patterns, estimate_strum_direction
|
||||
from songsplit.schema.strumming import StrumEvent
|
||||
from unmix.pipeline.s7_strumming import aggregate_strum_patterns, estimate_strum_direction
|
||||
from unmix.schema.strumming import StrumEvent
|
||||
|
||||
|
||||
def test_estimate_strum_direction_phase_prior():
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
import pytest
|
||||
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
from songsplit.tempo import beat_to_sec, sec_to_beat
|
||||
from unmix.schema.tempo import TempoAnchor, TempoDocument
|
||||
from unmix.tempo import beat_to_sec, sec_to_beat
|
||||
|
||||
|
||||
def test_empty_tempo_map_raises_error():
|
||||
|
||||
@ -3,8 +3,8 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
|
||||
from songsplit.tempo import build_tempo_map_from_beats, generate_click_track
|
||||
from unmix.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
|
||||
from unmix.tempo import build_tempo_map_from_beats, generate_click_track
|
||||
|
||||
|
||||
def test_build_tempo_map_constant_tempo():
|
||||
|
||||
@ -2,10 +2,12 @@
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar
|
||||
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
import pytest
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_ultrastar_writer_and_reader(tmp_path: Path):
|
||||
@ -56,8 +58,10 @@ def test_ultrastar_writer_and_reader(tmp_path: Path):
|
||||
content = txt_path.read_text(encoding="utf-8")
|
||||
assert "#TITLE:Test Song" in content
|
||||
assert "#ARTIST:Test Artist" in content
|
||||
assert "#BPM:480.00" in content # 120 * 4 = 480
|
||||
assert "#BPM:120.00" in content
|
||||
assert "#GAP:500" in content # 0.5s = 500 ms
|
||||
assert "#LANGUAGE:German" in content
|
||||
assert "stems/vocals.wav" not in content
|
||||
assert "E" in content
|
||||
|
||||
# 5. Parse back using parse_ultrastar
|
||||
@ -72,10 +76,123 @@ def test_ultrastar_writer_and_reader(tmp_path: Path):
|
||||
assert len(line1) == 2
|
||||
assert line1[0].text == "Hal-"
|
||||
assert line1[0].midi == 60.0
|
||||
assert line1[0].start_sec == pytest.approx(0.5, abs=0.02)
|
||||
assert line1[0].end_sec == pytest.approx(1.0, abs=0.02)
|
||||
|
||||
assert line1[1].text == "lo "
|
||||
assert line1[1].midi == 62.0
|
||||
assert line1[1].start_sec == pytest.approx(1.0, abs=0.02)
|
||||
assert line1[1].end_sec == pytest.approx(2.0, abs=0.02)
|
||||
|
||||
line2 = parsed.lines[1]
|
||||
assert len(line2) == 1
|
||||
assert line2[0].text == "Welt"
|
||||
assert line2[0].midi == 64.0
|
||||
assert line2[0].start_sec == pytest.approx(3.0, abs=0.02)
|
||||
assert line2[0].end_sec == pytest.approx(4.5, abs=0.02)
|
||||
|
||||
|
||||
def test_ultrastar_metadata_and_language_english(tmp_path: Path):
|
||||
song_dir = tmp_path / "song_pkg"
|
||||
song_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
meta = MetaDocument(
|
||||
title="Chasing Cars",
|
||||
artist="Snow Patrol",
|
||||
language="en",
|
||||
duration_sec=269.0,
|
||||
source_file=SourceFileInfo(
|
||||
filename="Chasing_Cars.mp3", path="/tmp/Chasing_Cars.mp3", sha256="abc", size_bytes=100
|
||||
),
|
||||
created_at="2026-11-02T10:00:00Z",
|
||||
)
|
||||
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
|
||||
|
||||
# Tempo anchor starting at 65.34s (reproducing Chasing Cars test scenario)
|
||||
tempo = TempoDocument(anchors=[TempoAnchor(sec=65.34, beat=0.0, bpm=104.0)])
|
||||
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
|
||||
|
||||
# Vocals starting at 7.08s, ending at 258.7s
|
||||
vocals = VocalsDocument(
|
||||
lines=[
|
||||
VocalLine(
|
||||
start=7.08,
|
||||
end=10.0,
|
||||
syllables=[
|
||||
VocalSyllable(text="I'll ", start=7.08, end=8.0, midi=52.0),
|
||||
VocalSyllable(text="do ", start=8.0, end=9.0, midi=52.0),
|
||||
VocalSyllable(text="it ", start=9.0, end=10.0, midi=52.0),
|
||||
],
|
||||
),
|
||||
VocalLine(
|
||||
start=250.0,
|
||||
end=258.7,
|
||||
syllables=[
|
||||
VocalSyllable(text="cars", start=250.0, end=258.7, midi=50.0),
|
||||
],
|
||||
),
|
||||
]
|
||||
)
|
||||
(song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2))
|
||||
|
||||
txt_path = export_ultrastar(song_dir)
|
||||
content = txt_path.read_text(encoding="utf-8")
|
||||
|
||||
assert "#TITLE:Chasing Cars" in content
|
||||
assert "#ARTIST:Snow Patrol" in content
|
||||
assert "#LANGUAGE:English" in content
|
||||
assert "#MP3:Chasing_Cars.mp3" in content
|
||||
assert "#GAP:7080" in content
|
||||
assert "#BPM:104.00" in content
|
||||
|
||||
parsed = parse_ultrastar(txt_path)
|
||||
assert parsed.bpm == 104.0
|
||||
assert parsed.gap_ms == 7080.0
|
||||
# First note must be at 7.08s
|
||||
assert parsed.lines[0][0].start_sec == pytest.approx(7.08, abs=0.05)
|
||||
# Last note must be around 250.0s to 258.7s (NOT compressed to 52s!)
|
||||
# Quantization resolution at 104 BPM is 15 / 104 = 0.144s per tick
|
||||
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"
|
||||
|
||||
|
||||
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"
|
||||
@ -1,10 +1,10 @@
|
||||
# Umsetzungskonzept: songsplit (Analyse-Tool)
|
||||
# Umsetzungskonzept: unmix (Analyse-Tool)
|
||||
|
||||
Arbeitsanweisung für einen KI-Coding-Agenten. Alles hier ist verbindlich, sofern nicht ausdrücklich als "offen" markiert.
|
||||
|
||||
## 1. Ziel
|
||||
|
||||
`songsplit` zerlegt einen Song (Video oder Audio) in ein **Song-Paket**: getrennte Stems, Text mit Wort-/Silben-Timing, Gesangsnoten, Tempo-Map, Akkorde und Strumming-Vorschlag. Das Paket wird später von einer Rust-Gesangstrainer-App und einem Editor gelesen.
|
||||
`unmix` zerlegt einen Song (Video oder Audio) in ein **Song-Paket**: getrennte Stems, Text mit Wort-/Silben-Timing, Gesangsnoten, Tempo-Map, Akkorde und Strumming-Vorschlag. Das Paket wird später von einer Rust-Gesangstrainer-App und einem Editor gelesen.
|
||||
|
||||
**Im Scope:** Analyse-Pipeline, Song-Paket-Format, UltraStar-Export (später auch Import als Testreferenz), Qualitätsmessung.
|
||||
**Nicht im Scope:** Editor, Pitch-Scoring live, Wiedergabe, GUI.
|
||||
@ -22,10 +22,10 @@ Arbeitsanweisung für einen KI-Coding-Agenten. Alles hier ist verbindlich, sofer
|
||||
## 3. Projektstruktur
|
||||
|
||||
```
|
||||
songsplit/
|
||||
unmix/
|
||||
pyproject.toml
|
||||
README.md
|
||||
src/songsplit/
|
||||
src/unmix/
|
||||
cli.py # typer-App
|
||||
config.py # Modellwahl, Devices, Pfade
|
||||
schema/ # pydantic-Modelle (siehe 4)
|
||||
@ -149,11 +149,11 @@ Reihenfolge der Abhängigkeiten: 1 → 2 → (3 → 4) und (5 → 6, 7). Stufen
|
||||
## 7. CLI
|
||||
|
||||
```
|
||||
songsplit analyze <datei> -o <ordner> [--lang de] [--stems 4|6] [--quality fast|best]
|
||||
songsplit analyze <datei> -o <ordner> --stage chords [--force]
|
||||
songsplit export-ultrastar <ordner>
|
||||
songsplit eval <testset.toml>
|
||||
songsplit doctor # prüft ffmpeg, Modelle, GPUs, Versionen
|
||||
unmix analyze <datei> -o <ordner> [--lang de] [--stems 4|6] [--quality fast|best]
|
||||
unmix analyze <datei> -o <ordner> --stage chords [--force]
|
||||
unmix export-ultrastar <ordner>
|
||||
unmix eval <testset.toml>
|
||||
unmix doctor # prüft ffmpeg, Modelle, GPUs, Versionen
|
||||
```
|
||||
|
||||
## 8. Qualitätsmessung (Eval)
|
||||
|
||||
142
uv.lock
generated
142
uv.lock
generated
@ -54,11 +54,6 @@ wheels = [
|
||||
name = "av"
|
||||
version = "18.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"python_full_version < '3.12' and platform_machine == 'x86_64' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.12' and sys_platform != 'darwin'",
|
||||
"python_full_version < '3.12' and platform_machine != 'x86_64' and sys_platform == 'darwin'",
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8d/f4/f22114d30d3435e38c6af2b4870f37b864403dca6ae7af747a289ce0a18e/av-18.1.0.tar.gz", hash = "sha256:47bfc286e1bc9de7ab4681fc2b575cd2460a66919d31ffe1bd5aa54fae531a28", size = 4451061, upload-time = "2026-08-12T22:28:18.761Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/05/d4/d7cdc8bff143c17a6d35924375ae28dd692cacde38700a7d419fde54f44a/av-18.1.0-cp311-abi3-macosx_11_0_x86_64.whl", hash = "sha256:ae75d8bb6467895ed1f8572ededf7ffa49eac07f6e483222f5d7d62a41d12f04", size = 22546147, upload-time = "2026-08-12T22:27:11.851Z" },
|
||||
@ -72,28 +67,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/ad/a3135884c5753b09773176b97201ae602f67ad14206c395ff838d66bf9b0/av-18.1.0-cp311-abi3-win_arm64.whl", hash = "sha256:5509ec12aaa19fd6601de13cfa6f4cdad450da07982118510592875d970454d6", size = 20257584, upload-time = "2026-08-12T22:27:38.472Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "av"
|
||||
version = "19.0.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.12' and platform_machine == 'x86_64' and sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.12' and sys_platform != 'darwin'",
|
||||
"python_full_version >= '3.12' and platform_machine != 'x86_64' and sys_platform == 'darwin'",
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/23/01/76b6bf563fe907597cf58f10d10168e93fe588b6db9f2658db87e87efa7e/av-19.0.2.tar.gz", hash = "sha256:bebbc52598886480f4d861c575dc2b020785d6c04e1308680ddcc545e1b94c66", size = 4277157, upload-time = "2026-10-21T03:45:30.799Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4a/2f/f51f37820741134516e841053d5ecebf6350fbd451adcbff9ead96aa1244/av-19.0.2-cp312-abi3-macosx_11_0_x86_64.whl", hash = "sha256:f5f7bcf987567cd3f9b01f1c375c59bf59d8a5b98c9c5c154aeda7a11e0c5dce", size = 22627374, upload-time = "2026-10-21T03:44:28.296Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/42/067d0bcd2c07103f18cc23b510a8289dd80330e984c49d51ce0bafcee017/av-19.0.2-cp312-abi3-macosx_14_0_arm64.whl", hash = "sha256:b0dff6dfcc6ff9944fbbff15bc4ee2d90a2c1695d493bdea96e86f48823e9feb", size = 18556422, upload-time = "2026-10-21T03:44:31.267Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/de/0c/448f89f76cf5e4da35dd6294a1e8155b75daa8839f2f2fa353775855d152/av-19.0.2-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:04c8e412642c652cb2b1997a9cb2114546ee7d894600c631f4be8ceb26a0d0d2", size = 32683287, upload-time = "2026-10-21T03:44:34.588Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e1/7f/9f1237feb894afa472ef834aa1fbfe4d6398f28dc7e86a1b418650204c36/av-19.0.2-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:9c1da7aad0fa6c13b4a5c1e7985be0d13f8526a96284573acaf3d55ead6d3fe8", size = 34990159, upload-time = "2026-10-21T03:44:37.637Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f1/b5/1bde0e54e525d88ad8f5becae657f8142543fd3be9d10b72141f041ca868/av-19.0.2-cp312-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9d4f9f78c0ce1f20deb72626fdb3c723757f61a8cd6fbb7dd44d9401884a91fd", size = 44422922, upload-time = "2026-10-21T03:44:41.847Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/08/21/65997929fa4dd7c20f64e742aa87205a8d65485718a2ab51633756078e83/av-19.0.2-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:dfe7af5aa8243afd5d4778f85ad1a7c948e37fad272869da1f8f93f8d57fa7ad", size = 33754699, upload-time = "2026-10-21T03:44:45.772Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/30/44/4de8c0ff5a5e25ceb0841efc0a4a7530a22d61800bc0cc19a1d03aa04358/av-19.0.2-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:44d3faae747cf04a33f39db8ae983ff3d93adc864ee663bc186b25b686803c3e", size = 36014845, upload-time = "2026-10-21T03:44:49.64Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/32/5a/743a83666ded197df8b9957e2800bef9a39d52b23be2ca211bbd14b5fb22/av-19.0.2-cp312-abi3-win_amd64.whl", hash = "sha256:3ce5a1d7b916d13c16ac58f1756f0fee4af2d53f02bc1403e18550b50d375a22", size = 28150949, upload-time = "2026-10-21T03:44:53.434Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/fe/e79d786628d9c0428f72214dbe4b90ee0c625e04d552a604d5235ff35515/av-19.0.2-cp312-abi3-win_arm64.whl", hash = "sha256:79a277b077e3768a0ea9f881ca0b3bc96d4135a8d3a7a579938adb58718d0dfd", size = 20708023, upload-time = "2026-10-21T03:44:56.435Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "beat-this"
|
||||
version = "1.1.0"
|
||||
@ -402,8 +375,7 @@ name = "faster-whisper"
|
||||
version = "1.2.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "av", version = "18.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
|
||||
{ name = "av", version = "19.0.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "av" },
|
||||
{ name = "ctranslate2" },
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "onnxruntime" },
|
||||
@ -1368,61 +1340,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "songsplit"
|
||||
version = "0.1.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "beat-this" },
|
||||
{ name = "chord-extractor" },
|
||||
{ name = "demucs", version = "4.0.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'" },
|
||||
{ name = "demucs", version = "4.1.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
|
||||
{ name = "faster-whisper" },
|
||||
{ name = "jiwer" },
|
||||
{ name = "julius" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "pyphen" },
|
||||
{ name = "rich" },
|
||||
{ name = "scipy" },
|
||||
{ name = "soundfile" },
|
||||
{ name = "torch", version = "2.15.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine != 'x86_64' and sys_platform == 'darwin'" },
|
||||
{ name = "torch", version = "2.15.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine == 'x86_64' or sys_platform != 'darwin'" },
|
||||
{ name = "torchaudio", version = "2.11.1", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine != 'x86_64' and sys_platform == 'darwin'" },
|
||||
{ name = "torchaudio", version = "2.11.1+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine == 'x86_64' or sys_platform != 'darwin'" },
|
||||
{ name = "torchcrepe" },
|
||||
{ name = "typer" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
dev = [
|
||||
{ name = "pytest" },
|
||||
{ name = "pytest-cov" },
|
||||
{ name = "ruff" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "beat-this", specifier = ">=1.1.0" },
|
||||
{ name = "chord-extractor", specifier = ">=0.1.3" },
|
||||
{ name = "demucs", specifier = ">=4.0.0" },
|
||||
{ name = "faster-whisper", specifier = ">=1.0.0" },
|
||||
{ name = "jiwer", specifier = ">=3.0.0" },
|
||||
{ name = "julius", specifier = ">=0.2.7" },
|
||||
{ name = "pydantic", specifier = ">=2.7.0" },
|
||||
{ name = "pyphen", specifier = ">=0.14.0" },
|
||||
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },
|
||||
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=5.0.0" },
|
||||
{ name = "rich", specifier = ">=13.7.0" },
|
||||
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.4.0" },
|
||||
{ name = "scipy", specifier = ">=1.12.0" },
|
||||
{ name = "soundfile", specifier = ">=0.12.0" },
|
||||
{ name = "torch", specifier = ">=2.4.0", index = "https://download.pytorch.org/whl/cpu" },
|
||||
{ name = "torchaudio", specifier = ">=2.4.0", index = "https://download.pytorch.org/whl/cpu" },
|
||||
{ name = "torchcrepe", specifier = ">=0.0.23" },
|
||||
{ name = "typer", specifier = ">=0.12.0" },
|
||||
]
|
||||
provides-extras = ["dev"]
|
||||
|
||||
[[package]]
|
||||
name = "soundfile"
|
||||
version = "0.14.0"
|
||||
@ -1715,6 +1632,63 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unmix"
|
||||
version = "0.1.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "av" },
|
||||
{ name = "beat-this" },
|
||||
{ name = "chord-extractor" },
|
||||
{ name = "demucs", version = "4.0.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'" },
|
||||
{ name = "demucs", version = "4.1.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
|
||||
{ name = "faster-whisper" },
|
||||
{ name = "jiwer" },
|
||||
{ name = "julius" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "pyphen" },
|
||||
{ name = "rich" },
|
||||
{ name = "scipy" },
|
||||
{ name = "soundfile" },
|
||||
{ name = "torch", version = "2.15.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine != 'x86_64' and sys_platform == 'darwin'" },
|
||||
{ name = "torch", version = "2.15.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine == 'x86_64' or sys_platform != 'darwin'" },
|
||||
{ name = "torchaudio", version = "2.11.1", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine != 'x86_64' and sys_platform == 'darwin'" },
|
||||
{ name = "torchaudio", version = "2.11.1+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "platform_machine == 'x86_64' or sys_platform != 'darwin'" },
|
||||
{ name = "torchcrepe" },
|
||||
{ name = "typer" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
dev = [
|
||||
{ name = "pytest" },
|
||||
{ name = "pytest-cov" },
|
||||
{ name = "ruff" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "av", specifier = "==18.1.0" },
|
||||
{ name = "beat-this", specifier = ">=1.1.0" },
|
||||
{ name = "chord-extractor", specifier = ">=0.1.3" },
|
||||
{ name = "demucs", specifier = ">=4.0.0" },
|
||||
{ name = "faster-whisper", specifier = ">=1.0.0" },
|
||||
{ name = "jiwer", specifier = ">=3.0.0" },
|
||||
{ name = "julius", specifier = ">=0.2.7" },
|
||||
{ name = "pydantic", specifier = ">=2.7.0" },
|
||||
{ name = "pyphen", specifier = ">=0.14.0" },
|
||||
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },
|
||||
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=5.0.0" },
|
||||
{ name = "rich", specifier = ">=13.7.0" },
|
||||
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.4.0" },
|
||||
{ name = "scipy", specifier = ">=1.12.0" },
|
||||
{ name = "soundfile", specifier = ">=0.12.0" },
|
||||
{ name = "torch", specifier = ">=2.4.0", index = "https://download.pytorch.org/whl/cpu" },
|
||||
{ name = "torchaudio", specifier = ">=2.4.0", index = "https://download.pytorch.org/whl/cpu" },
|
||||
{ name = "torchcrepe", specifier = ">=0.0.23" },
|
||||
{ name = "typer", specifier = ">=0.12.0" },
|
||||
]
|
||||
provides-extras = ["dev"]
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
version = "2.8.0"
|
||||
|
||||
Reference in New Issue
Block a user