49 Commits

Author SHA1 Message Date
d783221fce docs(readme): honest status, what works and measured results
Replaces the outdated milestone claim with the current state, a table of what
works and what does not, and measured numbers for the audio-only and lyrics
modes on the nine-song testset. Adds the evaluation command to the feature list.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 12:05:49 +01:00
c761a244d8 feat(lyrics): fetch lyrics text from LRCLIB (--lyrics-from lrclib)
Text only; the audio alignment is unchanged. The release is chosen by length
(within 5 s of the audio) and live/acoustic/remix/karaoke versions rank last.
The chosen release is recorded in meta.json as lyrics_source.
Local use only: lyrics are copyrighted and must not be redistributed.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 11:55:56 +01:00
c4613d5616 docs(readme): describe integration with other programs
File contract (required vs optional files), CLI usage with --json and exit codes,
Python usage and schema versioning.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 07:57:07 +01:00
5c8c2835fd docs(readme): describe the three input modes and lyrics testset option
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 07:54:26 +01:00
bcae76279b feat(modes): three explicit input modes (audio, --ultrastar, --lyrics)
- --ultrastar <txt> takes notes and timings of the file as the result (alias of --reference)
- --lyrics <txt> aligns plain lyrics to the vocals with CTC forced alignment (en, de)
- --lyrics and --ultrastar are mutually exclusive; UltraStar files are rejected by --lyrics
- meta.vocals_source is whisper | lyrics_aligned | reference_ultrastar
- fix: a later run in the same folder no longer evaluates the ground truth against itself;
  the AI result is backed up in .cache/vocals_ai.json and the pitch cache is invalidated
- eval: per-song lyrics = "reference" aligns the reference text without its timings

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 07:53:23 +01:00
861f6a29f2 fix(ultrastar): keep word boundaries of the leading-space convention
parse_ultrastar swallowed the leading space that marks a word start in some files
(e.g. Uriah Heep - Lady In Black), gluing a whole line into one 'word' and inflating
the WER (4.42 -> 0.43). Leading spaces are now normalised to a trailing space on the
previous note.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 13:29:25 +01:00
904ce6253f feat(pitch): end lines at the end of the strictly voiced run after the last word
Line ends follow CREPE periodicity >= 0.7 after the last syllable. Gaps up to 0.1 s
are always bridged, gaps up to 0.3 s only if voicing resumes for >= 0.3 s (held note
with dropout, not breath or consonant). Capped at the next line start.

Line-end hit rate (<= 0.3 s) over 5 songs: 31% -> 41%, MAE 1.12 s -> 0.98 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:38:15 +01:00
3fdd639f47 chore: ignore all local testset configs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 08:22:21 +01:00
4024b74953 feat(lyrics): split Whisper segments into singable lines
Segments are cut at word pauses > 0.6 s and long lines at their largest gap.
Mistimed single leading/trailing words are merged into the adjacent line.
Raw Whisper segments are cached in whisper_segments.json so line building
can be A/B tested without re-running Whisper.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 08:09:03 +01:00
769910286f feat(eval): show octave-corrected note accuracy in report and CLI
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:08:43 +01:00
c73ad8d66b feat(pitch,lyrics): tune pipeline heuristics from dual-track learnings
- Increase melisma pitch jump threshold to 1.6 st to prevent vibrato over-splitting
- Add transient consonant attack snapping in snap_onset
- Add continuous voicing extension for sustained rock vowels
- Deduplicate rapid hallucinated line repetitions in Whisper output
- Add automatic global octave transposition alignment in ultrastar_to_vocals
- Cache CREPE F0 frames in crepe_f0_<model>.npz for rapid iterative tuning
- Accurately compute octave-aligned pitch accuracy in evaluate_vocals
2026-11-04 00:33:50 +01:00
dcde066772 feat(dual-track): ground-truth packaging, training diff and import-ultrastar 2026-11-03 22:59:06 +01:00
c93d2c696e feat(eval): note onset snapping, melisma segmentation and youtube audio retrieval 2026-11-03 22:03:56 +01:00
d4745a48e0 feat(cli): add auto-export, --reference eval, YouTube URL source via yt-dlp, and README 2026-11-03 20:38:17 +01:00
8ea78914ac fix(stability): pin av 18.1.0, add CPU device fallback, and reset runner failure status 2026-11-03 20:37:41 +01:00
6b3c82738c fix(export): correct UltraStar BPM scaling, time axis linear mapping, and metadata 2026-11-03 20:37:24 +01:00
cb3047ddae fix(eval): correct UltraStar tick duration, word boundary WER, and pitch metrics 2026-11-03 20:37:04 +01:00
58ff3fe59a feat(cli): add --version flag to unmix CLI 2026-11-02 14:46:07 +01:00
c327d5c4c4 refactor: rename project, package, and CLI from songsplit to unmix 2026-11-02 14:43:31 +01:00
7bbc6b78df docs: rewrite README following pragmatic README template and add MIT license 2026-11-02 12:56:50 +01:00
999a3c3a9d docs: update format documentation and README for songpack v1.0 2026-11-02 12:22:14 +01:00
af11f507cf feat(example): upgrade demo song package and test suite to songpack v1.0 2026-11-02 12:22:11 +01:00
6d7d88e799 feat(cli): add pack and unpack commands for .songpack container with Section 12 security 2026-11-02 12:22:07 +01:00
e73c4ec328 feat(export): align UltraStar export with songpack spec (export/song.txt, word boundaries, headers) 2026-11-02 12:22:03 +01:00
fd17b63c7a feat(pipeline): modularize stage 7 into s7_tracks and support track sub-stages 2026-11-02 12:21:59 +01:00
6428e8be7d feat(container): implement songpack pack and secure unpack per spec 2026-11-02 12:10:02 +01:00
2a2da717e8 feat(schema): implement songpack v1.0 schemas (manifest, tracks, vocals_f0, editable items) 2026-11-02 12:08:36 +01:00
a874afe7cd docs: adopt updated concept and add songpack-spec v1.0 2026-11-02 12:05:55 +01:00
bc62fa1c56 docs: mark M6 hardening completed in README 2026-11-02 11:34:28 +01:00
a6dd0a649a feat(example): add synthetic demo song package and test suite 2026-11-02 11:34:17 +01:00
44311d007f feat(pipeline): add structured logging to pipeline runner 2026-11-02 11:31:15 +01:00
9db639ea9e docs(format): add song-paket v1.0 format specification 2026-11-02 11:31:13 +01:00
f1d55c4bcb docs: update README with M5 completion status 2026-11-02 11:20:33 +01:00
760bad7435 test: add unit and integration tests for M5 strumming analysis and beat quantization 2026-11-02 11:20:33 +01:00
7ec6b3274b feat(strumming): implement stage 7 onset detection, direction estimation, and pattern aggregation 2026-11-02 11:20:33 +01:00
8d366327e6 docs: update README with M4 completion status 2026-11-02 11:00:06 +01:00
fcc1cd2426 test: add unit and integration tests for M4 chord parsing, template matching, and pipeline 2026-11-02 11:00:06 +01:00
983102b588 feat(chords): implement stage 6 beat-synchronous chord recognition and key detection 2026-11-02 11:00:06 +01:00
a7dedd4306 docs: update README with M3 completion status 2026-11-02 10:53:19 +01:00
fac85bcd56 test: add integration test for M3 tempo stage and UltraStar BPM synchronization 2026-11-02 10:53:19 +01:00
887bd4a3e9 feat(pipeline): implement stage 5 beat and downbeat tracking via beat_this 2026-11-02 10:53:19 +01:00
cc5e2fe628 feat(tempo): implement tempo map building from beats and click track generator 2026-11-02 10:53:19 +01:00
6eb02fe576 docs: update README with M2 completion status 2026-11-02 10:42:10 +01:00
cdc47bc85a test: add end-to-end integration test for M2 vocals pipeline and eval 2026-11-02 10:42:10 +01:00
f1736caff5 feat(eval): implement evaluation metrics (timing MAE, pitch accuracy, WER) and runner 2026-11-02 10:42:10 +01:00
cd6f2a8fa3 feat(export): implement UltraStar writer and reader for song.txt 2026-11-02 10:42:10 +01:00
ac9831d195 feat(pitch): implement stage 4 torchcrepe pitch tracking with octave error correction 2026-11-02 10:42:10 +01:00
acb1411aa1 feat(lyrics): implement stage 3 Whisper transcription and pyphen hyphenation 2026-11-02 10:42:10 +01:00
4fbd741f4c fix(stems): optimize Demucs chunking and prevent dimension mismatch 2026-11-02 10:42:10 +01:00
101 changed files with 9406 additions and 915 deletions

10
.gitignore vendored
View File

@ -41,6 +41,16 @@ 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
# IDE
.idea/
.vscode/

21
LICENSE Normal file
View 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.

325
README.md
View File

@ -1,53 +1,312 @@
# 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`, Entwicklungsstand. Die Pipeline (Stufen 1 bis 7), das [Songpack-Format v1.0](songpack-spec.md), der UltraStar-Export und die Auswertung gegen Referenzen sind implementiert. Die Testsuite umfasst 87 Tests und läuft grün.
Die Qualität ist **nicht** die eines fertigen Karaoke-Produkts. Die Zahlen unten stammen aus Messungen an neun Songs mit handgetimten UltraStar-Referenzen und sind ein Ausgangspunkt, keine Garantie.
Getestet auf: Linux (CachyOS / Arch / Ubuntu, Kernel 6.13+, AMD Ryzen AI 9 / Strix Point, ROCm / CPU). Funktioniert dank standardisiertem PyTorch/Soundfile-Stack auf allen Plattformen mit Python 3.12 und `ffmpeg`.
### Was funktioniert, was nicht
| Bereich | Stand |
| :--- | :--- |
| Stems, Tempo, Akkorde, Strumming | läuft, nicht gegen Referenzen gemessen |
| Text und Silben (Modus 1, Whisper) | Zeilen fehlen oft, lange Vokalisen (z. B. „ah ah ah") schlecht erkannt |
| Text und Silben (Modus 3, mit Text) | Zeilen vollständig, Zeitfehler meist unter 0,5 s |
| Tonhöhe (CREPE) | Noten grob richtig, aber Oktavlage der Referenzen weicht oft ab, strikte Treffer deshalb niedrig |
| UltraStar-Export | verlustbehaftet: Tonhöhe auf Halbtöne gerundet, Zeiten an BPM gebunden |
| Sprachen für Textausrichtung | Englisch und Deutsch |
### Messwerte (neun Songs, echte Pipeline)
| Messung | Modus 1 (Whisper) | Modus 3 (mit Text) |
| :--- | :--- | :--- |
| Zeilenstarts innerhalb 200 ms | 42 % | 71 % |
| Zeilenstarts innerhalb 500 ms | 53 % | 80 % |
| Zeilenenden innerhalb 300 ms | 28 % | 66 % |
| Gefundene Zeilen | teils deutlich weniger als in der Referenz | alle |
| Notenzeit-Abweichung (MAE) | ca. 95–225 ms | ca. 85–135 ms |
| Noten, oktav-korrigiert | 40–71 % | 43–75 % |
Die Referenzen sind handgetimte UltraStar-Dateien. Sie sind die Messlatte, aber selbst nicht fehlerfrei. Die Auswahl der Testsongs ist klein: die Regeln für Zeilenbildung und Zeilenenden wurden zum Teil an denselben Songs entwickelt, auf denen sie bewertet wurden.
## Before you use it
**Rechenleistung & VRAM:** Die Ausführung im Qualitätsmodus `best` nutzt speicherintensive Modelle (`htdemucs_ft`, `whisper-large-v3`, `torchcrepe-full`). Auf Systemen mit weniger als 8 GB VRAM oder bei reiner CPU-Nutzung empfiehlt sich der Modus `--quality fast` (mit Modell-Chunking) oder das gezielte Ausführen einzelner Teilstufen über `--stage <name>`.
**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 chords [--force]
# 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).
- [ ] **M2 – Gesang**: Stufen 3 (Whisper+WhisperX) und 4 (torchcrepe), UltraStar-Writer, Eval-Gerüst.
- [ ] **M3 – Tempo-Map**: Stufe 5 (beat_this).
- [ ] **M4 – Akkorde**: Stufe 6 (Chordino / Transformer).
- [ ] **M5 – Strumming**: Stufe 7 (librosa Onsets / Strumming-Muster).
- [ ] **M6 – Härtung**: Fehlerbehandlung, Logging, Dokumentation, Beispielpaket.
`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** | Drei Eingabemodi: Whisper-Transkription (Modus 1), Ausrichtung eines vorhandenen Textes per CTC-Forced-Alignment (`--lyrics`, `--lyrics-from lrclib`) oder Übernahme einer UltraStar-Datei (`--ultrastar`). Silbentrennung via `pyphen` mit proportionaler Zeitverteilung. |
| **Tonhöhenerkennung (CREPE)** | Frame-genaue F0-Extraktion mit Hop-Size 10 ms, Medianberechnung pro Silbe, Voicing-Filterung und Oktavfehler-Korrektur. |
| **Tempo-Map & Beat-Grid** | Beat- und Downbeat-Tracking (`beat_this`), Erkennung von Taktarten (4/4, 3/4, 6/8) und Synthese von Metronom-Klickspuren. |
| **Akkorderkennung** | Harte-Notation (`C`, `Am`, `G7`, `Dsus4`), Quantisierung auf das Beat-Raster und Tonarterkennung (Krumhansl-Schmuckler). |
| **Instrumenten-Tracks (Strumming)** | Erkennung von Anschlägen (Onsets) auf der Gitarrenspur, Down/Up-Richtungsvorschlag und Muster-Kompression (`D . D U . U D U`). |
| **UltraStar Deluxe Export** | Erzeugt `song.txt` für UltraStar-kompatible Software (`export/song.txt`). Verlustbehaftet, siehe Tabelle oben. |
| **Auswertung gegen Referenzen** | `unmix eval` misst Zeiten, Tonhöhe, Zeilen und Wortfehler gegen UltraStar-Dateien und erzeugt einen Bericht. |
| **Sicherer Songpack-Container** | Packt und entpackt `.songpack`-Container mit Whitelist-Filterung, Pfadtraversierungs- und Zip-Bomben-Schutz. |
## How it works
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
# Modus 2: UltraStar-Datei (übernimmt Noten und Zeiten, vergleicht zusätzlich mit der KI-Vorhersage)
unmix analyze song.mp3 -o output_song/ --lang en --ultrastar ground_truth_song.txt
# Modus 3: nur Text (richtet den Text per Forced Alignment am Gesang aus, statt Whisper)
unmix analyze song.mp3 -o output_song/ --lang en --lyrics lyrics.txt
# Modus 3 mit Text von LRCLIB (nur lokal nutzen, Texte nicht weitergeben)
unmix analyze song.mp3 -o output_song/ --lang en --lyrics-from lrclib --artist "Snow Patrol" --title "Chasing Cars"
# Schneller Direkt-Import (übernimmt UltraStar-Gesang, rechnet nur Stems/Akkorde/Tempo)
unmix import-ultrastar ground_truth_song.txt song.mp3 -o output_song/
```
### Die drei Eingabemodi
Jede Analyse läuft in genau einem Modus. Der Modus steht danach in `meta.json` unter `vocals_source`.
| Modus | Aufruf | Quelle des Gesangs (`vocals.json`) | `vocals_source` |
|---|---|---|---|
| 1. Nur Audio/Video | `unmix analyze song.mp3 -o out --lang en` | Whisper (Text) + CREPE (Tonhöhe) | `whisper` |
| 2. UltraStar-Datei | `--ultrastar song.txt` | Noten und Zeiten der Datei, auf das Audio eingerastet | `reference_ultrastar` |
| 3. Nur Text | `--lyrics lyrics.txt` | Text per Forced Alignment am Gesang ausgerichtet, Tonhöhe weiterhin CREPE | `lyrics_aligned` |
- **Modus 2** ist die Messlatte: Zusätzlich zum Songpack entsteht `training_diff.json` mit dem Vergleich der KI-Vorhersage Note für Note (systematischer Timing- und Dauern-Drift, übersehene Noten, Melismen). Die KI-Vorhersage wird dafür in `.cache/vocals_ai.json` gesichert, damit ein späterer Lauf im selben Ordner nicht die Referenz mit sich selbst vergleicht.
- **Modus 3** braucht eine Textdatei, eine Zeile pro gesungener Zeile. Abschnittsmarker wie `[Verse 1]` werden ignoriert. Auch eine UltraStar-Datei ist als Text möglich, dann werden nur Text und Zeilenumbrüche übernommen, nicht die Zeiten. Unterstützt sind Englisch und Deutsch. Beim ersten Lauf lädt torchaudio ein Alignment-Modell (ca. 360 MB).
- Der Text kommt entweder aus einer Datei (`--lyrics`) oder von [LRCLIB](https://lrclib.net) (`--lyrics-from lrclib`, braucht `--artist` und `--title`). Bei LRCLIB wird die Fassung gewählt, deren Länge zur Audiodatei passt (bis 5 s Abweichung), Live-, Akustik- und Remix-Fassungen nur, wenn es keine andere gibt. Die gewählte Fassung steht in `meta.json` unter `lyrics_source`. LRCLIB liefert nur den Text, die Zeiten bestimmt die Ausrichtung am Audio. Die Texte sind urheberrechtlich geschützt: nur lokal verwenden, nicht weitergeben.
- `--lyrics`, `--lyrics-from` und `--ultrastar` schließen sich aus. Eine UltraStar-Datei an `--lyrics` übergeben ist ein Fehler.
- Laufen Modus 1 oder 3 in einem Ordner, der noch die Referenz aus Modus 2 enthält, wird die Tonhöhe neu berechnet, damit `vocals.json` nicht als KI-Ergebnis gilt.
> [!NOTE]
> **Rechtlicher Hinweis zu Online-Quellen:** Der Download von Audiodaten aus Online-Quellen (wie YouTube) über `yt-dlp` geschieht ausschließlich auf Veranlassung des Nutzers. Der Nutzer ist selbst dafür verantwortlich, dass die erforderlichen Rechte für die Verarbeitung und Analyse der Inhalte vorliegen.
### 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
```
Im Testset steht pro Song `reference` (UltraStar-Datei) und optional `audio` (sonst wird das Audio über den `#VIDEO:`-Tag der Referenz per yt-dlp geholt). Mit `lyrics = "reference"` richtet der Benchmark den Text der Referenz am Audio aus (Modus 3), ohne deren Zeiten zu verwenden. So lässt sich Modus 3 gegen Modus 1 messen.
## Integration in andere Programme
Eine App (z. B. ein Übungsprogramm oder Editor) braucht nur den Songpack-Ordner oder das `.songpack`-Archiv. Die Pipeline muss nicht in der App laufen. Die verbindliche Beschreibung des Formats steht in der [Songpack-Spezifikation](songpack-spec.md).
### 1. Was die App liest
| Datei | Pflicht | Inhalt |
|---|---|---|
| `manifest.json` | ja | Version, Varianten, Dateiliste |
| `meta.json` | ja | Titel, Sprache, Quelle, `vocals_source` (welcher Modus) |
| `vocals.json` | ja, für Gesangstraining | Silben mit Start/Ende in Sekunden, Tonhöhe (MIDI) |
| `tempo.json` | sobald Akkorde oder Strumming vorhanden | Tempo-Map (Sekunde ↔ Beat) |
| `chords.json`, `tracks/*.json` | optional | Akkorde und Instrumenten-Tracks in Beats |
| `vocals_f0.json` | optional | Tonhöhenverlauf |
| `stems/` | bei Variante `full` | Audiospuren, fehlen bei `data` |
| `export/song.txt` | optional | UltraStar-Export, nur zur Anzeige, nicht als Quelle nutzen |
Die App sollte `manifest.json` zuerst lesen und nur die Dateien laden, die sie braucht. Zeiten in `vocals.json` und `tracks/` sind in Sekunden bzw. Beats, die Umrechnung läuft über `tempo.json`. Unbekannte Felder soll die App ignorieren, damit neue optionale Felder in Minor-Versionen nicht brechen.
`training_diff.json` und `.cache/` sind interne Dateien für Auswertung und Pipeline. Eine App soll sie nicht lesen.
### 2. Aufruf über die Kommandozeile
Ein fremdes Programm startet `unmix` als Prozess:
```bash
# Ergebnis als JSON auf stdout (eine Zeile, am Ende der Ausgabe)
unmix analyze song.mp3 -o out/ --lang en --json
# Songpack packen (full = mit Stems, data = ohne Audio)
unmix pack out/ -o song.songpack
unmix pack out/ -o song_data.songpack --variant data
# Archiv sicher entpacken (prüft Pfade und Größen)
unmix unpack song.songpack -o unpacked/
```
- **Exit-Code:** `0` bei Erfolg, `1` bei Fehlern (fehlende Datei, falscher Modus, Stufe fehlgeschlagen).
- **`--json`** gibt `output_dir`, `stages_done`, `stages_failed` und `reference_eval` aus. Bei fehlgeschlagenen Stufen bricht `analyze` mit Exit-Code `1` ab, ohne JSON.
- Die Laufzeit liegt bei Minuten pro Song, die Modelle brauchen GPU oder genug RAM (siehe *Before you use it*). Die App sollte den Aufruf im Hintergrund starten und den Fortschritt nicht erwarten.
### 3. Aufruf aus Python
```python
from pathlib import Path
from unmix.pipeline import PipelineContext, get_default_pipeline
from unmix.schema.vocals import VocalsDocument
ctx = PipelineContext(source_file=Path("song.mp3"), output_dir=Path("out"), lang="en")
meta = get_default_pipeline().run(ctx)
vocals = VocalsDocument.model_validate_json(Path("out/vocals.json").read_text(encoding="utf-8"))
```
Die Datenmodelle (`unmix.schema.*`) sind Pydantic-Modelle und validieren beim Laden. Die Funktionen unter `unmix.pipeline` und `unmix.export` sind die Schnittstellen, die außerhalb der CLI genutzt werden können. Interne Hilfsfunktionen (mit `_` beginnend) sind nicht Teil der Schnittstelle.
### 4. Versionen
- Das Format ist mit `manifest.json` versioniert (aktuell `1.0`). Minor-Erhöhungen fügen nur optionale Felder hinzu, Major-Erhöhungen können Felder ändern oder entfernen.
- Eine App prüft `schema_version` und lehnt Major-Versionen ab, die sie nicht kennt.
- Die Spezifikation hat offene Punkte (z. B. Stem-Format WAV oder FLAC, Tempo-Rampen), siehe Abschnitt 15 dort.
## References & Links
* **[Songpack-Spezifikation](songpack-spec.md)** – Vollständige Spezifikation des Songpack-Containers v1.0.
* **[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).

278
docs/format.md Normal file
View File

@ -0,0 +1,278 @@
# Song-Paket Format Spezifikation (v1.0)
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).
---
## 1. Verzeichnisstruktur und Container
Maßgebliche Spezifikation: siehe [songpack-spec.md](../songpack-spec.md).
Ein Songpack existiert in zwei Formen:
- **Ordner** (Arbeitsform für Analyse und Editor)
- **`.songpack`** (Austauschform: ZIP-Archiv mit `manifest.json` als erstem Eintrag, Stems unkomprimiert `ZIP_STORED`, JSON komprimiert `ZIP_DEFLATED`)
```
<song>/
manifest.json # Pflicht: Dateiindex, SHA-256 Prüfsummen, Stufen-Status
meta.json # Pflicht: Titel, Interpret, Sprache, Dauer, Audio-Fingerabdruck, Tonart
tempo.json # Pflicht: Tempo-Map (Anker, Taktart)
vocals.json # Silben-Timing, Tonhöhen, Wortgrenzen (Sekundenbasis)
vocals_f0.json # Optional: F0-Grundfrequenzverlauf
chords.json # Akkordverlauf (Beat-Basis)
tracks/ # Instrumenten-Tracks (Beat-Basis)
guitar.json # kind: "strumming"
(später: bass.json, drums.json, piano.json)
stems/ # Isolierte Audiodateien (44.1 kHz, 16-Bit Stereo WAV oder FLAC)
vocals.wav # Gesangsspur
instrumental.wav # Gesamtes Playback ohne Gesang
drums.wav # Schlagzeug (optional)
bass.wav # Bass (optional)
other.wav # Sonstige Instrumente (optional)
export/
song.txt # UltraStar-Deluxe Export
cover.jpg # Optionales Cover-Bild
.cache/ # Stufen-Hashes und temporäre Zwischenergebnisse (nicht im .songpack)
```
---
## 2. Grundlegende Prinzipien
### 2.1 Zeitbasen
- **Gesang (`vocals.json`):** Ausschließlich in **Sekunden** (`float`).
- **Akkorde (`chords.json`) & Strumming (`strumming.json`):** Ausschließlich in **musikalischen Zählzeiten / Beats** (`float`, Viertelnoten).
- **Verbindung:** Ausschließlich über die in `tempo.json` definierte Tempo-Map mit den Konvertierungsfunktionen `sec_to_beat()` und `beat_to_sec()`.
### 2.2 Schemakonventionen
Jede JSON-Datei enthält im Wurzelknoten:
- `"schema_version": "1.0"`
- `"generated_by"`: Objekt mit Angaben zu Stufe, Modell, Modellversion und Ausführungsparametern:
```json
"generated_by": {
"stage": "s4_pitch",
"model": "torchcrepe-full",
"model_version": "1.0.0",
"params": {
"hop_length_ms": 10,
"voicing_threshold": 0.25
}
}
```
### 2.3 Konfidenz und Herkunft
Jedes automatisch erzeugte musikalische Ereignis (Silbe, Akkord, Strumming-Event) besitzt:
- `confidence`: Gleitkommazahl im Bereich `0.0` bis `1.0`.
- `source`: Literal aus `["auto", "manual", "import"]`.
---
## 3. Dateispezifikationen
### 3.1 `meta.json`
Zentrale Metadaten des analysierten Titels.
```json
{
"schema_version": "1.0",
"generated_by": null,
"title": "Beispielsong",
"artist": "Künstler",
"language": "de",
"duration_sec": 195.42,
"source_file": {
"path": "/daten/audio/beispiel.mp3",
"sha256": "3a7b9c1d...",
"size_bytes": 6245120
},
"key": "Am",
"capo": null,
"models_used": [
{"stage": "s1_extract", "name": "ffmpeg", "version": "6.0"},
{"stage": "s2_stems", "name": "htdemucs_ft", "version": "1.0.0"},
{"stage": "s3_lyrics", "name": "whisper-large-v3", "version": "1.0.0"},
{"stage": "s4_pitch", "name": "torchcrepe-full", "version": "1.0.0"},
{"stage": "s5_tempo", "name": "beat_this-final0", "version": "1.1.0"},
{"stage": "s6_chords", "name": "chordino", "version": "1.0.0"},
{"stage": "s7_strumming", "name": "librosa-onsets", "version": "1.0.0"}
],
"created_at": "2026-11-02T10:00:00Z",
"stages_done": ["s1_extract", "s2_stems", "s3_lyrics", "s4_pitch", "s5_tempo", "s6_chords", "s7_strumming"],
"stages_failed": {}
}
```
---
### 3.2 `tempo.json`
Definiert den Zeitverlauf und die Beziehung zwischen Sekunden und Taktschlägen.
```json
{
"schema_version": "1.0",
"generated_by": {
"stage": "s5_tempo",
"model": "beat_this-final0",
"model_version": "1.1.0",
"params": {"min_tempo_change_bpm": 4.0}
},
"anchors": [
{"sec": 0.52, "beat": 0.0, "bpm": 120.0}
],
"time_signature": {
"numerator": 4,
"denominator": 4
},
"downbeat_offset": 0
}
```
- **Regeln:**
- Zwischen zwei aufeinanderfolgenden Ankern gilt ein konstantes Tempo (`bpm`).
- `beat` ist eine Fließkommazahl (Viertelnoten).
- Der letzte Anker gilt bis zum Ende des Songs.
- Songs mit durchgehendem Tempo besitzen exakt **einen** Anker. Weitere Anker existieren nur bei echten Tempowechseln.
---
### 3.3 `vocals.json`
Liedtext, Silbenaufteilung und Gesangstonhöhe.
```json
{
"schema_version": "1.0",
"generated_by": {
"stage": "s4_pitch",
"model": "torchcrepe-full",
"model_version": "1.0.0",
"params": {"hop_length_ms": 10, "voicing_threshold": 0.25}
},
"lines": [
{
"start": 12.34,
"end": 15.80,
"syllables": [
{
"text": "Hel",
"start": 12.34,
"end": 12.61,
"midi": 64.0,
"golden": false,
"confidence": 0.88,
"source": "auto"
},
{
"text": "lo ",
"start": 12.61,
"end": 13.10,
"midi": 62.0,
"golden": false,
"confidence": 0.92,
"source": "auto"
}
]
}
]
}
```
- `start` / `end`: Absoluter Beginn und Ende in Sekunden.
- `midi`: Geglättete Median-Tonhöhe in Halbtönen (kontinuierlich, z. B. `64.0` = E4, `60.0` = C4).
- Oktavlage entspricht dem Original.
- Leerzeichen zwischen Wörtern hängen an der jeweils letzten Silbe (z. B. `"lo "`).
---
### 3.4 `chords.json`
Harmonischer Ablauf in musikalischen Zählzeiten (Beats).
```json
{
"schema_version": "1.0",
"generated_by": {
"stage": "s6_chords",
"model": "chordino",
"model_version": "1.0.0",
"params": {"backend": "chordino", "quantization": "beat"}
},
"chords": [
{
"start_beat": 0.0,
"end_beat": 4.0,
"label": "Am",
"root": "A",
"quality": "min",
"bass": null,
"confidence": 0.85,
"source": "auto"
},
{
"start_beat": 4.0,
"end_beat": 8.0,
"label": "F/A",
"root": "F",
"quality": "maj",
"bass": "A",
"confidence": 0.80,
"source": "auto"
}
]
}
```
- `label`: Harte-Notation (`C`, `Am`, `G7`, `Dsus4`, `F/A`, `N` für kein Akkord).
- `start_beat` / `end_beat`: Start- und Endzeitpunkt in Viertelnoten-Beats.
---
### 3.5 `strumming.json`
Anschlagereignisse und Rhythmusmuster für Begleitinstrumente.
```json
{
"schema_version": "1.0",
"generated_by": {
"stage": "s7_strumming",
"model": "librosa-onsets",
"model_version": "1.0.0",
"params": {"grid": "8th", "status": "experimental"}
},
"events": [
{
"beat": 0.0,
"direction": "down",
"strength": 0.9,
"confidence": 0.85,
"source": "auto"
},
{
"beat": 0.5,
"direction": "up",
"strength": 0.6,
"confidence": 0.70,
"source": "auto"
}
],
"patterns": [
{
"start_beat": 0.0,
"end_beat": 16.0,
"pattern": "D . D U . U D U",
"grid": "8th"
}
]
}
```
- `events`: Einzelereignisse auf dem Beat-Raster mit Anschlagstärke (`0.0` bis `1.0`) und Richtung (`"down"`, `"up"`, `"unknown"`).
- `patterns`: Aggregierte 8tel- oder 16tel-Muster pro Taktgruppe (`.` repräsentiert Pausen).
---
### 3.6 `song.txt` (UltraStar Deluxe)
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`

View File

@ -0,0 +1,30 @@
{
"schema_version": "1.0",
"generated_by": null,
"chords": [
{
"id": "c_0001",
"source": "auto",
"confidence": 0.9,
"locked": false,
"start_beat": 0.0,
"end_beat": 4.0,
"label": "Am",
"root": "A",
"quality": "min",
"bass": "A"
},
{
"id": "c_0002",
"source": "auto",
"confidence": 0.88,
"locked": false,
"start_beat": 4.0,
"end_beat": 6.0,
"label": "C",
"root": "C",
"quality": "maj",
"bass": "C"
}
]
}

View File

@ -0,0 +1,11 @@
#TITLE:Demo Song
#ARTIST:Synthetic Artist
#MP3:stems/vocals.wav
#BPM:480.00
#GAP:500
#LANGUAGE:en
#GENRE:Demo
: 0 4 -3 Hel
: 4 4 -3 lo
: 8 8 0 world
E

View File

@ -0,0 +1,129 @@
{
"format": "songpack",
"schema_version": "1.0",
"id": "88fa27d4-d39f-4eae-8b15-14585248a1c9",
"created": "2026-11-02T11:16:09.795264+00:00",
"modified": "2026-11-02T13:41:47.130704+00:00",
"generator": {
"name": "unmix",
"version": "0.1.0"
},
"variant": "full",
"audio_included": true,
"license": null,
"files": [
{
"path": "chords.json",
"role": "chords",
"schema_version": "1.0",
"sha256": "c8c4ae3dbbc89d427ab01b300dcb22c3dabd6293db4bfc16e4b5ac12bd92f38e",
"size": 545,
"stem": null
},
{
"path": "meta.json",
"role": "meta",
"schema_version": "1.0",
"sha256": "aef0e6ea47b66016fe8e79db3f98aa4361743216128ccebc610d210be9252374",
"size": 1611,
"stem": null
},
{
"path": "song.txt",
"role": "meta",
"schema_version": null,
"sha256": "1989999030e4d14bd7feee99899cf0eedc7efd0b2dcd0edbefb529e664230dc4",
"size": 152,
"stem": null
},
{
"path": "strumming.json",
"role": "meta",
"schema_version": "1.0",
"sha256": "23bce336d8207154f53736f8199f8d9eeb83eae067a5e159dfa85cf0f69ad850",
"size": 996,
"stem": null
},
{
"path": "tempo.json",
"role": "tempo",
"schema_version": "1.0",
"sha256": "e38602166d09cf2a88fa96768d6080c19c5f724e1602ed41d935bb8063028187",
"size": 459,
"stem": null
},
{
"path": "vocals.json",
"role": "vocals",
"schema_version": "1.0",
"sha256": "4298bba5f29cf3dca4452aae5f32a90bb44f90ccacbfc8c5b26ea746a1674ad4",
"size": 1191,
"stem": null
},
{
"path": "vocals_f0.json",
"role": "vocals_f0",
"schema_version": "1.0",
"sha256": "3c41341e1b7f1fcc58ab541bb0f47b58a2963fe6c509238ce9e3c9420ad7603d",
"size": 6521,
"stem": null
},
{
"path": "stems/bass.wav",
"role": "stem",
"schema_version": null,
"sha256": "3496df635d266e4cb59b7d7c1109524b84124406b4dbbb4f002319aee0625e77",
"size": 529244,
"stem": "bass"
},
{
"path": "stems/drums.wav",
"role": "stem",
"schema_version": null,
"sha256": "0b22ac43ea6b07df3415968b8fe60a9dce15859acaa6a21ac960cad6b3969013",
"size": 529244,
"stem": "drums"
},
{
"path": "stems/instrumental.wav",
"role": "stem",
"schema_version": null,
"sha256": "d8f805aac78efe4eb7529f7af4033e1e0e1137a02cfc76e7286f102422b2c1ce",
"size": 529244,
"stem": "instrumental"
},
{
"path": "stems/other.wav",
"role": "stem",
"schema_version": null,
"sha256": "ccbb2ccae58e3b9b8d6f73bdb4265eb30ea448acc93ccc6bfdeffffb5262c6d7",
"size": 529244,
"stem": "other"
},
{
"path": "stems/vocals.wav",
"role": "stem",
"schema_version": null,
"sha256": "61727088f8e8b917f83caaaf44212f47d852fe32b411205184ea450176a71d14",
"size": 529244,
"stem": "vocals"
},
{
"path": "export/song.txt",
"role": "ultrastar",
"schema_version": null,
"sha256": "1989999030e4d14bd7feee99899cf0eedc7efd0b2dcd0edbefb529e664230dc4",
"size": 152,
"stem": null
},
{
"path": "tracks/guitar.json",
"role": "track",
"schema_version": "1.0",
"sha256": "64f072e2bb2d17cca3ea18798d3c9448089f204e3ef40b04fab1ab8203b1eeea",
"size": 1091,
"stem": null
}
],
"stages": {}
}

View File

@ -0,0 +1,79 @@
{
"schema_version": "1.0",
"generated_by": null,
"title": "Demo Song",
"artist": "Synthetic Artist",
"album": null,
"year": null,
"language": "en",
"duration_sec": 3.0,
"source": {
"filename": "demo_song.wav",
"path": "examples/demo_song/stems/vocals.wav",
"kind": "audio",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000",
"size_bytes": 529200
},
"audio_ref": {
"duration_sec": 3.0,
"samplerate": 44100,
"pcm_sha256": "1111111111111111111111111111111111111111111111111111111111111111"
},
"audio_offset_sec": 0.0,
"key": {
"tonic": "A",
"mode": "minor",
"confidence": 0.9
},
"capo": null,
"capo_suggestion": {
"capo": 0,
"shapes_in": "Am"
},
"ultrastar": {
"GENRE": "Demo"
},
"models_used": [
{
"stage": "s2_stems",
"name": "htdemucs",
"version": "v4"
},
{
"stage": "s3_lyrics",
"name": "faster-whisper",
"version": "large-v3"
},
{
"stage": "s4_pitch",
"name": "torchcrepe",
"version": "tiny"
},
{
"stage": "s5_tempo",
"name": "beat-this",
"version": "final0"
},
{
"stage": "s6_chords",
"name": "chord-extractor",
"version": "0.2"
},
{
"stage": "tracks:strumming",
"name": "librosa-onset",
"version": "1.0"
}
],
"created_at": "2026-11-02T12:00:00+01:00",
"stages_done": [
"s1_extract",
"s2_stems",
"s3_lyrics",
"s4_pitch",
"s5_tempo",
"s6_chords",
"tracks:strumming"
],
"stages_failed": {}
}

View File

@ -0,0 +1,11 @@
#TITLE:Demo Song
#ARTIST:Synthetic Artist
#MP3:stems/vocals.wav
#BPM:480.00
#GAP:500
#LANGUAGE:en
#GENRE:Demo
: 0 4 -3 Hel
: 4 4 -3 lo
: 8 8 0 world
E

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,54 @@
{
"schema_version": "1.0",
"generated_by": null,
"events": [
{
"id": "e_0001",
"source": "auto",
"confidence": 0.85,
"locked": false,
"beat": 0.0,
"direction": "down",
"strength": 0.9
},
{
"id": "e_0002",
"source": "auto",
"confidence": 0.8,
"locked": false,
"beat": 0.5,
"direction": "up",
"strength": 0.7
},
{
"id": "e_0003",
"source": "auto",
"confidence": 0.85,
"locked": false,
"beat": 1.0,
"direction": "down",
"strength": 0.85
},
{
"id": "e_0004",
"source": "auto",
"confidence": 0.82,
"locked": false,
"beat": 1.5,
"direction": "up",
"strength": 0.75
}
],
"patterns": [
{
"id": "p_0001",
"source": "auto",
"confidence": null,
"locked": false,
"start_beat": 0.0,
"end_beat": 4.0,
"grid": "8th",
"pattern": "D U D U"
}
]
}

View File

@ -0,0 +1,27 @@
{
"schema_version": "1.0",
"generated_by": null,
"anchors": [
{
"id": "t_0001",
"source": "auto",
"confidence": 1.0,
"locked": false,
"sec": 0.0,
"beat": 0.0,
"bpm": 120.0
}
],
"time_signatures": [
{
"id": "ts_0001",
"source": "auto",
"confidence": null,
"locked": false,
"beat": 0.0,
"numerator": 4,
"denominator": 4
}
],
"downbeat_offset": 0
}

View File

@ -0,0 +1,58 @@
{
"schema_version": "1.0",
"generated_by": null,
"name": "guitar",
"instrument": "guitar",
"kind": "strumming",
"stem": "instrumental",
"events": [
{
"id": "e_0001",
"source": "auto",
"confidence": 0.85,
"locked": false,
"beat": 0.0,
"direction": "down",
"strength": 0.9
},
{
"id": "e_0002",
"source": "auto",
"confidence": 0.8,
"locked": false,
"beat": 0.5,
"direction": "up",
"strength": 0.7
},
{
"id": "e_0003",
"source": "auto",
"confidence": 0.85,
"locked": false,
"beat": 1.0,
"direction": "down",
"strength": 0.85
},
{
"id": "e_0004",
"source": "auto",
"confidence": 0.82,
"locked": false,
"beat": 1.5,
"direction": "up",
"strength": 0.75
}
],
"patterns": [
{
"id": "p_0001",
"source": "auto",
"confidence": null,
"locked": false,
"start_beat": 0.0,
"end_beat": 4.0,
"grid": "8th",
"pattern": "D U D U"
}
]
}

View File

@ -0,0 +1,56 @@
{
"schema_version": "1.0",
"generated_by": null,
"lines": [
{
"id": "l_0001",
"source": "auto",
"confidence": null,
"locked": false,
"voice": 0,
"start": 0.5,
"end": 2.5,
"syllables": [
{
"id": "s_0001",
"source": "auto",
"confidence": 0.95,
"locked": false,
"text": "Hel",
"start": 0.5,
"end": 1.0,
"midi": 57.0,
"type": "normal",
"word_end": false,
"golden": false
},
{
"id": "s_0002",
"source": "auto",
"confidence": 0.92,
"locked": false,
"text": "lo",
"start": 1.0,
"end": 1.5,
"midi": 57.0,
"type": "normal",
"word_end": true,
"golden": false
},
{
"id": "s_0003",
"source": "auto",
"confidence": 0.98,
"locked": false,
"text": "world",
"start": 1.5,
"end": 2.5,
"midi": 60.0,
"type": "normal",
"word_end": true,
"golden": false
}
]
}
]
}

View File

@ -0,0 +1,610 @@
{
"schema_version": "1.0",
"generated_by": null,
"hop_sec": 0.01,
"start_sec": 0.0,
"hz": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
220.0,
220.63,
221.24,
221.84,
222.41,
222.94,
223.42,
223.85,
224.22,
224.52,
224.76,
224.91,
224.99,
224.99,
224.91,
224.76,
224.52,
224.22,
223.85,
223.42,
222.94,
222.41,
221.84,
221.24,
220.63,
220.0,
219.37,
218.76,
218.16,
217.59,
217.06,
216.58,
216.15,
215.78,
215.48,
215.24,
215.09,
215.01,
215.01,
215.09,
215.24,
215.48,
215.78,
216.15,
216.58,
217.06,
217.59,
218.16,
218.76,
219.37,
220.0,
220.63,
221.24,
221.84,
222.41,
222.94,
223.42,
223.85,
224.22,
224.52,
224.76,
224.91,
224.99,
224.99,
224.91,
224.76,
224.52,
224.22,
223.85,
223.42,
222.94,
222.41,
221.84,
221.24,
220.63,
220.0,
219.37,
218.76,
218.16,
217.59,
217.06,
216.58,
216.15,
215.78,
215.48,
215.24,
215.09,
215.01,
215.01,
215.09,
215.24,
215.48,
215.78,
216.15,
216.58,
217.06,
217.59,
218.16,
218.76,
219.37,
220.0,
220.63,
221.24,
221.84,
222.41,
222.94,
223.42,
223.85,
224.22,
224.52,
224.76,
224.91,
224.99,
224.99,
224.91,
224.76,
224.52,
224.22,
223.85,
223.42,
222.94,
222.41,
221.84,
221.24,
220.63,
220.0,
219.37,
218.76,
218.16,
217.59,
217.06,
216.58,
216.15,
215.78,
215.48,
215.24,
215.09,
215.01,
215.01,
215.09,
215.24,
215.48,
215.78,
216.15,
216.58,
217.06,
217.59,
218.16,
218.76,
219.37,
220.0,
220.63,
221.24,
221.84,
222.41,
222.94,
223.42,
223.85,
224.22,
224.52,
224.76,
224.91,
224.99,
224.99,
224.91,
224.76,
224.52,
224.22,
223.85,
223.42,
222.94,
222.41,
221.84,
221.24,
220.63,
220.0,
219.37,
218.76,
218.16,
217.59,
217.06,
216.58,
216.15,
215.78,
215.48,
215.24,
215.09,
215.01,
215.01,
215.09,
215.24,
215.48,
215.78,
216.15,
216.58,
217.06,
217.59,
218.16,
218.76,
219.37,
220.0,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
],
"confidence": [
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.95,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05,
0.05
]
}

View File

@ -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"
@ -9,9 +9,18 @@ dependencies = [
"typer>=0.12.0",
"rich>=13.7.0",
"demucs>=4.0.0",
"torch>=2.0.0",
"torch>=2.4.0",
"torchaudio>=2.4.0",
"soundfile>=0.12.0",
"julius>=0.2.7",
"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",
"chord-extractor>=0.1.3",
]
[project.optional-dependencies]
@ -22,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"]
@ -38,6 +48,18 @@ markers = [
"integration: marks tests as integration tests",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
torchaudio = { index = "pytorch-cpu" }
[tool.uv.extra-build-dependencies]
vamp = ["numpy"]
[tool.ruff]
line-length = 120
target-version = "py312"

384
songpack-spec.md Normal file
View File

@ -0,0 +1,384 @@
# Songpack-Spezifikation v1.0
Das Songpack ist die Schnittstelle zwischen Analyse-Tool (Python) und Übungs-App/Editor (Rust). Alles, was ein Song an Information trägt, steht hier: Audio-Stems, Gesang mit Tonhöhen, Tempo-Map, Akkorde und Instrumenten-Tracks (Strumming, Bass, Schlagzeug, Klavier, …).
## 1. Container
Zwei gleichwertige Formen, identischer Inhalt:
- **Ordner** (Arbeitsform): Analyse-Tool und Editor lesen und schreiben einzelne Dateien.
- **`.songpack`** (Austauschform): ZIP-Archiv mit exakt dem Ordnerinhalt, `manifest.json` als erster Eintrag. Audiodateien werden nur gespeichert (nicht komprimiert), JSON darf deflate-komprimiert sein. Pfade relativ, `/` als Trenner, UTF-8.
```
<song>/
manifest.json Pflicht
meta.json Pflicht
tempo.json Pflicht, sobald Akkorde/Strumming existieren
vocals.json Pflicht für Gesangstraining
vocals_f0.json optional: Tonhöhenverlauf
chords.json optional
tracks/ optional: ein Track pro Instrument
guitar.json bass.json drums.json piano.json …
stems/ Pflicht bei Variante "full", fehlt bei "data" (siehe 11)
vocals.wav|flac
instrumental.wav|flac
drums.* bass.* guitar.* piano.* other.* optional
export/
song.txt optional: UltraStar-Export (abgeleitet)
cover.jpg optional
```
Der Ordner `.cache/` (Zwischenergebnisse der Pipeline) gehört nicht zum Songpack und wird beim Packen weggelassen.
## 2. Allgemeine Regeln
- JSON, UTF-8, kein BOM. Zahlen mit Punkt als Dezimaltrenner.
- **Zeit in Sekunden** (`float`, ab Anfang der Stem-Dateien), **musikalische Zeit in Beats** (`float`, Viertelnoten, Beat 0 = erste Eins des ersten Taktes; negative Beats für Auftakt erlaubt).
- Alle Stems haben dieselbe Länge und Samplerate (Standard 44,1 kHz) und beginnen bei Sekunde 0 des Originals.
- Jede JSON-Datei beginnt mit `"schema_version": "1.0"` (Major.Minor). Leser lehnen eine höhere Major-Version ab, ignorieren aber unbekannte Felder.
- Jeder bearbeitbare Eintrag hat:
- `id`: stabiler String, innerhalb der Datei eindeutig (z.B. `s_0001`), bleibt bei Änderungen erhalten
- `source`: `auto` | `manual` | `import`
- `confidence`: 0..1 oder `null` (bei `manual`/`import` meist `null`)
- `locked`: `true`, wenn eine Neuberechnung den Eintrag nicht überschreiben darf (Default `false`; `manual` gilt immer als gesperrt)
- Bereiche, die der Analyse nicht bekannt sind, fehlen oder sind `null`. Nie Platzhalter wie `0` oder `""`.
- Dateien werden atomar geschrieben (temporäre Datei, dann umbenennen).
## 3. manifest.json
```json
{
"format": "songpack",
"schema_version": "1.0",
"id": "5f0c9b0e-3c1e-4a56-9b8c-1d7f6c2a9a10",
"created": "2026-11-02T11:40:00+01:00",
"modified": "2026-11-02T11:55:12+01:00",
"generator": {"name": "unmix", "version": "0.1.0"},
"variant": "full",
"audio_included": true,
"license": null,
"files": [
{"path": "meta.json", "role": "meta", "schema_version": "1.0", "sha256": "…", "size": 812},
{"path": "stems/vocals.flac", "role": "stem", "stem": "vocals", "sha256": "…", "size": 21345678},
{"path": "vocals.json", "role": "vocals", "schema_version": "1.0", "sha256": "…", "size": 48210}
],
"stages": {
"stems": {"status": "done", "input_hash": "…", "model": "htdemucs_ft", "params": {"shifts": 1}, "finished": "…"},
"lyrics": {"status": "done", "input_hash": "…", "model": "whisper-large-v3+whisperx", "params": {"language": "en"}, "finished": "…"},
"pitch": {"status": "done", "input_hash": "…", "model": "torchcrepe-full", "params": {"hop_ms": 10}, "finished": "…"},
"tempo": {"status": "failed", "error": "…"},
"chords": {"status": "stale"}
}
}
```
- `role`: `meta` | `tempo` | `vocals` | `vocals_f0` | `chords` | `track` | `stem` | `ultrastar` | `cover`.
- `stem`: `vocals` | `instrumental` | `drums` | `bass` | `guitar` | `piano` | `other`.
- `status`: `done` | `failed` | `stale` (Eingabe hat sich geändert, Ergebnis veraltet) | `skipped`.
- `input_hash` fasst Eingabedateien, Stufenversion, Modell und Parameter zusammen. Gleicher Hash = Stufe wird nicht neu gerechnet.
- Prüfsummen dienen der Erkennung von Änderungen von außen, nicht der Sicherheit. Weichen sie ab, markiert der Leser die Datei als geändert und rechnet davon abhängige Stufen als `stale`.
## 4. meta.json
```json
{
"schema_version": "1.0",
"title": "Chasing Cars",
"artist": "Snow Patrol",
"album": null,
"year": 2006,
"language": "en",
"duration_sec": 267.4,
"source": {"filename": "chasing_cars.mp4", "kind": "video", "sha256": "…"},
"audio_ref": {"duration_sec": 267.4, "samplerate": 44100, "pcm_sha256": "…"},
"audio_offset_sec": 0.0,
"key": {"tonic": "A", "mode": "major", "confidence": 0.81},
"capo_suggestion": {"capo": 0, "shapes_in": "A"},
"ultrastar": {"CREATOR": "Canni", "EDITION": "[SC]-Songs", "GENRE": "Rock", "VIDEO": "…", "COVER": "…"}
}
```
`ultrastar` ist ein reiner Durchreichebereich für Header-Felder, die beim Import anfallen und beim Export wieder geschrieben werden, damit nichts verloren geht.
## 5. tempo.json
```json
{
"schema_version": "1.0",
"anchors": [
{"id": "t_0001", "sec": 0.52, "beat": 0.0, "bpm": 104.0, "source": "auto", "confidence": 0.93, "locked": false},
{"id": "t_0002", "sec": 98.47, "beat": 170.0, "bpm": 106.0, "source": "manual", "confidence": null, "locked": true}
],
"time_signatures": [
{"beat": 0.0, "numerator": 4, "denominator": 4}
]
}
```
**Bedeutung:** Ein Anker sagt "ab dieser Sekunde gilt dieses Tempo". Zwischen zwei Ankern ist das Tempo konstant.
- `bpm` ist in Viertelnoten pro Minute angegeben und gilt ab dem Anker bis zum nächsten.
- Wahrheit sind `sec` und `bpm` jedes Ankers sowie `beat` des **ersten** Ankers. Der `beat` der folgenden Anker ist redundant und wird so berechnet: `beat[i+1] = beat[i] + (sec[i+1] - sec[i]) * bpm[i] / 60`. Weicht der gespeicherte Wert um mehr als 0,001 Beats ab, ist die Datei ungültig.
- Vor dem ersten Anker wird mit dessen `bpm` rückwärts extrapoliert, nach dem letzten vorwärts.
- Keine Tempo-Rampen in v1, nur Sprünge.
**Funktionen** (einzige Stelle, an der Sekunden und Beats ineinander umgerechnet werden):
```
beat_to_sec(b): Anker i = letzter mit beat[i] <= b (sonst erster)
sec[i] + (b - beat[i]) * 60 / bpm[i]
sec_to_beat(s): Anker i = letzter mit sec[i] <= s (sonst erster)
beat[i] + (s - sec[i]) * bpm[i] / 60
```
`time_signatures` gilt ab dem angegebenen Beat und bestimmt Taktzählung (Taktanfang, Zählzeiten). Der erste Eintrag muss bei dem Beat stehen, der der ersten Eins entspricht (üblicherweise 0).
## 6. vocals.json (Sekunden)
```json
{
"schema_version": "1.0",
"lines": [
{
"id": "l_0001", "voice": 0,
"start": 7.08, "end": 9.40,
"source": "auto", "locked": false,
"syllables": [
{"id": "s_0001", "text": "We'll", "start": 7.08, "end": 7.30,
"midi": 64.2, "type": "normal", "word_end": true,
"confidence": 0.88, "source": "auto", "locked": false},
{"id": "s_0002", "text": "do", "start": 7.35, "end": 7.60,
"midi": 71.0, "type": "normal", "word_end": true,
"confidence": 0.91, "source": "auto", "locked": false}
]
}
]
}
```
- `voice`: 0 = Hauptstimme, 1 = zweite Stimme (Duett).
- `text`: Silbe ohne Leerzeichen. `word_end: true` heißt, danach folgt ein Leerzeichen (Wortgrenze). Zeile als Text = Silben mit Leerzeichen nach `word_end`.
- `midi`: Tonhöhe als MIDI-Wert (Float, 60 = C4), die geglättete Mediantonhöhe der Silbe. `null` bei Freestyle oder nicht bestimmbar.
- `type`: `normal` | `golden` | `freestyle` | `rap`.
- Silben sind nach `start` sortiert, überlappen nicht (`end[i] <= start[i+1]`), Zeilen ebenso. Zeilengrenzen `start`/`end` liegen auf der ersten und letzten Silbe, außer sie wurden von Hand erweitert.
- Die Oktavlage entspricht dem Original (keine Normalisierung). Oktav-Invarianz ist Sache der App.
### vocals_f0.json (optional)
```json
{
"schema_version": "1.0",
"hop_sec": 0.01,
"start_sec": 0.0,
"hz": [null, null, 220.1, 221.0],
"confidence": [0.0, 0.1, 0.92, 0.95]
}
```
Rohverlauf der Grundfrequenz aus dem Gesangs-Stem, Wert `i` gilt für `start_sec + i * hop_sec`. `null` = stimmlos. Wird für Editor-Anzeige und das Prüfen von Noten genutzt und von UltraStar nicht abgebildet.
## 7. chords.json (Beats)
```json
{
"schema_version": "1.0",
"chords": [
{"id": "c_0001", "start_beat": 0.0, "end_beat": 4.0,
"label": "Am", "root": "A", "quality": "min", "bass": null,
"confidence": 0.74, "source": "auto", "locked": false}
]
}
```
- `label`: Kurzschreibweise (`C`, `Am`, `G7`, `Dsus4`, `F/A`); `N` = kein Akkord.
- `root` (Notenname, `C`, `C#`, `Db`, …), `quality` (`maj`, `min`, `7`, `maj7`, `min7`, `sus2`, `sus4`, `dim`, `aug`, …) und `bass` sind die maschinenlesbare Zerlegung, `label` wird daraus erzeugt.
- Akkorde sind nach `start_beat` sortiert und überlappungsfrei. Lücken sind erlaubt (kein Akkord).
## 8. Instrumenten-Tracks (Beats)
Jedes Instrument hat eine eigene Datei `tracks/<name>.json` (`name`: Kleinbuchstaben, Ziffern, Unterstrich). Alle Tracks liegen in Beats und teilen sich diesen Kopf:
```json
{
"schema_version": "1.0",
"name": "guitar",
"instrument": "guitar",
"kind": "strumming",
"stem": "guitar",
"events": []
}
```
- `name`: eindeutige Track-ID und Dateiname. Mehrere Tracks desselben Instruments sind möglich (`guitar_rhythm`, `guitar_lead`).
- `instrument`: offene Liste (`guitar`, `bass`, `piano`, `keys`, `drums`, `other`, …).
- `stem`: Stem, aus dem der Track gewonnen wurde, oder `null` (z.B. von Hand angelegt).
- `kind`: bestimmt den Aufbau von `events`. Bekannt sind `strumming`, `notes`, `drums`. Leser ignorieren Tracks mit unbekanntem `kind` und zeigen sie als "nicht unterstützt" an. Neue Arten erfordern deshalb nur eine Minor-Version.
- Jeder Eintrag trägt `id`, `source`, `confidence`, `locked`. Ereignisse sind nach Startbeat sortiert.
### kind: strumming
```json
{
"events": [
{"id": "e_0001", "beat": 0.0, "direction": "down", "strength": 0.9,
"confidence": 0.5, "source": "auto", "locked": false}
],
"patterns": [
{"id": "p_0001", "start_beat": 0.0, "end_beat": 16.0,
"grid": "8th", "pattern": "D . D U . U D U",
"confidence": 0.4, "source": "auto", "locked": false}
]
}
```
- `direction`: `down` | `up` | `mute` | `unknown`. `strength`: 0..1.
- `events` sind die Rohdaten und die Wahrheit, `patterns` eine optionale Verdichtung für die Anzeige. Bei Widerspruch gilt `events`.
- `grid`: `quarter` | `8th` | `triplet` | `16th`. Im Muster steht `D` (down), `U` (up), `.` (Pause), `x` (gedämpft), je ein Zeichen pro Gitterschritt.
### kind: notes
Für Bass, Klavier, Lead-Gitarre und andere Instrumente mit Tonhöhen.
```json
{
"events": [
{"id": "n_0001", "start_beat": 4.0, "end_beat": 4.5, "midi": 45,
"velocity": 0.7, "confidence": 0.8, "source": "auto", "locked": false}
]
}
```
`midi` ist ganzzahlig (60 = C4), `velocity` 0..1. Anders als bei Akkorden und Silben dürfen sich Noten überlappen (Mehrstimmigkeit).
### kind: drums
```json
{
"events": [
{"id": "d_0001", "beat": 0.0, "piece": "kick", "strength": 0.9,
"confidence": 0.85, "source": "auto", "locked": false}
]
}
```
`piece`: `kick` | `snare` | `hihat_closed` | `hihat_open` | `tom` | `crash` | `ride` | `other`. Gleichzeitige Schläge sind mehrere Ereignisse mit demselben `beat`.
## 9. Neuberechnung und Handänderungen
Wenn eine Stufe neu läuft, gilt:
1. Einträge mit `locked: true` oder `source: manual` bleiben unverändert.
2. Alle übrigen Einträge der Stufe werden durch das neue Ergebnis ersetzt.
3. Überlappt ein neuer `auto`-Eintrag einen gesperrten, wird der neue verworfen (bei Silben und Akkorden) bzw. auf den freien Bereich zugeschnitten.
4. IDs bleiben bei bestehenden Einträgen erhalten. Neue Einträge bekommen neue IDs, die nie wiederverwendet werden.
5. Ändert sich die Tempo-Map, verschieben sich Akkorde und Tracks automatisch mit (sie liegen in Beats). Der Gesang bleibt, wo er im Audio liegt. Die Stufen `chords` und `tracks` werden nicht automatisch neu gerechnet, nur wenn die Beat-Zuordnung von Hand neu gewünscht ist.
## 10. UltraStar
### Umrechnung
```
sec = GAP/1000 + beat_us * 15 / BPM_us (beat_us = UltraStar-Beat, BPM_us = #BPM)
```
(`15/BPM` ist gleichbedeutend mit `60/(BPM*4)`: ein UltraStar-Beat ist ein Viertel der Zeit eines Beats bei `#BPM`.)
### Export (Songpack → song.txt)
- `BPM_us` = `bpm * 4` des ersten Ankers (16tel-Raster). Bei Bedarf feinerer Raster (`* 8`), wählbar.
- `GAP` = Sekunde des letzten Rasterpunkts, der vor oder auf dem Start der ersten Silbe liegt, in ms gerundet. So bleibt das Raster mit den Takten der Tempo-Map ausgerichtet.
- Silbenstart und -länge werden auf ganze UltraStar-Beats gerundet, Mindestlänge 1, keine Überlappung (bei Konflikt wird die frühere Silbe gekürzt).
- Tonhöhe: `pitch = round(midi) - PITCH_OFFSET`. Der Offset ist konfigurierbar (Default 60, also 0 = C4). Wegen unterschiedlicher Oktavlage in Fremddateien wird der Wert gegen Referenzdateien geprüft und bei Bedarf kalibriert, bevor er fest wird.
- Zeilenwechsel `- beat` am Ende der Zeile. `type` ↔ Zeichen: `normal` `:`, `golden` `*`, `freestyle` `F`, `rap` `R`. Duett: `P1`/`P2`-Blöcke.
- Silbentext: `text` plus Leerzeichen, wenn `word_end`.
- Header: `ARTIST`, `TITLE`, `LANGUAGE`, `YEAR` aus `meta.json`, `MP3` zeigt auf den exportierten Mix, dazu die durchgereichten Felder aus `meta.ultrastar`.
- Tempowechsel: v1 schreibt einen mittleren BPM-Wert und gibt eine Warnung aus. Optional `B beat bpm`-Zeilen (nicht von jeder Software unterstützt).
- Akkorde, Tracks, Konfidenz und f0-Verlauf werden nicht exportiert.
### Import (song.txt → Songpack)
- `source: "import"`, `locked: true` für alle Silben (handgemachte Noten sind besser als jede Automatik).
- `midi = pitch + PITCH_OFFSET`. Mit `#RELATIVE:YES` werden die Beats vor der Umrechnung in absolute umgerechnet. `#START`, `#END`, `#VIDEOGAP` wandern nach `meta.ultrastar`.
- Tempo-Map: ein Anker bei `GAP`, `bpm = BPM_us / 4`, `beat 0` an dieser Stelle. Die echte Taktzuordnung (Downbeat) ist nicht bekannt und wird von der Beat-Stufe oder von Hand gesetzt.
- Die Audiodatei aus `#MP3` wird, falls vorhanden, als Eingabe für die Stem-Trennung verwendet.
## 11. Varianten und Weitergabe
Ein Songpack gibt es in zwei Varianten, erkennbar am Manifest (`variant`, `audio_included`):
| | `full` | `data` |
|---|---|---|
| Stems | enthalten, Pflicht | nicht enthalten, `stems/` fehlt |
| Inhalt | alles | Text, Noten, Tempo-Map, Akkorde, Tracks, Metadaten |
| Typischer Einsatz | eigene Songs, lizenzfreie Songs, privates Archiv | Weitergabe von Songs, deren Audio man nicht weitergeben darf |
| `audio_included` | `true` | `false` |
`license` (Freitext oder SPDX-Kennung) nennt, unter welchen Bedingungen das Audio im Paket weitergegeben werden darf. Bei `full` ohne Angabe warnt die App vor dem Teilen. Originalaufnahmen (Video, MP3) sind nie Teil eines Songpacks, nur die abgeleiteten Stems.
### Eigene Audiodatei zuordnen (Import einer `data`-Variante)
Das Songpack speichert in `meta.audio_ref` einen Fingerabdruck der Aufnahme, auf die sich alle Zeiten beziehen: Dauer, Samplerate und `pcm_sha256` (SHA-256 des dekodierten Audios, 44,1 kHz, mono, 16 Bit, unabhängig vom Dateiformat).
1. Der Empfänger wählt seine Audiodatei. Die App dekodiert sie auf dasselbe Format.
2. **Identisch** (`pcm_sha256` gleich): `audio_offset_sec = 0`, fertig.
3. **Andere Datei** (anderes Format, Remaster, anderer Schnitt): Die App schätzt den Zeitversatz über Kreuzkorrelation der Onset-Hüllkurven von Original-Referenz und eigener Datei und schlägt `audio_offset_sec` vor. Weicht die Dauer um mehr als 0,5 s ab oder ist die Korrelation schwach, zeigt sie eine Warnung "Zuordnung unsicher". Der Nutzer prüft per Vorhören und kann den Versatz von Hand setzen.
4. Der Versatz wird in `meta.audio_offset_sec` gespeichert. **Alle Zeiten im Songpack bleiben unverändert**, nur die Wiedergabe addiert den Versatz: `abspielzeit = sek + audio_offset_sec`.
5. Stems erzeugt anschließend das Analyse-Tool aus der eigenen Datei. Ohne Analyse-Tool kann die App den Song nur mit dem Originalmix (also mit Originalgesang) abspielen. Vergleich und Bewertung funktionieren trotzdem.
Reine Geschwindigkeitsunterschiede (z.B. andere Wiedergaberate) werden in v1 nicht ausgeglichen. Die App weist darauf hin, wenn die Dauer um mehr als 1 % abweicht.
## 12. Import-Sicherheit
Ein fremdes `.songpack` ist nicht vertrauenswürdig. Die App und das Analyse-Tool halten diese Regeln ein:
**Entpacken**
1. Nie direkt in den Zielordner entpacken: erst in ein temporäres Verzeichnis, dort vollständig prüfen, dann atomar verschieben.
2. Nur Dateien aus der Whitelist werden entpackt: `manifest.json`, `meta.json`, `tempo.json`, `vocals.json`, `vocals_f0.json`, `chords.json`, `tracks/<name>.json`, `stems/<name>.wav|flac`, `export/song.txt`, `cover.jpg|png`. Alles andere wird ignoriert, mit Warnung.
3. Pfade normalisieren und ablehnen, wenn sie absolut sind, `..` enthalten, Backslashes oder Laufwerksbuchstaben haben oder auf reservierte Windows-Gerätenamen zeigen. Symlinks und Hardlinks im Archiv werden nie entpackt.
4. Grenzen werden **beim Entpacken gezählt**, nicht aus den ZIP-Headern übernommen: maximal 64 Einträge, 2 GB entpackt insgesamt, 32 MB pro JSON-Datei, 1 GB pro Stem. JSON-Dateien mit einem Kompressionsverhältnis über 100:1 werden abgelehnt (Zip-Bombe).
**Inhalt prüfen**
5. JSON: Tiefe höchstens 16, doppelte Schlüssel verboten, höchstens 100 000 Silben und 50 000 Akkorde bzw. Track-Ereignisse je Datei, höchstens 32 Tracks, Strings höchstens 1 kB.
6. Audio: Header prüfen (WAV oder FLAC), Samplerate, Kanalzahl und Länge gegen `meta` und Manifest abgleichen, Dekodierung mit begrenztem Speicher.
7. Bilder: nur JPEG oder PNG, höchstens 4096 × 4096 Pixel, Dekodierung mit einem sicheren Decoder.
8. Texte (Titel, Silben, Akkorde) werden nie als Markup interpretiert, beim Anzeigen escaped, Steuerzeichen entfernt.
9. Felder wie `VIDEO` oder `COVER` in `meta.ultrastar` werden nie automatisch aus dem Netz geladen, und nichts aus einem Songpack wird ausgeführt.
**Umgang mit Konflikten**
10. Hat der importierte Song dieselbe `id` wie ein vorhandener, fragt die App (als Kopie importieren, ersetzen, abbrechen). Es wird nie still überschrieben, damit eigene Handkorrekturen nicht verloren gehen.
11. Der Import ist atomar: Schlägt etwas fehl, bleibt nichts Halbfertiges zurück.
Eine digitale Signatur (Herkunftsnachweis) ist in v1 nicht vorgesehen.
## 13. Validierung
Ein Songpack ist gültig, wenn:
1. `manifest.json` vorhanden, `format` = `songpack`, Major-Version unterstützt
2. alle im Manifest genannten Dateien existieren, Prüfsummen stimmen (sonst Warnung, nicht Fehler)
3. vorhandene Stems gleiche Länge und Samplerate haben; bei `variant: data` fehlen die Stems und `audio_included` ist `false`, bei `full` sind `vocals` und `instrumental` Pflicht
3a. beim Import zusätzlich alle Regeln aus Abschnitt 12 erfüllt sind
4. IDs innerhalb einer Datei eindeutig sind
5. Silben und Zeilen sortiert und überlappungsfrei sind, `start < end`, alle Zeiten innerhalb `[0, duration_sec]`
6. Akkorde sortiert, überlappungsfrei, `start_beat < end_beat`
7. Tempo-Map: Anker streng aufsteigend in `sec`, `bpm > 0`, redundante `beat`-Werte konsistent (Toleranz 0,001)
8. `confidence` in `[0, 1]` oder `null`
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 `unmix migrate` für ältere Songpacks an.
- Die Schema-Version steht pro Datei, damit sich Dateien unabhängig weiterentwickeln können.
## 15. Offene Punkte
- Zuordnung eigener Audiodateien: Onset-Korrelation reicht ggf. nicht, dann zusätzlich akustischer Fingerabdruck (z.B. Chromaprint) prüfen
- Rechtslage bei der Weitergabe von `full`-Songpacks mit Stems fremder Songs: Hinweis in der App, Verantwortung liegt beim Nutzer
- Wert für `PITCH_OFFSET` gegen reale UltraStar-Dateien prüfen und fixieren
- Dateiformat für Stems: WAV (einfach) oder FLAC (kleiner). Beide erlaubt, Entscheidung nach Größenvergleich
- Tempo-Rampen (Ritardando) in einer späteren Version
- Weitere Track-Arten (z.B. Gesangsharmonien, Tabulatur mit Saite/Bund) nach Bedarf als neues `kind`
- Benennung der Schlagzeug-Teile (`piece`) gegen die Fähigkeiten des gewählten Erkennungsmodells abgleichen

View File

@ -1,3 +0,0 @@
"""songsplit: Audio analysis pipeline for song package decomposition."""
__version__ = "0.1.0"

View File

@ -1,170 +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()
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()

View File

@ -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()

View File

@ -1,6 +0,0 @@
"""Evaluation package."""
from songsplit.eval.metrics import calculate_timing_metrics
from songsplit.eval.run_eval import run_evaluation
__all__ = ["calculate_timing_metrics", "run_evaluation"]

View File

@ -1,8 +0,0 @@
"""Quality metrics against UltraStar reference (timing, pitch, WER)."""
from typing import Any
def calculate_timing_metrics(predicted: list[dict[str, Any]], reference: list[dict[str, Any]]) -> dict[str, float]:
"""Calculate mean/median syllable onset error in ms and fraction within +-100ms."""
raise NotImplementedError("Metrics will be implemented in M2.")

View File

@ -1,8 +0,0 @@
"""Evaluation runner for testset.toml."""
from pathlib import Path
def run_evaluation(testset_config: Path) -> dict[str, str]:
"""Run full evaluation suite across test songs."""
raise NotImplementedError("Evaluation runner will be implemented in M2.")

View File

@ -1,5 +0,0 @@
"""Export modules."""
from songsplit.export.ultrastar import export_ultrastar
__all__ = ["export_ultrastar"]

View File

@ -1,8 +0,0 @@
"""UltraStar format export and import."""
from pathlib import Path
def export_ultrastar(song_dir: Path) -> Path:
"""Export song package to UltraStar song.txt."""
raise NotImplementedError("UltraStar export will be implemented in M2.")

View File

@ -1,27 +0,0 @@
"""Stage 3: Lyrics transcription & alignment (Whisper + WhisperX + hyphenation)."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class LyricsStage(Stage):
name = "s3_lyrics"
version = "1.0.0"
model_name = "whisper-large-v3"
model_version = "1.0.0"
dependencies = ["s2_stems"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.stems_dir / "vocals.wav"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / ".cache" / "lyrics_raw.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"lang": ctx.lang}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M2
raise NotImplementedError("Stage s3_lyrics will be implemented in M2.")

View File

@ -1,30 +0,0 @@
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class PitchStage(Stage):
name = "s4_pitch"
version = "1.0.0"
model_name = "torchcrepe-full"
model_version = "1.0.0"
dependencies = ["s3_lyrics"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "vocals.wav",
ctx.output_dir / ".cache" / "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, "viterbi": True}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M2
raise NotImplementedError("Stage s4_pitch will be implemented in M2.")

View File

@ -1,27 +0,0 @@
"""Stage 5: Beat and downbeat tracking with beat_this -> tempo.json."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class TempoStage(Stage):
name = "s5_tempo"
version = "1.0.0"
model_name = "beat_this"
model_version = "1.0.0"
dependencies = ["s2_stems"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.stems_dir / "instrumental.wav"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "tempo.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M3
raise NotImplementedError("Stage s5_tempo will be implemented in M3.")

View File

@ -1,30 +0,0 @@
"""Stage 6: Chord recognition -> chords.json."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class ChordsStage(Stage):
name = "s6_chords"
version = "1.0.0"
model_name = "chordino"
model_version = "1.0.0"
dependencies = ["s5_tempo"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "instrumental.wav",
ctx.output_dir / "tempo.json",
]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "chords.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"backend": "chordino"}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M4
raise NotImplementedError("Stage s6_chords will be implemented in M4.")

View File

@ -1,30 +0,0 @@
"""Stage 7: Strumming pattern analysis -> strumming.json."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class StrummingStage(Stage):
name = "s7_strumming"
version = "1.0.0"
model_name = "librosa-onsets"
model_version = "1.0.0"
dependencies = ["s5_tempo"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "instrumental.wav",
ctx.output_dir / "tempo.json",
]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "strumming.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"grid": "8th"}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M5
raise NotImplementedError("Stage s7_strumming will be implemented in M5.")

View File

@ -1,29 +0,0 @@
"""Song-Paket data schemas."""
from songsplit.schema.base import DataSource, GeneratedBy, SongPackageBase
from songsplit.schema.chords import ChordEvent, ChordsDocument
from songsplit.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
from songsplit.schema.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
__all__ = [
"DataSource",
"GeneratedBy",
"SongPackageBase",
"SourceFileInfo",
"ModelInfo",
"MetaDocument",
"VocalSyllable",
"VocalLine",
"VocalsDocument",
"TempoAnchor",
"TimeSignature",
"TempoDocument",
"ChordEvent",
"ChordsDocument",
"StrumDirection",
"StrumEvent",
"StrumPattern",
"StrummingDocument",
]

View File

@ -1,43 +0,0 @@
"""Schema for meta.json."""
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import SongPackageBase
class SourceFileInfo(BaseModel):
"""Information about the original source audio/video file."""
model_config = ConfigDict(extra="ignore")
path: str
sha256: str
size_bytes: int
class ModelInfo(BaseModel):
"""Information about an AI model used during processing."""
model_config = ConfigDict(extra="ignore")
stage: str
name: str
version: str
class MetaDocument(SongPackageBase):
"""Song-Paket metadata document (meta.json)."""
model_config = ConfigDict(extra="ignore")
title: str | None = None
artist: str | None = None
language: str | None = None
duration_sec: float = Field(ge=0.0)
source_file: SourceFileInfo
key: str | None = None
capo: int | None = None
models_used: list[ModelInfo] = Field(default_factory=list)
created_at: str
stages_done: list[str] = Field(default_factory=list)
stages_failed: dict[str, str] = Field(default_factory=dict)

View File

@ -1,41 +0,0 @@
"""Schema for strumming.json."""
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import DataSource, SongPackageBase
StrumDirection = Literal["down", "up", "unknown"]
class StrumEvent(BaseModel):
"""A single strumming event."""
model_config = ConfigDict(extra="ignore")
beat: float
direction: StrumDirection
strength: float = Field(default=1.0, ge=0.0, le=1.0)
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
source: DataSource = "auto"
class StrumPattern(BaseModel):
"""An aggregated strumming pattern over a beat range."""
model_config = ConfigDict(extra="ignore")
start_beat: float
end_beat: float
pattern: str
grid: str = "8th"
class StrummingDocument(SongPackageBase):
"""Song-Paket strumming document (strumming.json)."""
model_config = ConfigDict(extra="ignore")
events: list[StrumEvent] = Field(default_factory=list)
patterns: list[StrumPattern] = Field(default_factory=list)

View File

@ -1,34 +0,0 @@
"""Schema for tempo.json."""
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import SongPackageBase
class TempoAnchor(BaseModel):
"""A tempo anchor defining constant BPM starting from a given time/beat."""
model_config = ConfigDict(extra="ignore")
sec: float
beat: float
bpm: float = Field(gt=0.0)
class TimeSignature(BaseModel):
"""Musical time signature, e.g. 4/4."""
model_config = ConfigDict(extra="ignore")
numerator: int = Field(default=4, gt=0)
denominator: int = Field(default=4, gt=0)
class TempoDocument(SongPackageBase):
"""Song-Paket tempo document (tempo.json)."""
model_config = ConfigDict(extra="ignore")
anchors: list[TempoAnchor] = Field(default_factory=list)
time_signature: TimeSignature = Field(default_factory=TimeSignature)
downbeat_offset: int = 0

View File

@ -1,37 +0,0 @@
"""Schema for vocals.json."""
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import DataSource, SongPackageBase
class VocalSyllable(BaseModel):
"""A single syllable with timing, pitch, and confidence."""
model_config = ConfigDict(extra="ignore")
text: str
start: float = Field(ge=0.0)
end: float = Field(ge=0.0)
midi: float
golden: bool = False
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
source: DataSource = "auto"
class VocalLine(BaseModel):
"""A line of lyrics consisting of one or more syllables."""
model_config = ConfigDict(extra="ignore")
start: float = Field(ge=0.0)
end: float = Field(ge=0.0)
syllables: list[VocalSyllable] = Field(default_factory=list)
class VocalsDocument(SongPackageBase):
"""Song-Paket vocals document (vocals.json)."""
model_config = ConfigDict(extra="ignore")
lines: list[VocalLine] = Field(default_factory=list)

View File

@ -1,64 +0,0 @@
"""Tempo-Map conversion between seconds and musical beats.
As defined in the concept:
- Vocals are in seconds
- Chords and strumming are in beats
- Conversion ONLY through sec_to_beat() and beat_to_sec().
"""
from bisect import bisect_right
from songsplit.schema.tempo import TempoAnchor, TempoDocument
def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]:
"""Return anchors sorted by time/beat, raising ValueError if empty."""
if not tempo_map.anchors:
raise ValueError("Tempo map has no anchors defined.")
return sorted(tempo_map.anchors, key=lambda a: a.sec)
def sec_to_beat(sec: float, tempo_map: TempoDocument) -> float:
"""Convert time in seconds to musical beat (float quarter notes).
Constant tempo is assumed between consecutive anchors.
The last anchor applies until the end of the song.
Extrapolation is used before the first anchor.
"""
anchors = _get_sorted_anchors(tempo_map)
sec_points = [a.sec for a in anchors]
idx = bisect_right(sec_points, sec) - 1
if idx < 0:
# Before the first anchor -> extrapolate using the first anchor's tempo
anchor = anchors[0]
delta_sec = sec - anchor.sec
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
anchor = anchors[idx]
delta_sec = sec - anchor.sec
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float:
"""Convert musical beat (float quarter notes) to time in seconds.
Constant tempo is assumed between consecutive anchors.
The last anchor applies until the end of the song.
Extrapolation is used before the first anchor.
"""
anchors = _get_sorted_anchors(tempo_map)
beat_points = [a.beat for a in anchors]
idx = bisect_right(beat_points, beat) - 1
if idx < 0:
# Before the first anchor -> extrapolate using the first anchor's tempo
anchor = anchors[0]
delta_beat = beat - anchor.beat
return anchor.sec + delta_beat * (60.0 / anchor.bpm)
anchor = anchors[idx]
delta_beat = beat - anchor.beat
return anchor.sec + delta_beat * (60.0 / anchor.bpm)

3
src/unmix/__init__.py Normal file
View File

@ -0,0 +1,3 @@
"""unmix: Audio analysis pipeline for song package decomposition."""
__version__ = "0.1.0"

527
src/unmix/cli.py Normal file
View File

@ -0,0 +1,527 @@
"""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"),
lyrics_from: str | None = typer.Option(
None,
"--lyrics-from",
help="Fetch the lyrics text instead of a file. Only 'lrclib' (needs --artist and --title). Local use only.",
),
ultrastar: Path | None = typer.Option(
None,
"--ultrastar",
help="UltraStar song.txt: its notes and timings become the result (same as --reference)",
),
lyrics: Path | None = typer.Option(
None,
"--lyrics",
help="Known lyrics (plain text, one sung line per line, or an UltraStar .txt): align them to the vocals "
"instead of transcribing with Whisper (languages: en, de)",
),
keep_ai_vocals: bool = typer.Option(
False,
"--keep-ai-vocals",
help="Keep AI-generated vocals.json instead of replacing with ground truth reference",
),
export_ultrastar_flag: bool = typer.Option(
True, "--export-ultrastar/--no-export-ultrastar", help="Export UltraStar song.txt to export/"
),
) -> 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)
if ultrastar is not None:
if reference is not None and reference.resolve() != ultrastar.resolve():
console.print("[red][ERROR][/red] --ultrastar und --reference nur einzeln angeben.")
raise typer.Exit(code=1)
reference = ultrastar
if lyrics is not None and reference is not None:
console.print("[red][ERROR][/red] --lyrics und --ultrastar schließen sich aus: genau einen Modus wählen.")
raise typer.Exit(code=1)
if lyrics is not None and not lyrics.exists():
console.print(f"[red][ERROR][/red] Lyrics file not found: {lyrics}")
raise typer.Exit(code=1)
lyrics_label: str | None = f"file: {lyrics.name}" if lyrics is not None else None
if lyrics_from is not None:
if lyrics_from.lower() != "lrclib":
console.print(f"[red][ERROR][/red] --lyrics-from kennt nur 'lrclib', nicht '{lyrics_from}'.")
raise typer.Exit(code=1)
if lyrics is not None or reference is not None:
console.print("[red][ERROR][/red] --lyrics-from schließt --lyrics und --ultrastar aus.")
raise typer.Exit(code=1)
if not title or not artist:
console.print("[red][ERROR][/red] --lyrics-from lrclib braucht --artist und --title.")
raise typer.Exit(code=1)
if lyrics is not None:
from unmix.pipeline.align import is_ultrastar_file
if is_ultrastar_file(lyrics):
console.print(
"[red][ERROR][/red] Das ist eine UltraStar-Datei. Dafür --ultrastar nutzen "
"(Noten und Zeiten werden übernommen). --lyrics ist für reinen Text gedacht."
)
raise typer.Exit(code=1)
if lyrics_from is not None:
from unmix.pipeline.lrclib import LyricsLookupError, audio_duration_sec, fetch_lyrics_file
try:
lyrics, lyrics_label = fetch_lyrics_file(
artist, title, audio_duration_sec(source_path), output_dir / ".cache"
)
except LyricsLookupError as exc:
console.print(f"[red][ERROR][/red] {exc}")
raise typer.Exit(code=1) from exc
console.print(f"[cyan][INFO][/cyan] Lyrics: {lyrics_label}")
ctx = PipelineContext(
source_file=source_path,
output_dir=output_dir,
lang=lang,
stems=stems,
quality=quality,
force=force,
target_stage=stage,
lyrics_file=lyrics,
)
from unmix.pipeline.source_modes import (
invalidate_pitch_cache,
mode_label,
previous_vocals_source,
)
if reference is None and previous_vocals_source(ctx.meta_file) == "reference_ultrastar":
# vocals.json still holds the ground truth of an earlier --ultrastar run: recompute pitch
invalidate_pitch_cache(ctx.cache_dir)
runner = get_default_pipeline()
meta = runner.run(ctx)
if reference is None:
meta.vocals_source = mode_label(lyrics is not None)
meta.lyrics_source = lyrics_label
ctx.save_meta(meta)
# Persist title/artist overrides if provided
updated_meta = False
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.pipeline.source_modes import invalidate_pitch_cache, prepare_ai_vocals
ref_song = parse_ultrastar(ref_path)
# 1. AI Vocals evaluation & Training Diff (Track B)
training_diff = None
ai_vocals = prepare_ai_vocals(output_dir, ctx.cache_dir, meta.vocals_source)
if ai_vocals is not None:
# Generate detailed note-by-note training difference
training_diff = generate_training_diff(ai_vocals, ref_song)
diff_path = output_dir / "training_diff.json"
with open(diff_path, "w", encoding="utf-8") as tdf:
json.dump(training_diff, tdf, indent=2)
meta.reference_eval = training_diff["summary"]
meta.training_diff = training_diff["systematic_biases"]
# 2. Ground-Truth Packaging (Track A)
if not keep_ai_vocals:
vocals_wav = ctx.stems_dir / "vocals.wav"
gt_vocals = ultrastar_to_vocals(ref_song, vocals_wav=vocals_wav)
with open(vocals_json, "w", encoding="utf-8") as vf:
vf.write(gt_vocals.model_dump_json(indent=2))
invalidate_pitch_cache(ctx.cache_dir)
meta.vocals_source = "reference_ultrastar"
console.print(
"[bold green][OK][/bold green] High-Quality Ground-Truth vocals.json generated from reference."
)
else:
meta.vocals_source = "whisper"
ctx.save_meta(meta)
# 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
View 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()

295
src/unmix/container.py Normal file
View File

@ -0,0 +1,295 @@
"""Songpack container implementation (packing and secure unpacking).
Follows Songpack specification v1.0, sections 1, 11, 12, and 13.
"""
import json
import logging
import os
import re
import shutil
import tempfile
import zipfile
from datetime import UTC, datetime
from pathlib import Path
from typing import Literal
from unmix.pipeline.runner import compute_file_sha256
from unmix.schema.manifest import ManifestDocument, ManifestFileInfo
logger = logging.getLogger("unmix.container")
# Security limits according to Section 12
MAX_ENTRIES = 64
MAX_TOTAL_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB
MAX_JSON_SIZE = 32 * 1024 * 1024 # 32 MB
MAX_STEM_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB
MAX_COMPRESSION_RATIO = 100.0
MAX_TRACKS = 32
RESERVED_WINDOWS_NAMES = {
"CON",
"PRN",
"AUX",
"NUL",
*(f"COM{i}" for i in range(1, 10)),
*(f"LPT{i}" for i in range(1, 10)),
}
WHITELIST_PATTERNS = [
re.compile(r"^manifest\.json$"),
re.compile(r"^meta\.json$"),
re.compile(r"^tempo\.json$"),
re.compile(r"^vocals\.json$"),
re.compile(r"^vocals_f0\.json$"),
re.compile(r"^chords\.json$"),
re.compile(r"^tracks/[a-z0-9_]+\.json$"),
re.compile(r"^stems/[a-z0-9_]+\.(wav|flac)$"),
re.compile(r"^export/song\.txt$"),
re.compile(r"^cover\.(jpg|jpeg|png)$"),
]
class SongpackSecurityError(Exception):
"""Raised when a songpack violates security rules."""
def is_path_safe(rel_path: str) -> bool:
"""Check if relative path satisfies Section 12 traversal and platform rules."""
if "\\" in rel_path or ":" in rel_path:
return False
parts = rel_path.split("/")
if any(p == ".." or p == "." or not p for p in parts):
return False
for part in parts:
stem_name = part.split(".")[0].upper()
if stem_name in RESERVED_WINDOWS_NAMES:
return False
return True
def is_whitelisted(rel_path: str) -> bool:
"""Check if relative path matches allowed songpack files."""
return any(pattern.match(rel_path) for pattern in WHITELIST_PATTERNS)
def build_manifest_for_dir(song_dir: Path, variant: Literal["full", "data"] = "full") -> ManifestDocument:
"""Scan song directory and generate or update manifest.json."""
manifest_path = song_dir / "manifest.json"
now_iso = datetime.now(UTC).isoformat()
manifest: ManifestDocument
if manifest_path.exists():
try:
with open(manifest_path, encoding="utf-8") as f:
manifest = ManifestDocument.model_validate(json.load(f))
manifest.modified = now_iso
except Exception:
manifest = ManifestDocument(created=now_iso, modified=now_iso)
else:
manifest = ManifestDocument(created=now_iso, modified=now_iso)
manifest.variant = variant
manifest.audio_included = variant == "full"
files_list: list[ManifestFileInfo] = []
# Map roles
role_mapping = {
"meta.json": ("meta", None),
"tempo.json": ("tempo", None),
"vocals.json": ("vocals", None),
"vocals_f0.json": ("vocals_f0", None),
"chords.json": ("chords", None),
"export/song.txt": ("ultrastar", None),
}
for root, _, filenames in os.walk(song_dir):
rel_root = Path(root).relative_to(song_dir)
if any(part.startswith(".") for part in rel_root.parts):
continue
for fname in sorted(filenames):
rel_file = (rel_root / fname).as_posix() if str(rel_root) != "." else fname
file_path = song_dir / rel_file
if rel_file == "manifest.json" or rel_file.startswith("."):
continue
# Skip stems in data variant
if variant == "data" and rel_file.startswith("stems/"):
continue
role: str = "meta"
stem_name: str | None = None
if rel_file in role_mapping:
role, _ = role_mapping[rel_file]
elif rel_file.startswith("tracks/"):
role = "track"
elif rel_file.startswith("stems/"):
role = "stem"
stem_name = Path(fname).stem
elif rel_file.startswith("cover."):
role = "cover"
sha = compute_file_sha256(file_path)
size = file_path.stat().st_size
files_list.append(
ManifestFileInfo(
path=rel_file,
role=role, # type: ignore[arg-type]
schema_version="1.0" if rel_file.endswith(".json") else None,
sha256=sha,
size=size,
stem=stem_name, # type: ignore[arg-type]
)
)
manifest.files = files_list
return manifest
def pack_songpack(
song_dir: Path,
output_path: Path | None = None,
variant: Literal["full", "data"] = "full",
) -> Path:
"""Pack song directory into a .songpack archive.
- manifest.json is guaranteed to be the first ZIP entry.
- Audio stems (.wav, .flac) are stored uncompressed (ZIP_STORED).
- JSON and text files are compressed (ZIP_DEFLATED).
- .cache/ is omitted.
"""
song_dir = song_dir.resolve()
if output_path is None:
output_path = song_dir.parent / f"{song_dir.name}.songpack"
output_path = output_path.resolve()
# Generate / update manifest.json
manifest = build_manifest_for_dir(song_dir, variant=variant)
manifest_bytes = manifest.model_dump_json(indent=2).encode("utf-8")
# Atomic write to temporary zip first
temp_zip = output_path.with_suffix(".tmp.zip")
if temp_zip.exists():
temp_zip.unlink()
with zipfile.ZipFile(temp_zip, mode="w") as zf:
# First entry MUST be manifest.json (Section 1)
zf.writestr("manifest.json", manifest_bytes, compress_type=zipfile.ZIP_DEFLATED)
for item in manifest.files:
file_abs = song_dir / item.path
if not file_abs.is_file():
continue
compress_type = zipfile.ZIP_STORED if item.path.endswith((".wav", ".flac")) else zipfile.ZIP_DEFLATED
zf.write(file_abs, arcname=item.path, compress_type=compress_type)
temp_zip.replace(output_path)
# Also write manifest.json to song_dir
(song_dir / "manifest.json").write_bytes(manifest_bytes)
logger.info("Created songpack %s (variant: %s)", output_path, variant)
return output_path
def unpack_songpack(songpack_path: Path, output_dir: Path) -> Path:
"""Securely extract a .songpack archive according to Section 12 rules.
- Extracts into a temporary directory first.
- Enforces whitelist, path traversal guards, zip bomb / file size limits.
- Moves atomically into destination.
"""
songpack_path = songpack_path.resolve()
if not songpack_path.is_file():
raise FileNotFoundError(f"Songpack not found: {songpack_path}")
with tempfile.TemporaryDirectory(prefix="songpack_unpack_") as tmp_dir_str:
tmp_dir = Path(tmp_dir_str)
extracted_dir = tmp_dir / "unpacked"
extracted_dir.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(songpack_path, "r") as zf:
infolist = zf.infolist()
if len(infolist) > MAX_ENTRIES:
raise SongpackSecurityError(f"Too many archive entries: {len(infolist)} > {MAX_ENTRIES}")
total_uncompressed_bytes = 0
track_count = 0
for info in infolist:
# Reject directories, symlinks, device files
if info.is_dir():
continue
# Check for symlink (Unix mode 0o120000)
if (info.external_attr >> 16) & 0o120000 == 0o120000:
raise SongpackSecurityError(f"Symlinks not allowed: {info.filename}")
rel_path = info.filename
if not is_path_safe(rel_path):
raise SongpackSecurityError(f"Unsafe path detected: {rel_path}")
if not is_whitelisted(rel_path):
logger.warning("Skipping non-whitelisted file: %s", rel_path)
continue
if rel_path.startswith("tracks/"):
track_count += 1
if track_count > MAX_TRACKS:
raise SongpackSecurityError(f"Too many tracks: > {MAX_TRACKS}")
# Compression ratio check (zip bomb defense)
if info.compress_size > 0:
ratio = info.file_size / info.compress_size
if ratio > MAX_COMPRESSION_RATIO:
raise SongpackSecurityError(f"Compression ratio too high ({ratio:.1f}:1) for {rel_path}")
# Size limits per type
if rel_path.endswith(".json") and info.file_size > MAX_JSON_SIZE:
raise SongpackSecurityError(f"JSON file too large: {info.file_size} > {MAX_JSON_SIZE}")
if rel_path.startswith("stems/") and info.file_size > MAX_STEM_SIZE:
raise SongpackSecurityError(f"Stem audio too large: {info.file_size} > {MAX_STEM_SIZE}")
total_uncompressed_bytes += info.file_size
if total_uncompressed_bytes > MAX_TOTAL_SIZE:
raise SongpackSecurityError(
f"Total uncompressed size exceeded: {total_uncompressed_bytes} > {MAX_TOTAL_SIZE}"
)
# Extract safely
dest_file = extracted_dir / rel_path
dest_file.parent.mkdir(parents=True, exist_ok=True)
with zf.open(info) as src, open(dest_file, "wb") as dst:
shutil.copyfileobj(src, dst)
# Validate extracted manifest
manifest_file = extracted_dir / "manifest.json"
if not manifest_file.exists():
raise SongpackSecurityError("manifest.json missing in songpack")
try:
with open(manifest_file, encoding="utf-8") as f:
manifest_doc = ManifestDocument.model_validate(json.load(f))
if manifest_doc.format != "songpack":
raise SongpackSecurityError(f"Invalid format: {manifest_doc.format}")
except Exception as e:
raise SongpackSecurityError(f"Invalid manifest.json: {e}") from e
# Atomic copy/move to destination
output_dir = output_dir.resolve()
output_dir.mkdir(parents=True, exist_ok=True)
for item in extracted_dir.iterdir():
target = output_dir / item.name
if target.exists():
if target.is_dir():
shutil.rmtree(target)
else:
target.unlink()
shutil.move(str(item), str(target))
logger.info("Successfully unpacked songpack to %s", output_dir)
return output_dir

View 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
View 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,
}

160
src/unmix/eval/run_eval.py Normal file
View File

@ -0,0 +1,160 @@
"""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
# lyrics = "reference": align the reference's text and line breaks (not its timings) instead of Whisper
lyrics_entry = song_entry.get("lyrics")
lyrics_file = ref_path if lyrics_entry == "reference" else (Path(lyrics_entry) if lyrics_entry else None)
song_out_dir = report_dir / "eval_runs" / name
ctx = PipelineContext(
source_file=audio_path,
output_dir=song_out_dir,
lang=lang,
target_stage="s4_pitch",
lyrics_file=lyrics_file,
)
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

View File

@ -0,0 +1,5 @@
"""Export modules."""
from unmix.export.ultrastar import UltraStarNote, UltraStarSong, export_ultrastar, parse_ultrastar
__all__ = ["export_ultrastar", "parse_ultrastar", "UltraStarSong", "UltraStarNote"]

View File

@ -0,0 +1,478 @@
"""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
# The lyric starts after exactly one separator space; further leading spaces mark a word start
# (leading-space convention) and are normalised to a trailing space on the previous note below.
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)(?: (.*))?$", line)
if match:
ntype, s_beat, dur, pitch, text = match.groups()
text = text or ""
if text.startswith(" "):
text = text.lstrip(" ")
if current_line and not current_line[-1].text.endswith(" "):
current_line[-1].text += " "
note = UltraStarNote(
note_type=ntype,
start_beat=int(s_beat),
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

View 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(),

199
src/unmix/pipeline/align.py Normal file
View File

@ -0,0 +1,199 @@
"""Text-guided word alignment: place given lyrics on the vocals stem with CTC forced alignment.
Used by stage 3 when ``--lyrics`` is given instead of transcribing with Whisper. The lyrics file is either
plain text (one sung line per line) or an UltraStar ``.txt`` (its line structure and text are used, its timings
are ignored).
"""
import re
from pathlib import Path
from typing import Any
import soundfile as sf
# wav2vec2 CTC models with a character vocabulary, already used elsewhere via the torch hub cache.
ALIGN_BUNDLES = {
"en": "WAV2VEC2_ASR_BASE_960H",
"de": "VOXPOPULI_ASR_BASE_10K_DE",
}
STRIDE = 320 # samples per wav2vec2 frame at 16 kHz
SAMPLE_RATE = 16000
FRAME_SEC = STRIDE / SAMPLE_RATE
_SECTION_MARKER = re.compile(r"^\s*[\[(].*[\])]\s*$")
def supported_languages() -> list[str]:
return sorted(ALIGN_BUNDLES)
def read_lyrics_lines(path: Path) -> list[list[str]]:
"""Read lyrics as a list of lines, each a list of display words (original case and punctuation)."""
text = Path(path).read_text(encoding="utf-8", errors="replace")
if is_ultrastar_file(Path(path)):
return _lines_from_ultrastar(Path(path))
lines: list[list[str]] = []
for raw in text.splitlines():
line = raw.strip()
if not line or _SECTION_MARKER.match(line):
continue
words = line.split()
if words:
lines.append(words)
return lines
def is_ultrastar_file(path: Path) -> bool:
text = Path(path).read_text(encoding="utf-8", errors="replace")
head = text.lstrip("")[:2000]
return bool(re.search(r"^#(TITLE|ARTIST|BPM):", head, flags=re.MULTILINE)) and bool(
re.search(r"^[:*FR] +-?\d+ +\d+ +-?\d+", text, flags=re.MULTILINE)
)
def _lines_from_ultrastar(path: Path) -> list[list[str]]:
from unmix.export.ultrastar import parse_ultrastar
song = parse_ultrastar(path)
lines: list[list[str]] = []
for line in song.lines:
words: list[str] = []
cur = ""
for note in line:
cur += note.text.replace("~", "")
if note.text.endswith(" ") and cur.strip():
words.append(cur.strip())
cur = ""
if cur.strip():
words.append(cur.strip())
if words:
lines.append(words)
return lines
def clean_word(word: str, labels: tuple[str, ...] | list[str], lang: str) -> str:
"""Reduce a display word to the character set of the alignment model."""
allowed = set(labels) - {"-", "|"}
w = word.strip().replace("’", "'").replace("`", "'").replace("´", "'")
w = w.upper() if any(c.isupper() for c in allowed) else w.lower()
return "".join(c for c in w if c in allowed)
def compute_emissions(wav_path: Path, model: Any, bundle: Any, window_sec: float = 30.0, ctx_sec: float = 2.0) -> Any:
"""Frame-wise log-probabilities for the whole file, computed in overlapping windows."""
import torch
import torchaudio
data, sr = sf.read(str(wav_path), dtype="float32")
if data.ndim > 1:
data = data.mean(axis=-1)
wav = torch.from_numpy(data)
if sr != bundle.sample_rate:
wav = torchaudio.functional.resample(wav, sr, bundle.sample_rate)
n = wav.shape[0]
win = int(window_sec * SAMPLE_RATE) // STRIDE * STRIDE
ctx = int(ctx_sec * SAMPLE_RATE) // STRIDE * STRIDE
out = torch.zeros(n // STRIDE + 1, len(bundle.get_labels()))
normalize = bool(getattr(bundle, "_normalize_waveform", False))
with torch.inference_mode():
for s0 in range(0, n, win):
a = max(0, s0 - ctx) # always a multiple of STRIDE, so frame indices stay absolute
b = min(n, s0 + win + ctx)
chunk = wav[a:b]
if normalize:
chunk = torch.nn.functional.layer_norm(chunk, chunk.shape)
logits, _ = model(chunk.unsqueeze(0))
logp = torch.log_softmax(logits, dim=-1)[0]
f0 = a // STRIDE
lo = s0 // STRIDE - f0
hi = min(logp.shape[0], min(n, s0 + win) // STRIDE - f0)
out[f0 + lo : f0 + hi] = logp[lo:hi]
return out
def align_words(
emissions: Any, clean_lines: list[list[str]], labels: tuple[str, ...] | list[str]
) -> dict[tuple[int, int], tuple[float, float]]:
"""CTC forced alignment. Returns {(line_idx, word_idx): (start_sec, end_sec)} for every non-empty word."""
import torch
import torchaudio.functional as F
idx = {c: i for i, c in enumerate(labels)}
tokens: list[int] = []
owner: list[tuple[int, int]] = []
for li, words in enumerate(clean_lines):
for wi, w in enumerate(words):
for c in w:
tokens.append(idx[c])
owner.append((li, wi))
if not tokens:
return {}
if emissions.shape[0] < len(tokens):
raise ValueError(
f"Lyrics too long for the audio: {len(tokens)} characters but only {emissions.shape[0]} audio frames."
)
targets = torch.tensor([tokens], dtype=torch.int32)
aligned, scores = F.forced_align(emissions.unsqueeze(0), targets, blank=0)
spans = F.merge_tokens(aligned[0], scores[0].exp())
if len(spans) != len(tokens):
raise ValueError("Forced alignment returned an unexpected number of token spans.")
result: dict[tuple[int, int], tuple[float, float]] = {}
for span, key in zip(spans, owner, strict=True):
s, e = span.start * FRAME_SEC, span.end * FRAME_SEC
cur = result.get(key)
result[key] = (s, e) if cur is None else (min(cur[0], s), max(cur[1], e))
return result
def load_aligner(lang: str) -> tuple[Any, Any]:
"""Return (bundle, model) for a language or raise ValueError for unsupported languages."""
import torchaudio
key = (lang or "").lower()[:2]
if key not in ALIGN_BUNDLES:
raise ValueError(
f"--lyrics alignment supports languages {supported_languages()}, got '{lang}'. "
"Run without --lyrics to transcribe with Whisper."
)
bundle = getattr(torchaudio.pipelines, ALIGN_BUNDLES[key])
return bundle, bundle.get_model().eval()
def lyrics_to_timed_lines(
lyrics: list[list[str]],
vocals_wav: Path,
lang: str,
syllabify: Any,
) -> list[dict[str, Any]]:
"""Align ``lyrics`` to the vocals stem and return stage-3 style lines.
``syllabify(word_text, start, end)`` splits a timed word into syllable dicts.
"""
bundle, model = load_aligner(lang)
labels = bundle.get_labels()
key = lang.lower()[:2]
clean = [[clean_word(w, labels, key) for w in line] for line in lyrics]
emissions = compute_emissions(vocals_wav, model, bundle)
timing = align_words(emissions, clean, labels)
lines: list[dict[str, Any]] = []
for li, words in enumerate(lyrics):
# Words without alignable characters (e.g. "-", digits) get no time and are skipped.
timed = [(wi, w) for wi, w in enumerate(words) if (li, wi) in timing]
if not timed:
continue
syllables: list[dict[str, Any]] = []
for pos, (wi, w) in enumerate(timed):
start, end = timing[(li, wi)]
text = w + (" " if pos < len(timed) - 1 else "")
syllables.extend(syllabify(text, start, max(end, start + 0.02)))
if syllables:
lines.append(
{
"start": syllables[0]["start"],
"end": syllables[-1]["end"],
"text": " ".join(w for _, w in timed),
"syllables": syllables,
}
)
return lines

View File

@ -0,0 +1,85 @@
"""Plain lyrics from LRCLIB (https://lrclib.net) for ``--lyrics-from lrclib``.
Only the text is used. LRCLIB timestamps are line-level and belong to one release of a song, so they are not used
for alignment; the text is aligned to the audio as in ``--lyrics``. Several releases exist per song, so the one whose
length matches the audio is chosen.
Local, personal use only: lyrics are copyrighted and must not be redistributed.
"""
import json
import subprocess
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
API_SEARCH = "https://lrclib.net/api/search"
USER_AGENT = "unmix/0.1 (local analysis tool)"
MAX_DURATION_DIFF_SEC = 5.0
ALTERNATE_VERSION_WORDS = ("live", "acoustic", "remix", "karaoke", "instrumental", "unplugged")
TIMEOUT_SEC = 20
class LyricsLookupError(RuntimeError):
"""Raised when LRCLIB cannot provide a usable text for the song."""
def audio_duration_sec(path: Path) -> float:
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
capture_output=True,
text=True,
check=False,
)
try:
return float(out.stdout.strip())
except ValueError as exc:
raise LyricsLookupError(f"Dauer von {path.name} nicht lesbar (ffprobe)") from exc
def pick_version(results: list[dict[str, Any]], duration_sec: float) -> dict[str, Any]:
"""Choose the release whose length is closest to the audio, among entries with text."""
candidates = [r for r in results if r.get("plainLyrics") and not r.get("instrumental")]
if not candidates:
raise LyricsLookupError("LRCLIB: kein Eintrag mit Text gefunden")
# Prefer studio releases: live, acoustic, remix or karaoke versions only win if nothing else is left.
def rank(r: dict[str, Any]) -> tuple[bool, float]:
name = f"{r.get('albumName') or ''} {r.get('trackName') or ''}".lower()
return (
any(word in name for word in ALTERNATE_VERSION_WORDS),
abs(float(r.get("duration") or 0) - duration_sec),
)
best = min(candidates, key=rank)
diff = abs(float(best.get("duration") or 0) - duration_sec)
if diff > MAX_DURATION_DIFF_SEC:
raise LyricsLookupError(
f"LRCLIB: keine Version mit passender Länge (nächste {best.get('duration')} s, Audio {duration_sec:.0f} s)"
)
return best
def search(artist: str, title: str) -> list[dict[str, Any]]:
query = urllib.parse.urlencode({"track_name": title, "artist_name": artist})
request = urllib.request.Request(f"{API_SEARCH}?{query}", headers={"User-Agent": USER_AGENT})
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SEC) as response:
data = json.load(response)
except (OSError, ValueError) as exc:
raise LyricsLookupError(f"LRCLIB nicht erreichbar: {exc}") from exc
if not isinstance(data, list):
raise LyricsLookupError("LRCLIB: unerwartete Antwort")
return data
def fetch_lyrics_file(artist: str, title: str, duration_sec: float, target_dir: Path) -> tuple[Path, str]:
"""Write the chosen plain text to ``target_dir`` and return (path, human-readable source label)."""
chosen = pick_version(search(artist, title), duration_sec)
target_dir.mkdir(parents=True, exist_ok=True)
safe = "".join(c if c.isalnum() else "_" for c in f"{artist}_{title}")
path = target_dir / f"lrclib_{safe}.txt"
path.write_text(chosen["plainLyrics"].strip() + "\n", encoding="utf-8")
label = f"lrclib: {chosen.get('artistName')} - {chosen.get('trackName')} ({chosen.get('albumName')}, {chosen.get('duration')} s)"
return path, label

View File

@ -2,13 +2,16 @@
import hashlib
import json
import logging
import sys
from abc import ABC, abstractmethod
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("unmix.pipeline")
def compute_file_sha256(file_path: Path, chunk_size: int = 65536) -> str:
@ -32,8 +35,10 @@ class PipelineContext:
quality: str = "best",
force: bool = False,
target_stage: str | None = None,
lyrics_file: Path | None = None,
):
self.source_file = source_file.resolve()
self.lyrics_file = lyrics_file.resolve() if lyrics_file else None
self.output_dir = output_dir.resolve()
self.lang = lang
self.stems = stems
@ -56,15 +61,23 @@ 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,
source_file=SourceFileInfo(
language=self.lang,
source=SourceFileInfo(
filename=self.source_file.name,
path=str(self.source_file),
kind="video"
if self.source_file.suffix.lower() in [".mp4", ".mkv", ".mov", ".webm", ".avi"]
else "audio",
sha256=source_hash,
size_bytes=size_bytes,
),
@ -85,6 +98,20 @@ class Stage(ABC):
model_name: str
model_version: str = "1.0.0"
dependencies: list[str] = []
aliases: list[str] = []
def __init__(
self,
name: str = "",
version: str = "1.0.0",
dependencies: list[str] | None = None,
aliases: list[str] | None = None,
):
if name:
self.name = name
self.version = version
self.dependencies = dependencies if dependencies is not None else list(getattr(self, "dependencies", []))
self.aliases = aliases if aliases is not None else list(getattr(self, "aliases", []))
@abstractmethod
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
@ -123,7 +150,8 @@ class Stage(ABC):
def is_cached(self, ctx: PipelineContext) -> bool:
"""Check if stage output is already computed and valid in cache."""
cache_file = ctx.cache_dir / f"{self.name}.json"
safe_name = self.name.replace(":", "_")
cache_file = ctx.cache_dir / f"{safe_name}.json"
if not cache_file.exists():
return False
@ -142,7 +170,8 @@ class Stage(ABC):
def write_cache_entry(self, ctx: PipelineContext, cache_hash: str) -> None:
"""Record successful stage run in cache."""
cache_file = ctx.cache_dir / f"{self.name}.json"
safe_name = self.name.replace(":", "_")
cache_file = ctx.cache_dir / f"{safe_name}.json"
data = {
"stage": self.name,
"version": self.version,
@ -178,8 +207,26 @@ class PipelineRunner:
def get_stages_to_run(self, ctx: PipelineContext) -> list[Stage]:
"""Resolve ordered list of stages to run."""
if ctx.target_stage:
if ctx.target_stage not in self.stages_by_name:
raise ValueError(f"Unknown target stage: '{ctx.target_stage}'")
target = ctx.target_stage
if target not in self.stages_by_name:
# Check aliases
found = None
for s in self.stages_by_name.values():
if target in s.aliases:
found = s.name
break
if found:
target = found
elif target == "tracks":
# Match all track stages
track_stages = [s for s in self.stages_by_name.values() if s.name.startswith("tracks:")]
if track_stages:
target = track_stages[-1].name
else:
raise ValueError(f"Unknown target stage: '{ctx.target_stage}'")
else:
raise ValueError(f"Unknown target stage: '{ctx.target_stage}'")
# Collect target stage and all its transitive dependencies
needed = set()
@ -189,7 +236,7 @@ class PipelineRunner:
if dep not in needed:
add_deps(dep)
add_deps(ctx.target_stage)
add_deps(target)
selected = [s for s in self.stages_by_name.values() if s.name in needed]
else:
selected = list(self.stages_by_name.values())
@ -218,6 +265,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:
@ -225,6 +275,7 @@ class PipelineRunner:
failed_deps = [d for d in stage.dependencies if d in failed_stages]
if failed_deps:
msg = f"Skipping {stage.name} because dependencies failed: {failed_deps}"
logger.warning(msg)
sys.stderr.write(f"[WARN] {msg}\n")
meta.stages_failed[stage.name] = msg
failed_stages.add(stage.name)
@ -232,11 +283,13 @@ class PipelineRunner:
# Check cache
if not ctx.force and stage.is_cached(ctx):
logger.info("Stage %s is up to date (cached).", stage.name)
sys.stderr.write(f"[INFO] Stage {stage.name} is up to date (cached).\n")
if stage.name not in meta.stages_done:
meta.stages_done.append(stage.name)
continue
logger.info("Running stage: %s...", stage.name)
sys.stderr.write(f"[INFO] Running stage: {stage.name}...\n")
try:
cache_hash = stage.compute_cache_hash(ctx)
@ -259,9 +312,19 @@ class PipelineRunner:
except Exception as e:
err_msg = f"{type(e).__name__}: {str(e)}"
logger.error("Stage %s failed: %s", stage.name, err_msg, exc_info=True)
sys.stderr.write(f"[ERROR] Stage {stage.name} failed: {err_msg}\n")
meta.stages_failed[stage.name] = err_msg
failed_stages.add(stage.name)
ctx.save_meta(meta)
try:
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")
except Exception as e:
logger.warning("Could not update manifest.json: %s", e)
return meta

View File

@ -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)

View File

@ -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):
@ -47,7 +47,6 @@ class StemsStage(Stage):
return {
"stems": ctx.stems,
"quality": ctx.quality,
"segment": 7 if ctx.quality == "fast" else 10,
"shifts": 0 if ctx.quality == "fast" else 1,
}
@ -100,7 +99,6 @@ class StemsStage(Stage):
wav = (wav - ref.mean()) / (ref.std() + 1e-8)
params = self.get_params(ctx)
segment = params["segment"]
shifts = params["shifts"]
# Add batch dimension: [1, 2, samples]
@ -114,7 +112,6 @@ class StemsStage(Stage):
shifts=shifts,
split=True,
overlap=0.25,
segment=segment,
device=device,
progress=False,
)

View File

@ -0,0 +1,372 @@
"""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]:
inputs = [ctx.stems_dir / "vocals.wav"]
if ctx.lyrics_file is not None:
inputs.append(ctx.lyrics_file) # content hash invalidates the cache when the lyrics change
return inputs
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.cache_dir / "lyrics_raw.json"]
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",
"mode": "aligned" if ctx.lyrics_file is not None else "whisper",
}
def _run_aligned(self, ctx: PipelineContext, vocals_wav: Path, lang: str, dic: pyphen.Pyphen) -> None:
"""Place the given lyrics on the vocals stem (CTC forced alignment) instead of transcribing."""
from unmix.pipeline.align import lyrics_to_timed_lines, read_lyrics_lines
assert ctx.lyrics_file is not None
lyrics = read_lyrics_lines(ctx.lyrics_file)
if not lyrics:
raise ValueError(f"No lyrics found in {ctx.lyrics_file}")
self.model_name = "wav2vec2-ctc-forced-alignment"
lines = lyrics_to_timed_lines(
lyrics,
vocals_wav,
lang,
lambda text, start, end: split_word_into_syllables_timed(text, start, end, dic),
)
output_data = {"language": lang, "detected_language": lang, "lines": lines}
output_file = self.get_outputs(ctx)[0]
output_file.parent.mkdir(parents=True, exist_ok=True)
with open(output_file, "w", encoding="utf-8") as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
def run(self, ctx: PipelineContext) -> None:
from faster_whisper import WhisperModel
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")
if ctx.lyrics_file is not None:
self._run_aligned(ctx, vocals_wav, lang, dic)
return
# Determine compute device
device_str = config.get_device(self.name)
compute_type = "float16" if device_str.startswith("cuda") else "int8"
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)

View File

@ -0,0 +1,501 @@
"""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
# Line ends: follow strictly voiced frames (CREPE periodicity) after the last word.
# Short dropouts are always bridged; longer ones (up to the max) only if voicing resumes for a while,
# i.e. a held note with a dropout rather than a breath or consonant.
LINE_END_VOICING_THRESHOLD = 0.7
LINE_END_MAX_GAP_SEC = 0.1
LINE_END_RESUME_MAX_GAP_SEC = 0.3
LINE_END_RESUME_MIN_RUN_SEC = 0.3
def voiced_run_end(
is_voiced: np.ndarray,
t0: float,
hop_sec: float,
max_gap_sec: float,
cap_t: float,
resume_max_gap_sec: float = 0.0,
resume_min_run_sec: float = 0.0,
) -> float:
"""End time of the voiced run starting at ``t0``.
Unvoiced gaps up to ``max_gap_sec`` are always bridged. Gaps up to ``resume_max_gap_sec`` are
bridged if the voiced run that follows lasts at least ``resume_min_run_sec``.
"""
n = len(is_voiced)
k = int(t0 / hop_sec) if hop_sec > 0 else 0
last = k
while k < n and k * hop_sec < cap_t:
if is_voiced[k]:
last = k
k += 1
continue
j = k
while j < n and not is_voiced[j]:
j += 1
if j >= n or j * hop_sec >= cap_t:
break
gap = (j - k) * hop_sec
r = j
while r < n and is_voiced[r]:
r += 1
run = (r - j) * hop_sec
if gap <= max_gap_sec or (gap <= resume_max_gap_sec and run >= resume_min_run_sec):
k = j
else:
break
return (last + 1) * hop_sec
def hz_to_midi(hz: np.ndarray) -> np.ndarray:
"""Convert frequency in Hz to fractional MIDI note numbers."""
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.3.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
all_lines = lyrics_data.get("lines", [])
is_voiced_strict = (periodicity >= LINE_END_VOICING_THRESHOLD) & (pitch_hz > 50)
for line_pos, line_dict in enumerate(all_lines):
sylls = line_dict.get("syllables", [])
if not sylls:
continue
next_line_start = None
for later in all_lines[line_pos + 1 :]:
if later.get("syllables"):
next_line_start = float(later["syllables"][0]["start"])
break
line_counter += 1
line_syllables_raw = []
prev_end = 0.0
for 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)
if idx == len(sylls) - 1:
# Line end: end of the strictly voiced run after the last word (holds sustained vowels)
cap_t = next_line_start - 0.05 if next_line_start is not None else s_end + 3.0
strict_end = voiced_run_end(
is_voiced_strict,
s_start,
hop_sec,
LINE_END_MAX_GAP_SEC,
cap_t,
resume_max_gap_sec=LINE_END_RESUME_MAX_GAP_SEC,
resume_min_run_sec=LINE_END_RESUME_MIN_RUN_SEC,
)
real_end = max(snapped_start + 0.08, min(strict_end, cap_t))
segs = segment_melisma(
snapped_start,
real_end,
frame_times=frame_times,
midi_frames=midi_frames,
is_voiced=is_voiced,
hop_sec=hop_sec,
)
for seg_idx, (seg_start, seg_end, seg_midi) in enumerate(segs):
is_melisma = seg_idx > 0
txt = "~ " if is_melisma else s["text"]
is_word_end = s.get("word_end", False) if seg_idx == len(segs) - 1 else False
s_mask = (frame_times >= seg_start) & (frame_times <= seg_end)
if np.any(s_mask):
conf = float(np.mean(periodicity[s_mask]))
else:
conf = 0.5
line_syllables_raw.append(
{
"text": txt,
"start": seg_start,
"end": seg_end,
"midi": seg_midi,
"confidence": float(np.clip(conf, 0.0, 1.0)),
"word_end": is_word_end,
}
)
prev_end = line_syllables_raw[-1]["end"]
# Prevent overlapping within line
for i in range(len(line_syllables_raw) - 1):
if line_syllables_raw[i]["end"] > line_syllables_raw[i + 1]["start"]:
line_syllables_raw[i]["end"] = line_syllables_raw[i + 1]["start"]
# Apply octave error correction within phrase
corrected_sylls = correct_octave_errors(line_syllables_raw)
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

View File

@ -0,0 +1,102 @@
"""Stage 5: Beat and downbeat tracking -> tempo.json."""
from pathlib import Path
from typing import Any
import soundfile as sf
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):
"""Stage 5 tracks beats and downbeats and builds a clean Tempo-Map."""
name = "s5_tempo"
version = "1.0.0"
model_name = "beat_this"
model_version = "1.1.0"
dependencies = ["s2_stems"]
def __init__(self, model_name: str = "beat_this"):
self.model_name = model_name
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
drums_path = ctx.stems_dir / "drums.wav"
inst_path = ctx.stems_dir / "instrumental.wav"
if drums_path.exists():
return [drums_path]
return [inst_path]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "tempo.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {
"model": "final0",
"min_tempo_change_bpm": 4.0,
}
def run(self, ctx: PipelineContext) -> None:
input_audio = self.get_inputs(ctx)[0]
if not input_audio.exists():
raise FileNotFoundError(f"Input audio for tempo tracking not found: {input_audio}")
beats = None
downbeats = None
# 1. Try beat_this deep learning model
try:
from beat_this.inference import File2Beats
device_str = config.get_device(self.name)
if device_str.startswith("cuda"):
import torch
if not torch.cuda.is_available():
device_str = "cpu"
file2beats = File2Beats(checkpoint_path="final0", device=device_str)
beats, downbeats = file2beats(str(input_audio))
self.model_name = "beat_this-final0"
except Exception:
# 2. Fallback to librosa beat tracking if beat_this is offline or fails
import librosa
y, sr = librosa.load(str(input_audio), sr=22050, mono=True)
tempo_est, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
beats = librosa.frames_to_time(beat_frames, sr=sr)
# Estimate downbeats as every 4th beat
downbeats = beats[::4] if len(beats) >= 4 else beats
self.model_name = "librosa-beat_track"
# Build clean tempo map
params = self.get_params(ctx)
tempo_doc = build_tempo_map_from_beats(
beats,
downbeats,
min_tempo_change_bpm=params.get("min_tempo_change_bpm", 4.0),
)
tempo_doc.schema_version = "1.0"
tempo_doc.generated_by = GeneratedBy(
stage=self.name,
model=self.model_name,
model_version=self.version,
params=params,
)
# Save tempo.json
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(tempo_doc.model_dump_json(indent=2))
# Generate click track for auditory verification (saved in .cache/click_track.wav)
info = sf.info(str(input_audio))
duration = info.duration
click_wav = generate_click_track(tempo_doc, duration_sec=duration)
click_out_path = ctx.cache_dir / "click_track.wav"
sf.write(str(click_out_path), click_wav, 44100, subtype="PCM_16")

View File

@ -0,0 +1,317 @@
"""Stage 6: Chord recognition -> chords.json with beat-synchronous quantization."""
import json
import re
from pathlib import Path
from typing import Any
import librosa
import numpy as np
import soundfile as sf
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"]
def parse_harte_chord(label: str) -> tuple[str | None, str | None, str | None]:
"""Parse Harte chord label into (root, quality, bass).
Examples:
- 'C' -> ('C', 'maj', None)
- 'Am' -> ('A', 'min', None)
- 'G7' -> ('G', '7', None)
- 'Dsus4' -> ('D', 'sus4', None)
- 'F/A' -> ('F', 'maj', 'A')
- 'N' -> (None, None, None)
"""
clean = label.strip()
if not clean or clean.upper() in ("N", "NONE", "NO CHORD"):
return None, None, None
# Check for bass note (slash chord): F/A
bass = None
if "/" in clean:
parts = clean.split("/", 1)
clean = parts[0]
bass = parts[1].strip()
# Match Root (e.g. C, C#, Db, Eb, etc.)
match = re.match(r"^([A-G][#b]?)(.*)$", clean)
if not match:
return clean, None, bass
root, rest = match.groups()
# Determine quality
rest = rest.strip()
if not rest or rest == "maj":
quality = "maj"
elif rest in ("m", "min"):
quality = "min"
elif rest in ("7", "dom7"):
quality = "7"
elif rest in ("m7", "min7"):
quality = "min7"
elif rest in ("maj7", "M7"):
quality = "maj7"
elif "sus4" in rest:
quality = "sus4"
elif "sus2" in rest:
quality = "sus2"
elif "dim" in rest:
quality = "dim"
elif "aug" in rest:
quality = "aug"
else:
quality = rest
return root, quality, bass
# Krumhansl-Schmuckler Key Profiles for key detection
MAJOR_PROFILE = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
MINOR_PROFILE = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
def estimate_key(chroma_mean: np.ndarray) -> str:
"""Estimate musical key from mean chromagram profile."""
best_key = "C"
best_corr = -1.0
chroma_norm = chroma_mean - np.mean(chroma_mean)
for i, pc in enumerate(PITCH_CLASSES):
# Major correlation
maj_roll = np.roll(MAJOR_PROFILE, i)
maj_norm = maj_roll - np.mean(maj_roll)
corr_maj = float(np.corrcoef(chroma_norm, maj_norm)[0, 1])
if corr_maj > best_corr:
best_corr = corr_maj
best_key = f"{pc}"
# Minor correlation
min_roll = np.roll(MINOR_PROFILE, i)
min_norm = min_roll - np.mean(min_roll)
corr_min = float(np.corrcoef(chroma_norm, min_norm)[0, 1])
if corr_min > best_corr:
best_corr = corr_min
best_key = f"{pc}m"
return best_key
def extract_chords_template(audio_data: np.ndarray, sr: int) -> list[tuple[float, str]]:
"""Chroma-based chord template recognition as baseline/comparison."""
if audio_data.ndim > 1:
audio_data = audio_data.mean(axis=-1)
# Compute Chroma CQT
hop_length = 2048
chroma = librosa.feature.chroma_cqt(y=audio_data, sr=sr, hop_length=hop_length)
times = librosa.frames_to_time(np.arange(chroma.shape[1]), sr=sr, hop_length=hop_length)
# 12 Major and 12 Minor chord templates
templates: list[tuple[str, np.ndarray]] = []
for i, root in enumerate(PITCH_CLASSES):
# Major triad: root, +4, +7
maj = np.zeros(12)
maj[i] = 1.0
maj[(i + 4) % 12] = 1.0
maj[(i + 7) % 12] = 1.0
templates.append((root, maj / np.linalg.norm(maj)))
# Minor triad: root, +3, +7
min_t = np.zeros(12)
min_t[i] = 1.0
min_t[(i + 3) % 12] = 1.0
min_t[(i + 7) % 12] = 1.0
templates.append((f"{root}m", min_t / np.linalg.norm(min_t)))
raw_chords: list[tuple[float, str]] = []
for t_idx, t_sec in enumerate(times):
frame = chroma[:, t_idx]
norm = np.linalg.norm(frame)
if norm < 1e-4:
raw_chords.append((float(t_sec), "N"))
continue
frame_norm = frame / norm
best_chord = "N"
best_sim = -1.0
for chord_name, template in templates:
sim = float(np.dot(frame_norm, template))
if sim > best_sim:
best_sim = sim
best_chord = chord_name
raw_chords.append((float(t_sec), best_chord))
return raw_chords
class ChordsStage(Stage):
"""Stage 6 recognizes musical chords and quantizes them onto the beat grid."""
name = "s6_chords"
version = "1.0.0"
model_name = "chordino"
model_version = "1.0.0"
dependencies = ["s5_tempo"]
def __init__(self, backend: str = "chordino"):
self.backend = backend
self.model_name = backend
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "instrumental.wav",
ctx.output_dir / "tempo.json",
]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "chords.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {
"backend": self.backend,
"quantization": "beat",
}
def run(self, ctx: PipelineContext) -> None:
inst_path, tempo_path = self.get_inputs(ctx)
if not inst_path.exists():
raise FileNotFoundError(f"Instrumental stem not found: {inst_path}")
if not tempo_path.exists():
raise FileNotFoundError(f"tempo.json not found: {tempo_path}")
with open(tempo_path, encoding="utf-8") as f:
tempo_doc = TempoDocument.model_validate(json.load(f))
audio_data, sr = sf.read(str(inst_path), dtype="float32")
# Estimate key and save in meta.json
mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data
chroma = librosa.feature.chroma_cqt(y=mono_audio, sr=sr)
detected_key_str = estimate_key(chroma.mean(axis=1))
from unmix.schema.meta import KeyInfo
if detected_key_str.endswith("m"):
key_tonic = detected_key_str[:-1]
key_mode = "minor"
else:
key_tonic = detected_key_str
key_mode = "major"
meta = ctx.load_or_init_meta()
meta.key = KeyInfo(tonic=key_tonic, mode=key_mode, confidence=0.8)
ctx.save_meta(meta)
params = self.get_params(ctx)
backend = params.get("backend", "chordino")
time_chord_pairs: list[tuple[float, str]] = []
if backend == "chordino":
try:
from chord_extractor import ChordExtractor
extractor = ChordExtractor()
chord_changes = extractor.extract(str(inst_path))
for change in chord_changes:
time_chord_pairs.append((float(change.timestamp), str(change.chord)))
except Exception:
# Fallback to template if chordino vamp is unavailable
time_chord_pairs = extract_chords_template(audio_data, sr)
self.model_name = "chroma-template"
else:
time_chord_pairs = extract_chords_template(audio_data, sr)
self.model_name = "chroma-template"
# Beat-synchronous quantization
info = sf.info(str(inst_path))
total_duration_sec = info.duration
total_beats = int(np.ceil(sec_to_beat(total_duration_sec, tempo_doc)))
total_beats = max(1, total_beats)
# Sample dominant chord per beat
beat_chords: list[str] = []
for b in range(total_beats):
b_start_sec = beat_to_sec(float(b), tempo_doc)
b_end_sec = beat_to_sec(float(b + 1), tempo_doc)
# Find chords active in this beat interval
active = [ch for t, ch in time_chord_pairs if b_start_sec <= t < b_end_sec]
if active:
# Most frequent chord in this beat
dom = max(set(active), key=active.count)
else:
# Chord active before b_start_sec
prior = [ch for t, ch in time_chord_pairs if t <= b_start_sec]
dom = prior[-1] if prior else "N"
beat_chords.append(dom)
# Merge consecutive identical beat chords into ChordEvent segments
chord_events: list[ChordEvent] = []
cur_chord = beat_chords[0]
cur_start_beat = 0.0
for b_idx in range(1, len(beat_chords)):
ch = beat_chords[b_idx]
if ch != cur_chord:
root, quality, bass = parse_harte_chord(cur_chord)
chord_events.append(
ChordEvent(
start_beat=cur_start_beat,
end_beat=float(b_idx),
label=cur_chord,
root=root,
quality=quality,
bass=bass,
confidence=0.85 if cur_chord != "N" else 0.5,
source="auto",
)
)
cur_chord = ch
cur_start_beat = float(b_idx)
# Final segment
root, quality, bass = parse_harte_chord(cur_chord)
chord_events.append(
ChordEvent(
start_beat=cur_start_beat,
end_beat=float(len(beat_chords)),
label=cur_chord,
root=root,
quality=quality,
bass=bass,
confidence=0.85 if cur_chord != "N" else 0.5,
source="auto",
)
)
for idx, ev in enumerate(chord_events):
ev.id = f"c_{idx + 1:04d}"
chords_doc = ChordsDocument(
schema_version="1.0",
generated_by=GeneratedBy(
stage=self.name,
model=self.model_name,
model_version=self.version,
params=params,
),
chords=chord_events,
)
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(chords_doc.model_dump_json(indent=2))

View File

@ -0,0 +1,23 @@
"""Stage 7: Strumming pattern analysis -> tracks/guitar.json (wrapper for s7_tracks/strumming)."""
from unmix.pipeline.s7_tracks.strumming import (
StrummingTrackStage,
aggregate_strum_patterns,
estimate_strum_direction,
)
class StrummingStage(StrummingTrackStage):
"""Backward-compatible alias for StrummingTrackStage."""
def __init__(self, track_name: str = "guitar", grid: str = "8th") -> None:
super().__init__(track_name=track_name, grid=grid) # type: ignore[arg-type]
self.name = "s7_strumming"
__all__ = [
"StrummingStage",
"StrummingTrackStage",
"estimate_strum_direction",
"aggregate_strum_patterns",
]

View File

@ -0,0 +1,5 @@
"""Instrument track stages (tracks/<name>.json)."""
from unmix.pipeline.s7_tracks.strumming import StrummingTrackStage
__all__ = ["StrummingTrackStage"]

View File

@ -0,0 +1,261 @@
"""Stage 7 sub-stage: Strumming track analysis -> tracks/guitar.json (experimental)."""
import json
from pathlib import Path
from typing import Any
import librosa
import numpy as np
import soundfile as sf
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(
audio: np.ndarray,
sr: int,
onset_sec: float,
beat: float,
) -> tuple[StrumDirection, float]:
"""Estimate strumming direction (down vs up) from spectral centroid gradient and beat phase."""
start_sample = int(onset_sec * sr)
window_samples = int(sr * 0.05)
end_sample = min(len(audio), start_sample + window_samples)
direction: StrumDirection = "down"
confidence = 0.5
if end_sample - start_sample > 256:
chunk = audio[start_sample:end_sample]
centroids = librosa.feature.spectral_centroid(y=chunk, sr=sr, hop_length=128)[0]
if len(centroids) >= 2:
centroid_slope = centroids[-1] - centroids[0]
if centroid_slope > 0:
direction = "down"
confidence += 0.1
else:
direction = "up"
confidence += 0.1
beat_frac = beat - np.floor(beat)
if beat_frac < 0.25 or beat_frac > 0.75:
if direction == "down":
confidence = min(0.85, confidence + 0.15)
else:
direction = "down"
confidence = 0.6
elif 0.35 <= beat_frac <= 0.65:
if direction == "up":
confidence = min(0.85, confidence + 0.15)
else:
direction = "up"
confidence = 0.6
return direction, round(confidence, 2)
def aggregate_strum_patterns(
events: list[StrumEvent],
total_beats: float,
grid: StrumGrid = "8th",
pattern_beats: float = 4.0,
section_beats: float = 16.0,
) -> list[StrumPattern]:
"""Condense discrete strumming events into representative pattern strings (e.g. 'D . D U . U D U')."""
if not events:
return []
grid_step = 0.5 if grid == "8th" else 0.25
slots_per_pattern = int(round(pattern_beats / grid_step))
patterns: list[StrumPattern] = []
num_sections = int(np.ceil(total_beats / section_beats))
for sec_idx in range(num_sections):
sec_start = sec_idx * section_beats
sec_end = min(total_beats, sec_start + section_beats)
sec_events = [e for e in events if sec_start <= e.beat < sec_end]
if not sec_events:
continue
slot_votes: list[list[str]] = [[] for _ in range(slots_per_pattern)]
for e in sec_events:
rel_beat = (e.beat - sec_start) % pattern_beats
slot_idx = int(round(rel_beat / grid_step)) % slots_per_pattern
symbol = "D" if e.direction == "down" else "U"
slot_votes[slot_idx].append(symbol)
pattern_chars: list[str] = []
for votes in slot_votes:
if not votes:
pattern_chars.append(".")
else:
d_count = votes.count("D")
u_count = votes.count("U")
pattern_chars.append("D" if d_count >= u_count else "U")
pattern_str = " ".join(pattern_chars)
patterns.append(
StrumPattern(
id=f"p_{len(patterns) + 1:04d}",
start_beat=round(sec_start, 3),
end_beat=round(sec_end, 3),
grid=grid,
pattern=pattern_str,
confidence=0.5,
source="auto",
locked=False,
)
)
return patterns
class StrummingTrackStage(Stage):
"""Stage 7: Track: Strumming -> tracks/guitar.json (experimental)."""
def __init__(self, track_name: str = "guitar", grid: StrumGrid = "8th"):
super().__init__(
name="tracks:strumming",
version="1.0.0",
dependencies=["s2_stems", "s5_tempo"],
aliases=["strumming", "s7_strumming", "s7", "guitar", "tracks"],
)
self.track_name = track_name
self.grid = grid
self.model_name = "librosa-onset+spectral-gradient"
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
guitar_stem = ctx.output_dir / "stems" / "guitar.wav"
inst_stem = ctx.output_dir / "stems" / "instrumental.wav"
audio_stem = guitar_stem if guitar_stem.exists() else inst_stem
return [audio_stem, ctx.output_dir / "tempo.json"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.output_dir / "tracks" / f"{self.track_name}.json",
# backward compatibility for legacy readers
ctx.output_dir / "strumming.json",
]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {
"track_name": self.track_name,
"grid": self.grid,
"pattern_beats": 4.0,
"section_beats": 16.0,
"status": "experimental",
}
def run(self, ctx: PipelineContext) -> None:
audio_path, tempo_path = self.get_inputs(ctx)
if not audio_path.exists():
raise FileNotFoundError(f"Input audio for strumming not found: {audio_path}")
if not tempo_path.exists():
raise FileNotFoundError(f"tempo.json not found: {tempo_path}")
with open(tempo_path, encoding="utf-8") as f:
tempo_doc = TempoDocument.model_validate(json.load(f))
audio_data, sr = sf.read(str(audio_path), dtype="float32")
mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data
params = self.get_params(ctx)
grid: StrumGrid = params.get("grid", "8th")
grid_step = 0.5 if grid == "8th" else 0.25
# Detect onsets
onset_env = librosa.onset.onset_strength(y=mono_audio, sr=sr, hop_length=512)
onset_frames = librosa.onset.onset_detect(
onset_envelope=onset_env,
sr=sr,
hop_length=512,
backtrack=True,
)
onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=512)
max_env = float(np.max(onset_env)) if len(onset_env) > 0 and np.max(onset_env) > 0 else 1.0
# Preserve locked events if existing track file exists (Section 9)
track_output = ctx.output_dir / "tracks" / f"{self.track_name}.json"
locked_events: list[StrumEvent] = []
if track_output.exists():
try:
with open(track_output, encoding="utf-8") as f:
old_doc = TrackDocument.model_validate(json.load(f))
locked_events = [
StrumEvent.model_validate(e)
for e in old_doc.events
if getattr(e, "locked", False) or getattr(e, "source", "") == "manual"
]
except Exception:
pass
raw_events_by_grid: dict[float, StrumEvent] = {round(e.beat, 3): e for e in locked_events}
for frame_idx, t_sec in zip(onset_frames, onset_times, strict=False):
beat = sec_to_beat(float(t_sec), tempo_doc)
if beat < 0:
continue
quantized_beat = round(beat / grid_step) * grid_step
q_key = round(quantized_beat, 3)
if q_key in raw_events_by_grid and raw_events_by_grid[q_key].locked:
# Locked item takes precedence
continue
strength = float(np.clip(onset_env[frame_idx] / max_env, 0.1, 1.0))
direction, conf = estimate_strum_direction(mono_audio, sr, float(t_sec), quantized_beat)
if q_key not in raw_events_by_grid or strength > raw_events_by_grid[q_key].strength:
raw_events_by_grid[q_key] = StrumEvent(
id=f"e_{len(raw_events_by_grid) + 1:04d}",
beat=q_key,
direction=direction,
strength=round(strength, 2),
confidence=conf,
source="auto",
locked=False,
)
sorted_events = sorted(raw_events_by_grid.values(), key=lambda e: e.beat)
for idx, ev in enumerate(sorted_events):
if not ev.id or ev.id == "e_0001":
ev.id = f"e_{idx + 1:04d}"
total_duration = sf.info(str(audio_path)).duration
total_beats = sec_to_beat(total_duration, tempo_doc)
patterns = aggregate_strum_patterns(sorted_events, total_beats, grid=grid)
stem_used = "guitar" if (ctx.output_dir / "stems" / "guitar.wav").exists() else "instrumental"
doc = TrackDocument(
schema_version="1.0",
name=self.track_name,
instrument="guitar",
kind="strumming",
stem=stem_used,
generated_by=GeneratedBy(
stage=self.name,
model=self.model_name,
model_version=self.version,
params=params,
),
events=sorted_events,
patterns=patterns,
)
# Write tracks/guitar.json
track_output.parent.mkdir(parents=True, exist_ok=True)
with open(track_output, "w", encoding="utf-8") as f:
f.write(doc.model_dump_json(indent=2))
# Also write legacy strumming.json for compatibility
legacy_output = ctx.output_dir / "strumming.json"
with open(legacy_output, "w", encoding="utf-8") as f:
f.write(doc.model_dump_json(indent=2))

View File

@ -0,0 +1,56 @@
"""Input modes of a song package.
Mode 1 (audio only): Whisper transcribes the lyrics. vocals_source = "whisper"
Mode 2 (UltraStar): notes and timings of the .txt are the result. vocals_source = "reference_ultrastar"
Mode 3 (lyrics): given text is aligned to the audio. vocals_source = "lyrics_aligned"
Mode 2 overwrites vocals.json with the ground truth. Without the helpers below, a later run would take that
ground truth for the AI prediction and keep a stale pitch cache.
"""
import json
from pathlib import Path
from unmix.schema.vocals import VocalsDocument
PITCH_CACHE = "s4_pitch.json"
AI_BACKUP = "vocals_ai.json"
GROUND_TRUTH = "reference_ultrastar"
def mode_label(lyrics_given: bool) -> str:
return "lyrics_aligned" if lyrics_given else "whisper"
def previous_vocals_source(meta_file: Path) -> str | None:
if not meta_file.exists():
return None
try:
return json.loads(meta_file.read_text(encoding="utf-8")).get("vocals_source")
except (OSError, ValueError, AttributeError):
return None
def prepare_ai_vocals(output_dir: Path, cache_dir: Path, vocals_source: str) -> VocalsDocument | None:
"""Return the AI prediction for evaluation, never a ground truth written by an earlier run.
While vocals.json holds the AI result, a copy is kept in the cache. Once it holds the ground truth,
only that copy is valid. Returns None if no AI result is available.
"""
backup = cache_dir / AI_BACKUP
if vocals_source == GROUND_TRUTH:
if not backup.exists():
return None
return VocalsDocument.model_validate(json.loads(backup.read_text(encoding="utf-8")))
vocals_json = output_dir / "vocals.json"
if not vocals_json.exists():
return None
doc = VocalsDocument.model_validate(json.loads(vocals_json.read_text(encoding="utf-8")))
cache_dir.mkdir(parents=True, exist_ok=True)
backup.write_text(doc.model_dump_json(indent=2), encoding="utf-8")
return doc
def invalidate_pitch_cache(cache_dir: Path) -> None:
"""Drop the cached pitch stage so the next run recomputes vocals.json instead of reusing a ground truth."""
(cache_dir / PITCH_CACHE).unlink(missing_ok=True)

View File

@ -0,0 +1,68 @@
"""Songpack data schemas."""
from unmix.schema.base import DataSource, EditableItem, GeneratedBy, SongPackageBase
from unmix.schema.chords import ChordEvent, ChordsDocument
from unmix.schema.manifest import (
FileRole,
GeneratorInfo,
ManifestDocument,
ManifestFileInfo,
ManifestStageInfo,
StageStatus,
StemName,
)
from unmix.schema.meta import (
AudioRefInfo,
CapoSuggestion,
KeyInfo,
MetaDocument,
ModelInfo,
SourceFileInfo,
)
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
__all__ = [
"DataSource",
"EditableItem",
"GeneratedBy",
"SongPackageBase",
"SourceFileInfo",
"AudioRefInfo",
"KeyInfo",
"CapoSuggestion",
"ModelInfo",
"MetaDocument",
"ManifestDocument",
"ManifestFileInfo",
"ManifestStageInfo",
"FileRole",
"StemName",
"StageStatus",
"GeneratorInfo",
"VocalSyllable",
"VocalLine",
"VocalsDocument",
"VocalsF0Document",
"TempoAnchor",
"TimeSignature",
"TimeSignatureEntry",
"TempoDocument",
"ChordEvent",
"ChordsDocument",
"StrumDirection",
"StrumEvent",
"StrumPattern",
"StrummingDocument",
"NoteEvent",
"DrumEvent",
"DrumPiece",
"TrackDocument",
"TrackKind",
]

View File

@ -1,4 +1,4 @@
"""Base classes and shared types for Song-Paket schemas."""
"""Base classes and shared types for Songpack schemas."""
from typing import Any, Literal
@ -18,8 +18,19 @@ class GeneratedBy(BaseModel):
params: dict[str, Any] = Field(default_factory=dict)
class EditableItem(BaseModel):
"""Base model for editable items carrying identity, provenance, and lock state."""
model_config = ConfigDict(extra="ignore")
id: str
source: DataSource = "auto"
confidence: float | None = Field(default=None, ge=0.0, le=1.0)
locked: bool = False
class SongPackageBase(BaseModel):
"""Base schema for all Song-Paket JSON files with schema version and generation info."""
"""Base schema for all Songpack JSON files with schema version and generation info."""
model_config = ConfigDict(extra="ignore")

View File

@ -1,27 +1,26 @@
"""Schema for chords.json."""
from pydantic import BaseModel, ConfigDict, Field
from pydantic import ConfigDict, Field
from songsplit.schema.base import DataSource, SongPackageBase
from unmix.schema.base import EditableItem, SongPackageBase
class ChordEvent(BaseModel):
"""A chord segment defined in beats."""
class ChordEvent(EditableItem):
"""A chord segment defined in musical beats."""
model_config = ConfigDict(extra="ignore")
id: str = "c_0001"
start_beat: float
end_beat: float
label: str
root: str | None = None
quality: str | None = None
bass: str | None = None
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
source: DataSource = "auto"
class ChordsDocument(SongPackageBase):
"""Song-Paket chords document (chords.json)."""
"""Songpack chords document (chords.json)."""
model_config = ConfigDict(extra="ignore")

View File

@ -0,0 +1,83 @@
"""Schema for manifest.json."""
from typing import Any, Literal
from uuid import uuid4
from pydantic import BaseModel, ConfigDict, Field
FileRole = Literal[
"meta",
"tempo",
"vocals",
"vocals_f0",
"chords",
"track",
"stem",
"ultrastar",
"cover",
]
StemName = Literal[
"vocals",
"instrumental",
"drums",
"bass",
"guitar",
"piano",
"other",
]
StageStatus = Literal["done", "failed", "stale", "skipped"]
class GeneratorInfo(BaseModel):
"""Information about generator tool."""
model_config = ConfigDict(extra="ignore")
name: str = "unmix"
version: str = "0.1.0"
class ManifestFileInfo(BaseModel):
"""Entry describing a file inside the songpack."""
model_config = ConfigDict(extra="ignore")
path: str
role: FileRole
schema_version: str | None = None
sha256: str
size: int
stem: StemName | None = None
class ManifestStageInfo(BaseModel):
"""Execution status and metadata for a pipeline stage."""
model_config = ConfigDict(extra="ignore")
status: StageStatus
input_hash: str | None = None
model: str | None = None
params: dict[str, Any] = Field(default_factory=dict)
finished: str | None = None
error: str | None = None
class ManifestDocument(BaseModel):
"""Songpack manifest document (manifest.json)."""
model_config = ConfigDict(extra="ignore")
format: Literal["songpack"] = "songpack"
schema_version: str = "1.0"
id: str = Field(default_factory=lambda: str(uuid4()))
created: str
modified: str
generator: GeneratorInfo = Field(default_factory=GeneratorInfo)
variant: Literal["full", "data"] = "full"
audio_included: bool = True
license: str | None = None
files: list[ManifestFileInfo] = Field(default_factory=list)
stages: dict[str, ManifestStageInfo] = Field(default_factory=dict)

101
src/unmix/schema/meta.py Normal file
View File

@ -0,0 +1,101 @@
"""Schema for meta.json."""
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from unmix.schema.base import SongPackageBase
class SourceFileInfo(BaseModel):
"""Information about the original source audio/video file."""
model_config = ConfigDict(extra="ignore")
filename: str = ""
path: str = ""
kind: Literal["audio", "video"] = "audio"
sha256: str = ""
size_bytes: int = 0
class AudioRefInfo(BaseModel):
"""Audio reference information for fingerprinting and alignment."""
model_config = ConfigDict(extra="ignore")
duration_sec: float = Field(ge=0.0)
samplerate: int = 44100
pcm_sha256: str = ""
class KeyInfo(BaseModel):
"""Estimated musical key."""
model_config = ConfigDict(extra="ignore")
tonic: str
mode: str = "major"
confidence: float | None = None
def __eq__(self, other: object) -> bool:
if isinstance(other, str):
short = f"{self.tonic}m" if self.mode == "minor" else self.tonic
return other in (short, self.tonic)
return super().__eq__(other)
def __str__(self) -> str:
return f"{self.tonic}m" if self.mode == "minor" else self.tonic
class CapoSuggestion(BaseModel):
"""Capo suggestion and chord shape root."""
model_config = ConfigDict(extra="ignore")
capo: int = 0
shapes_in: str | None = None
class ModelInfo(BaseModel):
"""Information about an AI model used during processing."""
model_config = ConfigDict(extra="ignore")
stage: str
name: str
version: str
class MetaDocument(SongPackageBase):
"""Songpack metadata document (meta.json)."""
model_config = ConfigDict(extra="ignore", populate_by_name=True)
title: str | None = None
artist: str | None = None
album: str | None = None
year: int | None = None
language: str | None = None
duration_sec: float = Field(default=0.0, ge=0.0)
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
capo: int | None = None
capo_suggestion: CapoSuggestion | None = None
ultrastar: dict[str, str] = Field(default_factory=dict)
models_used: list[ModelInfo] = Field(default_factory=list)
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["whisper", "lyrics_aligned", "reference_ultrastar", "ai"] = "ai"
lyrics_source: str | None = None # where the aligned text came from, e.g. "file: x.txt" or "lrclib: ..."
training_diff: dict[str, Any] | None = None
# Backward compatibility helper
@property
def source_file(self) -> SourceFileInfo:
return self.source

View File

@ -0,0 +1,17 @@
"""Backward-compatible re-export of strumming types from tracks."""
from unmix.schema.tracks import (
StrumDirection,
StrumEvent,
StrumGrid,
StrummingDocument,
StrumPattern,
)
__all__ = [
"StrumDirection",
"StrumEvent",
"StrumGrid",
"StrumPattern",
"StrummingDocument",
]

47
src/unmix/schema/tempo.py Normal file
View File

@ -0,0 +1,47 @@
"""Schema for tempo.json."""
from pydantic import ConfigDict, Field
from unmix.schema.base import EditableItem, SongPackageBase
class TempoAnchor(EditableItem):
"""A tempo anchor defining constant BPM starting from a given time/beat."""
model_config = ConfigDict(extra="ignore")
id: str = "t_0001"
sec: float
beat: float
bpm: float = Field(gt=0.0)
class TimeSignatureEntry(EditableItem):
"""Musical time signature starting at a given beat."""
model_config = ConfigDict(extra="ignore")
id: str = "ts_0001"
beat: float = 0.0
numerator: int = Field(default=4, gt=0)
denominator: int = Field(default=4, gt=0)
# Backward-compatible alias
TimeSignature = TimeSignatureEntry
class TempoDocument(SongPackageBase):
"""Songpack tempo document (tempo.json)."""
model_config = ConfigDict(extra="ignore")
anchors: list[TempoAnchor] = Field(default_factory=list)
time_signatures: list[TimeSignatureEntry] = Field(default_factory=list)
downbeat_offset: int = 0
@property
def time_signature(self) -> TimeSignatureEntry:
if self.time_signatures:
return self.time_signatures[0]
return TimeSignatureEntry(beat=0.0, numerator=4, denominator=4)

View File

@ -0,0 +1,90 @@
"""Schema for instrument tracks (tracks/<name>.json)."""
from typing import Any, Literal
from pydantic import ConfigDict, Field
from unmix.schema.base import EditableItem, SongPackageBase
TrackKind = Literal["strumming", "notes", "drums"]
StrumDirection = Literal["down", "up", "mute", "unknown"]
StrumGrid = Literal["quarter", "8th", "triplet", "16th"]
DrumPiece = Literal[
"kick",
"snare",
"hihat_closed",
"hihat_open",
"tom",
"crash",
"ride",
"other",
]
class StrumEvent(EditableItem):
"""A single strumming event."""
model_config = ConfigDict(extra="ignore")
id: str = "e_0001"
beat: float
direction: StrumDirection
strength: float = Field(default=1.0, ge=0.0, le=1.0)
class StrumPattern(EditableItem):
"""An aggregated strumming pattern over a beat range."""
model_config = ConfigDict(extra="ignore")
id: str = "p_0001"
start_beat: float
end_beat: float
grid: StrumGrid = "8th"
pattern: str
class NoteEvent(EditableItem):
"""A single musical note event (e.g. for bass, piano, lead guitar)."""
model_config = ConfigDict(extra="ignore")
id: str = "n_0001"
start_beat: float
end_beat: float
midi: int
velocity: float = Field(default=0.8, ge=0.0, le=1.0)
class DrumEvent(EditableItem):
"""A single drum hit event."""
model_config = ConfigDict(extra="ignore")
id: str = "d_0001"
beat: float
piece: DrumPiece
strength: float = Field(default=1.0, ge=0.0, le=1.0)
class TrackDocument(SongPackageBase):
"""Instrument track document (tracks/<name>.json)."""
model_config = ConfigDict(extra="ignore")
name: str
instrument: str
kind: TrackKind
stem: str | None = None
events: list[Any] = Field(default_factory=list)
patterns: list[StrumPattern] = Field(default_factory=list)
# Backward-compatible alias
class StrummingDocument(SongPackageBase):
"""Backward compatibility wrapper for strumming."""
model_config = ConfigDict(extra="ignore")
events: list[StrumEvent] = Field(default_factory=list)
patterns: list[StrumPattern] = Field(default_factory=list)

View File

@ -0,0 +1,50 @@
"""Schema for vocals.json."""
from typing import Literal
from pydantic import ConfigDict, Field
from unmix.schema.base import EditableItem, SongPackageBase
SyllableType = Literal["normal", "golden", "freestyle", "rap"]
class VocalSyllable(EditableItem):
"""A single syllable with timing, pitch, type, and word boundary."""
model_config = ConfigDict(extra="ignore")
id: str = "s_0001"
text: str
start: float = Field(ge=0.0)
end: float = Field(ge=0.0)
midi: float | None = None
type: SyllableType = "normal"
word_end: bool = False
golden: bool = False
def model_post_init(self, __context: object) -> None:
if self.golden and self.type == "normal":
self.type = "golden"
elif self.type == "golden":
self.golden = True
class VocalLine(EditableItem):
"""A line of lyrics consisting of one or more syllables."""
model_config = ConfigDict(extra="ignore")
id: str = "l_0001"
voice: int = 0
start: float = Field(ge=0.0)
end: float = Field(ge=0.0)
syllables: list[VocalSyllable] = Field(default_factory=list)
class VocalsDocument(SongPackageBase):
"""Songpack vocals document (vocals.json)."""
model_config = ConfigDict(extra="ignore")
lines: list[VocalLine] = Field(default_factory=list)

View File

@ -0,0 +1,16 @@
"""Schema for vocals_f0.json."""
from pydantic import ConfigDict, Field
from unmix.schema.base import SongPackageBase
class VocalsF0Document(SongPackageBase):
"""Raw fundamental frequency track of the vocal stem (vocals_f0.json)."""
model_config = ConfigDict(extra="ignore")
hop_sec: float = 0.01
start_sec: float = 0.0
hz: list[float | None] = Field(default_factory=list)
confidence: list[float] = Field(default_factory=list)

View 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"]

View 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

218
src/unmix/tempo.py Normal file
View File

@ -0,0 +1,218 @@
"""Tempo-Map conversion between seconds and musical beats and click track generation.
As defined in the concept:
- Vocals are in seconds
- Chords and strumming are in beats
- Conversion ONLY through sec_to_beat() and beat_to_sec().
"""
from bisect import bisect_right
import numpy as np
from unmix.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]:
"""Return anchors sorted by time/beat, raising ValueError if empty."""
if not tempo_map.anchors:
raise ValueError("Tempo map has no anchors defined.")
return sorted(tempo_map.anchors, key=lambda a: a.sec)
def sec_to_beat(sec: float, tempo_map: TempoDocument) -> float:
"""Convert time in seconds to musical beat (float quarter notes).
Constant tempo is assumed between consecutive anchors.
The last anchor applies until the end of the song.
Extrapolation is used before the first anchor.
"""
anchors = _get_sorted_anchors(tempo_map)
sec_points = [a.sec for a in anchors]
idx = bisect_right(sec_points, sec) - 1
if idx < 0:
# Before the first anchor -> extrapolate using the first anchor's tempo
anchor = anchors[0]
delta_sec = sec - anchor.sec
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
anchor = anchors[idx]
delta_sec = sec - anchor.sec
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float:
"""Convert musical beat (float quarter notes) to time in seconds.
Constant tempo is assumed between consecutive anchors.
The last anchor applies until the end of the song.
Extrapolation is used before the first anchor.
"""
anchors = _get_sorted_anchors(tempo_map)
beat_points = [a.beat for a in anchors]
idx = bisect_right(beat_points, beat) - 1
if idx < 0:
# Before the first anchor -> extrapolate using the first anchor's tempo
anchor = anchors[0]
delta_beat = beat - anchor.beat
return anchor.sec + delta_beat * (60.0 / anchor.bpm)
anchor = anchors[idx]
delta_beat = beat - anchor.beat
return anchor.sec + delta_beat * (60.0 / anchor.bpm)
def build_tempo_map_from_beats(
beat_times: list[float] | np.ndarray,
downbeat_times: list[float] | np.ndarray | None = None,
min_tempo_change_bpm: float = 4.0,
min_beats_for_change: int = 6,
) -> TempoDocument:
"""Construct a clean TempoDocument from raw detected beat and downbeat timestamps.
Only inserts new anchors for true persistent tempo changes, keeping single-anchor
representation for songs with steady tempo.
"""
beats = np.sort(np.asarray(beat_times, dtype=np.float64))
if len(beats) < 2:
# Fallback default 120 BPM
return TempoDocument(
anchors=[TempoAnchor(sec=float(beats[0]) if len(beats) == 1 else 0.0, beat=0.0, bpm=120.0)],
time_signature=TimeSignature(numerator=4, denominator=4),
downbeat_offset=0,
)
# Determine time signature and downbeat offset
time_sig = TimeSignature(numerator=4, denominator=4)
downbeat_offset = 0
if downbeat_times is not None and len(downbeat_times) >= 2:
downbeats = np.sort(np.asarray(downbeat_times, dtype=np.float64))
# Match downbeats to nearest beat indices
downbeat_indices = []
for db in downbeats:
nearest_idx = int(np.argmin(np.abs(beats - db)))
if np.abs(beats[nearest_idx] - db) < 0.2: # within 200ms
downbeat_indices.append(nearest_idx)
if len(downbeat_indices) >= 2:
intervals = np.diff(downbeat_indices)
median_num = int(round(float(np.median(intervals))))
if median_num in (3, 4, 6):
time_sig = TimeSignature(numerator=median_num, denominator=4)
downbeat_offset = downbeat_indices[0] % time_sig.numerator
# Calculate initial tempo from the beginning of the song
ibis = np.diff(beats) # Inter-beat intervals in seconds
valid_mask = (ibis > 0.15) & (ibis < 2.0) # 30 to 400 BPM
clean_ibis = ibis[valid_mask]
if len(clean_ibis) == 0:
base_bpm = 120.0
else:
init_window = clean_ibis[: max(4, min_beats_for_change)]
base_bpm = float(np.median(60.0 / init_window))
# Segment into anchors if persistent tempo shifts occur
anchors = []
current_sec = float(beats[0])
current_beat = 0.0
current_bpm = base_bpm
anchors.append(
TempoAnchor(
sec=round(current_sec, 3),
beat=round(current_beat, 3),
bpm=round(current_bpm, 2),
)
)
# Detect sustained tempo changes across window
i = 0
while i <= len(ibis) - min_beats_for_change:
win_ibis = ibis[i : i + min_beats_for_change]
# Check all intervals are valid
if np.all((win_ibis > 0.15) & (win_ibis < 2.0)):
win_bpms = 60.0 / win_ibis
win_bpm = float(np.median(win_bpms))
win_std = float(np.std(win_bpms))
# Trigger change only when the new section is stable and genuinely different
if abs(win_bpm - current_bpm) >= min_tempo_change_bpm and win_std < (min_tempo_change_bpm * 0.75):
new_sec = float(beats[i])
# Calculate beat position from previous anchor
elapsed_sec = new_sec - current_sec
new_beat = current_beat + elapsed_sec * (current_bpm / 60.0)
current_sec = new_sec
current_beat = new_beat
current_bpm = win_bpm
anchors.append(
TempoAnchor(
sec=round(current_sec, 3),
beat=round(current_beat, 3),
bpm=round(current_bpm, 2),
)
)
i += min_beats_for_change
continue
i += 1
ts_entry = TimeSignature(
id="ts_0001",
beat=0.0,
numerator=time_sig.numerator,
denominator=time_sig.denominator,
)
for idx, a in enumerate(anchors):
a.id = f"t_{idx + 1:04d}"
return TempoDocument(
anchors=anchors,
time_signatures=[ts_entry],
downbeat_offset=downbeat_offset,
)
def generate_click_track(
tempo_map: TempoDocument,
duration_sec: float,
sr: int = 44100,
) -> np.ndarray:
"""Generate a click track waveform aligned to the TempoDocument.
Downbeats receive a distinct high click (1600 Hz), regular beats a low click (800 Hz).
"""
total_samples = int(duration_sec * sr)
click_audio = np.zeros(total_samples, dtype=np.float32)
click_len = int(sr * 0.02) # 20 ms
t_click = np.linspace(0, 0.02, click_len, endpoint=False)
envelope = np.exp(-t_click / 0.005).astype(np.float32)
high_click = (0.7 * np.sin(2 * np.pi * 1600.0 * t_click) * envelope).astype(np.float32)
low_click = (0.5 * np.sin(2 * np.pi * 800.0 * t_click) * envelope).astype(np.float32)
# Step through beats from 0 until duration_sec
num = tempo_map.time_signature.numerator
offset = tempo_map.downbeat_offset
beat = 0.0
while True:
sec = beat_to_sec(beat, tempo_map)
if sec > duration_sec:
break
if sec >= 0:
idx = int(sec * sr)
if idx + click_len <= total_samples:
# Check if this beat is a downbeat
is_downbeat = (int(round(beat)) % num) == (offset % num)
sample_click = high_click if is_downbeat else low_click
click_audio[idx : idx + click_len] += sample_click
beat += 1.0
return click_audio

130
tests/test_align.py Normal file
View File

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

75
tests/test_chords.py Normal file
View File

@ -0,0 +1,75 @@
"""Unit tests for Harte chord parsing, key detection, and template chord recognition."""
import numpy as np
from unmix.pipeline.s6_chords import estimate_key, extract_chords_template, parse_harte_chord
def test_parse_harte_chord_labels():
# Major triad
root, quality, bass = parse_harte_chord("C")
assert root == "C"
assert quality == "maj"
assert bass is None
# Minor triad
root, quality, bass = parse_harte_chord("Am")
assert root == "A"
assert quality == "min"
assert bass is None
# Dominant 7th
root, quality, bass = parse_harte_chord("G7")
assert root == "G"
assert quality == "7"
assert bass is None
# Sus4
root, quality, bass = parse_harte_chord("Dsus4")
assert root == "D"
assert quality == "sus4"
assert bass is None
# Slash chord
root, quality, bass = parse_harte_chord("F/A")
assert root == "F"
assert quality == "maj"
assert bass == "A"
# No chord
root, quality, bass = parse_harte_chord("N")
assert root is None
assert quality is None
assert bass is None
def test_estimate_key():
# Synthetic C major profile (peaks at C, E, G -> indices 0, 4, 7)
c_maj_chroma = np.zeros(12)
c_maj_chroma[0] = 5.0
c_maj_chroma[4] = 4.0
c_maj_chroma[7] = 4.5
assert estimate_key(c_maj_chroma) == "C"
# Synthetic A minor profile (peaks at A, C, E -> indices 9, 0, 4)
a_min_chroma = np.zeros(12)
a_min_chroma[9] = 5.0
a_min_chroma[0] = 4.0
a_min_chroma[4] = 4.5
assert estimate_key(a_min_chroma) == "Am"
def test_extract_chords_template_synthetic():
sr = 22050
duration = 1.0
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
# Synthesize C major: C4 (261.63), E4 (329.63), G4 (392.00)
c_chord = (np.sin(2 * np.pi * 261.63 * t) + np.sin(2 * np.pi * 329.63 * t) + np.sin(2 * np.pi * 392.00 * t)).astype(
np.float32
)
raw_chords = extract_chords_template(c_chord, sr)
labels = [ch for _, ch in raw_chords]
# Dominant detected chord should be "C"
assert labels.count("C") > len(labels) * 0.5

View File

@ -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

98
tests/test_container.py Normal file
View File

@ -0,0 +1,98 @@
"""Tests for songpack container packing and secure unpacking."""
import zipfile
from pathlib import Path
import pytest
from unmix.container import (
SongpackSecurityError,
build_manifest_for_dir,
pack_songpack,
unpack_songpack,
)
def test_build_manifest(tmp_path: Path):
song_dir = tmp_path / "song"
song_dir.mkdir()
(song_dir / "meta.json").write_text('{"schema_version": "1.0"}', encoding="utf-8")
stems_dir = song_dir / "stems"
stems_dir.mkdir()
(stems_dir / "vocals.wav").write_bytes(b"RIFFdummyWAVdata")
manifest = build_manifest_for_dir(song_dir, variant="full")
assert manifest.format == "songpack"
assert manifest.variant == "full"
assert manifest.audio_included is True
paths = [f.path for f in manifest.files]
assert "meta.json" in paths
assert "stems/vocals.wav" in paths
manifest_data = build_manifest_for_dir(song_dir, variant="data")
assert manifest_data.variant == "data"
assert manifest_data.audio_included is False
assert "stems/vocals.wav" not in [f.path for f in manifest_data.files]
def test_pack_and_unpack_roundtrip(tmp_path: Path):
song_dir = tmp_path / "song"
song_dir.mkdir()
(song_dir / "meta.json").write_text('{"title": "Test Song"}', encoding="utf-8")
(song_dir / "tempo.json").write_text('{"schema_version": "1.0"}', encoding="utf-8")
stems_dir = song_dir / "stems"
stems_dir.mkdir()
(stems_dir / "vocals.wav").write_bytes(b"audio-bytes-vocals")
tracks_dir = song_dir / "tracks"
tracks_dir.mkdir()
(tracks_dir / "guitar.json").write_text('{"kind": "strumming"}', encoding="utf-8")
archive_path = tmp_path / "song.songpack"
pack_songpack(song_dir, archive_path)
assert archive_path.is_file()
# Check zip properties
with zipfile.ZipFile(archive_path, "r") as zf:
infolist = zf.infolist()
# First entry must be manifest.json
assert infolist[0].filename == "manifest.json"
# Audio stems must be ZIP_STORED
stem_info = zf.getinfo("stems/vocals.wav")
assert stem_info.compress_type == zipfile.ZIP_STORED
# JSON must be ZIP_DEFLATED
meta_info = zf.getinfo("meta.json")
assert meta_info.compress_type == zipfile.ZIP_DEFLATED
# Unpack
dest_dir = tmp_path / "unpacked_song"
unpack_songpack(archive_path, dest_dir)
assert (dest_dir / "manifest.json").is_file()
assert (dest_dir / "meta.json").is_file()
assert (dest_dir / "tracks" / "guitar.json").is_file()
assert (dest_dir / "stems" / "vocals.wav").read_bytes() == b"audio-bytes-vocals"
def test_unpack_security_traversal(tmp_path: Path):
bad_zip = tmp_path / "traversal.songpack"
with zipfile.ZipFile(bad_zip, "w") as zf:
zf.writestr("manifest.json", '{"format": "songpack", "schema_version": "1.0", "created": "", "modified": ""}')
zf.writestr("../evil.txt", "evil")
dest = tmp_path / "out"
with pytest.raises(SongpackSecurityError, match="Unsafe path"):
unpack_songpack(bad_zip, dest)
def test_unpack_security_max_entries(tmp_path: Path):
bad_zip = tmp_path / "many_entries.songpack"
with zipfile.ZipFile(bad_zip, "w") as zf:
zf.writestr("manifest.json", '{"format": "songpack", "schema_version": "1.0", "created": "", "modified": ""}')
for i in range(70):
zf.writestr(f"tracks/track_{i}.json", "{}")
dest = tmp_path / "out"
with pytest.raises(SongpackSecurityError, match="Too many archive entries"):
unpack_songpack(bad_zip, dest)

146
tests/test_demo_package.py Normal file
View File

@ -0,0 +1,146 @@
"""Test the demo song package in examples/demo_song according to Songpack spec v1.0."""
import json
from pathlib import Path
import soundfile as sf
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():
demo_dir = Path("examples/demo_song")
assert demo_dir.is_dir()
required_files = [
"manifest.json",
"meta.json",
"tempo.json",
"vocals.json",
"vocals_f0.json",
"chords.json",
"tracks/guitar.json",
"export/song.txt",
"strumming.json",
"song.txt",
]
for rf in required_files:
p = demo_dir / rf
assert p.is_file(), f"Missing {rf} in demo package"
stems_dir = demo_dir / "stems"
assert stems_dir.is_dir()
for stem_name in ["vocals.wav", "instrumental.wav", "drums.wav", "bass.wav", "other.wav"]:
p = stems_dir / stem_name
assert p.is_file(), f"Missing stem {stem_name} in demo package"
def test_demo_package_schemas():
demo_dir = Path("examples/demo_song")
# Manifest
manifest_raw = json.loads((demo_dir / "manifest.json").read_text(encoding="utf-8"))
manifest = ManifestDocument.model_validate(manifest_raw)
assert manifest.format == "songpack"
assert manifest.schema_version == "1.0"
assert manifest.variant == "full"
assert manifest.audio_included is True
# Meta
meta_raw = json.loads((demo_dir / "meta.json").read_text(encoding="utf-8"))
meta = MetaDocument.model_validate(meta_raw)
assert meta.title == "Demo Song"
assert meta.schema_version == "1.0"
assert meta.duration_sec > 0
assert meta.audio_ref is not None
assert meta.key.tonic == "A"
assert meta.key.mode == "minor"
# Tempo
tempo_raw = json.loads((demo_dir / "tempo.json").read_text(encoding="utf-8"))
tempo = TempoDocument.model_validate(tempo_raw)
assert len(tempo.anchors) >= 1
assert tempo.anchors[0].bpm == 120.0
assert tempo.time_signature.numerator == 4
# Vocals
vocals_raw = json.loads((demo_dir / "vocals.json").read_text(encoding="utf-8"))
vocals = VocalsDocument.model_validate(vocals_raw)
assert len(vocals.lines) >= 1
assert len(vocals.lines[0].syllables) == 3
assert vocals.lines[0].syllables[0].text == "Hel"
assert vocals.lines[0].syllables[1].word_end is True
# Vocals F0
f0_raw = json.loads((demo_dir / "vocals_f0.json").read_text(encoding="utf-8"))
f0 = VocalsF0Document.model_validate(f0_raw)
assert f0.hop_sec == 0.01
assert len(f0.hz) > 0
# Chords
chords_raw = json.loads((demo_dir / "chords.json").read_text(encoding="utf-8"))
chords = ChordsDocument.model_validate(chords_raw)
assert len(chords.chords) == 2
assert chords.chords[0].label == "Am"
# Tracks (guitar.json)
track_raw = json.loads((demo_dir / "tracks" / "guitar.json").read_text(encoding="utf-8"))
track = TrackDocument.model_validate(track_raw)
assert track.kind == "strumming"
assert track.name == "guitar"
assert len(track.events) == 4
assert len(track.patterns) == 1
# Strumming (backward compat)
strumming_raw = json.loads((demo_dir / "strumming.json").read_text(encoding="utf-8"))
strumming = StrummingDocument.model_validate(strumming_raw)
assert len(strumming.events) == 4
assert len(strumming.patterns) == 1
def test_demo_package_audio_properties():
demo_dir = Path("examples/demo_song")
stems = ["vocals.wav", "instrumental.wav", "drums.wav", "bass.wav", "other.wav"]
for s in stems:
path = demo_dir / "stems" / s
info = sf.info(str(path))
assert info.samplerate == 44100
assert info.channels == 2
assert abs(info.duration - 3.0) < 0.01
def test_demo_package_ultrastar_roundtrip():
demo_dir = Path("examples/demo_song")
song_txt = demo_dir / "export" / "song.txt"
parsed = parse_ultrastar(song_txt)
assert parsed.title == "Demo Song"
assert parsed.artist == "Synthetic Artist"
assert len(parsed.lines) == 1
assert len(parsed.lines[0]) == 3
texts = [s.text for s in parsed.lines[0]]
assert texts == ["Hel", "lo ", "world"]
def test_demo_package_pack_unpack_roundtrip(tmp_path: Path):
demo_dir = Path("examples/demo_song")
archive_out = tmp_path / "demo.songpack"
pack_songpack(demo_dir, archive_out)
assert archive_out.is_file()
unpacked_dir = tmp_path / "demo_unpacked"
unpack_songpack(archive_out, unpacked_dir)
assert (unpacked_dir / "manifest.json").is_file()
assert (unpacked_dir / "tracks" / "guitar.json").is_file()
assert (unpacked_dir / "stems" / "vocals.wav").is_file()

93
tests/test_lyrics.py Normal file
View File

@ -0,0 +1,93 @@
"""Unit tests for Stage 3 lyrics hyphenation and proportional timing."""
import pyphen
from unmix.pipeline.s3_lyrics import hyphenate_word, split_word_into_syllables_timed
def test_hyphenate_word_german():
dic = pyphen.Pyphen(lang="de_DE")
# "Guten" -> ["Gu", "ten"]
sylls = hyphenate_word("Guten", dic)
assert len(sylls) == 2
assert "".join(sylls) == "Guten"
# With trailing punctuation and space: "Morgen! "
sylls_punct = hyphenate_word("Morgen! ", dic)
assert len(sylls_punct) == 2
assert "".join(sylls_punct) == "Morgen! "
def test_hyphenate_word_english():
dic = pyphen.Pyphen(lang="en_US")
# "Hello" -> ["Hel", "lo"]
sylls = hyphenate_word("Hello", dic)
assert len(sylls) == 2
assert "".join(sylls) == "Hello"
def test_split_word_into_syllables_timed():
dic = pyphen.Pyphen(lang="en_US")
# "Hello " duration 1.0s (from 10.0 to 11.0)
timed = split_word_into_syllables_timed("Hello ", 10.0, 11.0, dic)
assert len(timed) == 2
assert timed[0]["start"] == 10.0
assert timed[1]["end"] == 11.0
assert timed[0]["end"] == timed[1]["start"]
# 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

193
tests/test_metrics.py Normal file
View File

@ -0,0 +1,193 @@
"""Unit tests for evaluation metrics (timing, pitch, pitch class, octave offset, WER)."""
import pytest
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():
raw = "Hallo, Welt! Wie geht's?"
norm = normalize_text_for_wer(raw)
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": "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),
]
],
)
pred_doc = VocalsDocument(
lines=[
VocalLine(
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, word_end=True),
],
)
]
)
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": "120", "GAP": "1000"},
lines=[
[
# 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 70ms, has octave error (-1 octave: 48.2 vs 60.0), duration 0.6s
pred_doc = VocalsDocument(
lines=[
VocalLine(
start=1.07,
end=1.67,
syllables=[
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(70.0, abs=1.0)
assert metrics["fraction_within_50ms"] == pytest.approx(0.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(100.0, abs=1.0)
# Strict pitch should fail (48 != 60)
assert metrics["strict_pitch_accuracy"] == pytest.approx(0.0)
# 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)

View File

@ -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:

98
tests/test_pipeline_m2.py Normal file
View File

@ -0,0 +1,98 @@
"""End-to-end integration test for Milestone 2 (Lyrics, Pitch, UltraStar export, and Eval runner)."""
import json
from pathlib import Path
import numpy as np
import soundfile as sf
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):
song_dir = tmp_path / "song_pkg"
stems_dir = song_dir / "stems"
cache_dir = song_dir / ".cache"
stems_dir.mkdir(parents=True, exist_ok=True)
cache_dir.mkdir(parents=True, exist_ok=True)
# 1. Create a 2.0s 440 Hz (A4 = MIDI 69) test vocal stem
sr = 16000
t = np.linspace(0, 2.0, int(sr * 2.0), endpoint=False)
sine_wave = 0.5 * np.sin(2 * np.pi * 440.0 * t).astype(np.float32)
vocals_wav = stems_dir / "vocals.wav"
sf.write(str(vocals_wav), sine_wave, sr)
# 2. Write mock lyrics in .cache/lyrics_raw.json (two syllables)
lyrics_data = {
"language": "de",
"lines": [
{
"start": 0.2,
"end": 1.8,
"text": "Hal-lo ",
"syllables": [
{"text": "Hal-", "start": 0.2, "end": 0.9},
{"text": "lo ", "start": 0.9, "end": 1.8},
],
}
],
}
(cache_dir / "lyrics_raw.json").write_text(json.dumps(lyrics_data, indent=2))
# 3. Write meta.json
meta = MetaDocument(
title="Integration Song",
artist="Test Singer",
language="de",
duration_sec=2.0,
source_file=SourceFileInfo(path=str(vocals_wav), sha256="fakehash", size_bytes=len(sine_wave)),
created_at="2026-11-02T10:00:00Z",
)
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
# 4. Run PitchStage (CREPE) with crepe_model="tiny" for fast test execution
ctx = PipelineContext(
source_file=vocals_wav,
output_dir=song_dir,
quality="fast", # uses tiny crepe model
)
pitch_stage = PitchStage()
pitch_stage.run(ctx)
vocals_json = song_dir / "vocals.json"
assert vocals_json.exists()
with open(vocals_json, encoding="utf-8") as f:
doc = VocalsDocument.model_validate(json.load(f))
assert len(doc.lines) == 1
sylls = doc.lines[0].syllables
assert len(sylls) == 2
# Sine wave is at 440 Hz -> MIDI 69.0
assert 68.0 <= sylls[0].midi <= 70.0
assert 68.0 <= sylls[1].midi <= 70.0
assert sylls[0].confidence > 0.5
# 5. Export UltraStar song.txt
txt_path = export_ultrastar(song_dir)
assert txt_path.exists()
song = parse_ultrastar(txt_path)
assert song.title == "Integration Song"
assert len(song.lines) == 1
assert len(song.lines[0]) == 2
# Pitch relative to C4 (60) -> 69 - 60 = 9
assert song.lines[0][0].pitch == 9
# 6. Evaluate predicted vocals against ground truth UltraStar song
metrics = evaluate_vocals(doc, song)
assert metrics["mae_timing_ms"] <= 50.0
assert metrics["strict_pitch_accuracy"] >= 0.99
assert metrics["octave_equiv_pitch_accuracy"] >= 0.99
assert metrics["wer"] == 0.0

94
tests/test_pipeline_m3.py Normal file
View File

@ -0,0 +1,94 @@
"""Integration test for Milestone 3 (Stage 5 Tempo Map and Click Track)."""
import json
from pathlib import Path
import numpy as np
import pytest
import soundfile as sf
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):
song_dir = tmp_path / "song_pkg"
stems_dir = song_dir / "stems"
cache_dir = song_dir / ".cache"
stems_dir.mkdir(parents=True, exist_ok=True)
cache_dir.mkdir(parents=True, exist_ok=True)
# 1. Generate 6.0s synthetic drum beats at 120 BPM (beats at 0.0, 0.5, 1.0, 1.5, ...)
sr = 44100
duration_sec = 6.0
audio = np.zeros(int(sr * duration_sec), dtype=np.float32)
# Place a 10ms burst pulse every 0.5s
burst_len = int(sr * 0.01)
burst = np.sin(2 * np.pi * 300.0 * np.linspace(0, 0.01, burst_len, endpoint=False)).astype(np.float32)
for t in np.arange(0.5, 5.5, 0.5):
idx = int(t * sr)
audio[idx : idx + burst_len] += burst
drums_wav = stems_dir / "drums.wav"
sf.write(str(drums_wav), audio, sr)
# 2. Write meta.json
meta = MetaDocument(
title="Tempo Test Song",
artist="Test Drummer",
duration_sec=duration_sec,
source_file=SourceFileInfo(path=str(drums_wav), sha256="fakehash", size_bytes=len(audio)),
created_at="2026-11-02T10:00:00Z",
)
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
# 3. Write minimal vocals.json
vocals = VocalsDocument(
lines=[
VocalLine(
start=1.0,
end=2.0,
syllables=[VocalSyllable(text="Beat", start=1.0, end=2.0, midi=60.0)],
)
]
)
(song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2))
# 4. Run TempoStage
ctx = PipelineContext(source_file=drums_wav, output_dir=song_dir)
stage = TempoStage()
stage.run(ctx)
# 5. Verify tempo.json
tempo_json = song_dir / "tempo.json"
assert tempo_json.exists()
with open(tempo_json, encoding="utf-8") as f:
doc = TempoDocument.model_validate(json.load(f))
assert len(doc.anchors) >= 1
# Detected tempo should be around 120 BPM (or 60/240 subharmonic)
bpm = doc.anchors[0].bpm
assert (
bpm == pytest.approx(120.0, abs=5.0)
or bpm == pytest.approx(60.0, abs=5.0)
or bpm == pytest.approx(240.0, abs=10.0)
)
# 6. Verify click track audio generated
click_track = cache_dir / "click_track.wav"
assert click_track.exists()
click_data, click_sr = sf.read(str(click_track))
assert len(click_data) == len(audio)
# 7. Test UltraStar export derives BPM/GAP from tempo.json
txt_path = export_ultrastar(song_dir)
assert txt_path.exists()
song = parse_ultrastar(txt_path)
assert song.bpm == pytest.approx(doc.anchors[0].bpm, abs=1.0)

76
tests/test_pipeline_m4.py Normal file
View File

@ -0,0 +1,76 @@
"""Integration test for Milestone 4 (Stage 6 Beat-Quantized Chord Recognition)."""
import json
from pathlib import Path
import numpy as np
import soundfile as sf
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):
song_dir = tmp_path / "song_pkg"
stems_dir = song_dir / "stems"
stems_dir.mkdir(parents=True, exist_ok=True)
# 1. Synthesize 4.0s instrumental audio:
# 2.0s C major (261.63, 329.63, 392.00) + 2.0s A minor (220.0, 261.63, 329.63)
sr = 22050
t_half = np.linspace(0, 2.0, int(sr * 2.0), endpoint=False)
c_major = (
np.sin(2 * np.pi * 261.63 * t_half) + np.sin(2 * np.pi * 329.63 * t_half) + np.sin(2 * np.pi * 392.00 * t_half)
).astype(np.float32)
a_minor = (
np.sin(2 * np.pi * 220.00 * t_half) + np.sin(2 * np.pi * 261.63 * t_half) + np.sin(2 * np.pi * 329.63 * t_half)
).astype(np.float32)
inst_audio = np.concatenate([c_major, a_minor])
inst_wav = stems_dir / "instrumental.wav"
sf.write(str(inst_wav), inst_audio, sr)
# 2. Prepare tempo.json: 120 BPM starting at 0.0s (0.5s per beat)
# 4.0s = 8 beats total (0.0 to 4.0 beat is C, 4.0 to 8.0 beat is Am)
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.0, beat=0.0, bpm=120.0)])
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
# 3. Prepare meta.json
meta = MetaDocument(
title="Chord Test Song",
artist="Test Pianist",
duration_sec=4.0,
source_file=SourceFileInfo(path=str(inst_wav), sha256="fakehash", size_bytes=len(inst_audio)),
created_at="2026-11-02T10:00:00Z",
)
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
# 4. Run ChordsStage with template backend
ctx = PipelineContext(source_file=inst_wav, output_dir=song_dir)
stage = ChordsStage(backend="template")
stage.run(ctx)
chords_json = song_dir / "chords.json"
assert chords_json.exists()
with open(chords_json, encoding="utf-8") as f:
doc = ChordsDocument.model_validate(json.load(f))
assert len(doc.chords) >= 1
labels = [c.label for c in doc.chords]
assert "C" in labels or "Am" in labels
# Check beat-based timing
for ch in doc.chords:
assert ch.start_beat >= 0.0
assert ch.end_beat > ch.start_beat
assert ch.confidence > 0.0
# 5. Verify meta.json updated with key
updated_meta = ctx.load_or_init_meta()
assert updated_meta.key in ("C", "Am")

77
tests/test_pipeline_m5.py Normal file
View File

@ -0,0 +1,77 @@
"""Integration test for Milestone 5 (Stage 7 Strumming Analysis)."""
import json
from pathlib import Path
import numpy as np
import soundfile as sf
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):
song_dir = tmp_path / "song_pkg"
stems_dir = song_dir / "stems"
stems_dir.mkdir(parents=True, exist_ok=True)
# 1. Synthesize 4.0s audio with strumming acoustic pulses
sr = 22050
duration_sec = 4.0
audio = np.zeros(int(sr * duration_sec), dtype=np.float32)
# Pulses every 0.25s (8th notes at 120 BPM: 0.5s per quarter beat -> 0.25s per 8th note)
pulse_len = int(sr * 0.05)
t_pulse = np.linspace(0, 0.05, pulse_len, endpoint=False)
pulse = (np.sin(2 * np.pi * 350.0 * t_pulse) * np.exp(-t_pulse / 0.01)).astype(np.float32)
for onset_t in np.arange(0.25, 3.75, 0.25):
idx = int(onset_t * sr)
audio[idx : idx + pulse_len] += pulse
guitar_wav = stems_dir / "guitar.wav"
sf.write(str(guitar_wav), audio, sr)
# 2. Prepare tempo.json at 120 BPM starting at 0.0s
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.0, beat=0.0, bpm=120.0)])
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
# 3. Prepare meta.json
meta = MetaDocument(
title="Strumming Test Song",
artist="Test Guitarist",
duration_sec=duration_sec,
source_file=SourceFileInfo(path=str(guitar_wav), sha256="fakehash", size_bytes=len(audio)),
created_at="2026-11-02T10:00:00Z",
)
(song_dir / "meta.json").write_text(meta.model_dump_json(indent=2))
# 4. Run StrummingStage
ctx = PipelineContext(source_file=guitar_wav, output_dir=song_dir)
stage = StrummingStage(grid="8th")
stage.run(ctx)
strum_json = song_dir / "strumming.json"
assert strum_json.exists()
with open(strum_json, encoding="utf-8") as f:
doc = StrummingDocument.model_validate(json.load(f))
assert len(doc.events) > 0
for e in doc.events:
# Quantized to 8th note grid (multiples of 0.5 beats)
assert (e.beat * 2).is_integer()
assert e.direction in ("down", "up")
assert 0.0 <= e.strength <= 1.0
assert 0.0 <= e.confidence <= 1.0
# Verify marked as experimental in generated_by metadata
assert doc.generated_by is not None
assert doc.generated_by.params.get("status") == "experimental"
# Patterns generated
assert len(doc.patterns) > 0
assert doc.patterns[0].grid == "8th"

75
tests/test_pitch.py Normal file
View File

@ -0,0 +1,75 @@
"""Unit tests for Stage 4 pitch processing (Hz to MIDI and octave error correction)."""
import numpy as np
import pytest
from unmix.pipeline.s4_pitch import correct_octave_errors, hz_to_midi
def test_hz_to_midi_standards():
# A4 = 440 Hz -> MIDI 69
# A3 = 220 Hz -> MIDI 57
# C4 = 261.6256 Hz -> MIDI 60
hz = np.array([440.0, 220.0, 261.6256])
midi = hz_to_midi(hz)
assert midi[0] == pytest.approx(69.0, abs=0.01)
assert midi[1] == pytest.approx(57.0, abs=0.01)
assert midi[2] == pytest.approx(60.0, abs=0.01)
def test_correct_octave_errors():
# Line with an octave spike in the middle: 60, 72 (+12 jump), 61
syllables = [
{"text": "A", "midi": 60.0},
{"text": "B", "midi": 72.0}, # Isolated octave jump
{"text": "C", "midi": 61.0},
]
corrected = correct_octave_errors(syllables)
assert corrected[0]["midi"] == 60.0
assert corrected[1]["midi"] == pytest.approx(60.0) # Corrected from 72 down to 60
assert corrected[2]["midi"] == 61.0
def test_no_correction_for_legitimate_contour():
# Gradual rise: 60 -> 64 -> 67 (C major triad arpeggio)
syllables = [
{"text": "A", "midi": 60.0},
{"text": "B", "midi": 64.0},
{"text": "C", "midi": 67.0},
]
corrected = correct_octave_errors(syllables)
assert corrected[1]["midi"] == 64.0
def test_voiced_run_end_bridges_short_gaps():
import numpy as np
from unmix.pipeline.s4_pitch import voiced_run_end
hop = 0.01
v = np.zeros(300, dtype=bool)
v[100:150] = True # 1.00-1.50 s
v[155:200] = True # gap of 0.05 s, then voiced until 2.00 s
v[260:290] = True # separate run after a 0.6 s gap
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=5.0) == pytest.approx(2.0)
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.0, cap_t=5.0) == pytest.approx(1.5)
# cap stops the run
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=1.3) <= 1.31
def test_voiced_run_end_bridges_longer_gap_only_if_voicing_resumes():
import numpy as np
from unmix.pipeline.s4_pitch import voiced_run_end
hop = 0.01
v = np.zeros(400, dtype=bool)
v[100:150] = True # 1.00-1.50 s
v[170:230] = True # gap 0.20 s, then a long run (0.60 s) until 2.30 s
v[250:260] = True # gap 0.20 s, then a short run (0.10 s)
kwargs = {"resume_max_gap_sec": 0.3, "resume_min_run_sec": 0.3}
assert voiced_run_end(v, 1.0, hop, 0.1, 5.0, **kwargs) == pytest.approx(2.3)
# without the resume rule the 0.2 s gap ends the run
assert voiced_run_end(v, 1.0, hop, 0.1, 5.0) == pytest.approx(1.5)

View File

@ -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):

View File

@ -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

View File

@ -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:
@ -69,10 +69,8 @@ def test_stems_stage_chunking_params(tmp_path: Path):
ctx_fast = PipelineContext(source_file=source, output_dir=out_dir, quality="fast")
params_fast = stage.get_params(ctx_fast)
assert params_fast["segment"] == 7
assert params_fast["shifts"] == 0
ctx_best = PipelineContext(source_file=source, output_dir=out_dir, quality="best")
params_best = stage.get_params(ctx_best)
assert params_best["segment"] == 10
assert params_best["shifts"] == 1

View File

@ -5,7 +5,7 @@ import json
import pytest
from pydantic import ValidationError
from songsplit.schema import (
from unmix.schema import (
ChordsDocument,
MetaDocument,
ModelInfo,
@ -149,3 +149,83 @@ def test_strumming_document_roundtrip_and_spec_example():
dumped = json.loads(doc.model_dump_json())
assert dumped["events"][0]["direction"] == "down"
def test_manifest_document_roundtrip():
from unmix.schema.manifest import ManifestDocument, ManifestFileInfo, ManifestStageInfo
manifest = ManifestDocument(
created="2026-11-02T11:40:00+01:00",
modified="2026-11-02T11:55:12+01:00",
files=[
ManifestFileInfo(path="meta.json", role="meta", sha256="abc", size=100),
ManifestFileInfo(path="stems/vocals.wav", role="stem", stem="vocals", sha256="def", size=2000),
],
stages={
"stems": ManifestStageInfo(status="done", model="htdemucs_ft"),
},
)
dumped = json.loads(manifest.model_dump_json())
assert dumped["format"] == "songpack"
assert dumped["schema_version"] == "1.0"
assert len(dumped["files"]) == 2
assert dumped["stages"]["stems"]["status"] == "done"
loaded = ManifestDocument.model_validate(dumped)
assert loaded.format == "songpack"
assert loaded.files[0].path == "meta.json"
def test_tracks_document_kinds():
from unmix.schema.tracks import DrumEvent, NoteEvent, StrumEvent, StrumPattern, TrackDocument
# Strumming track
t_strum = TrackDocument(
name="guitar",
instrument="guitar",
kind="strumming",
stem="guitar",
events=[StrumEvent(id="e_0001", beat=0.0, direction="down", strength=0.9, confidence=0.5)],
patterns=[StrumPattern(id="p_0001", start_beat=0.0, end_beat=16.0, pattern="D . D U . U D U", grid="8th")],
)
assert t_strum.kind == "strumming"
assert len(t_strum.events) == 1
assert len(t_strum.patterns) == 1
# Notes track
t_notes = TrackDocument(
name="bass",
instrument="bass",
kind="notes",
stem="bass",
events=[NoteEvent(id="n_0001", start_beat=4.0, end_beat=4.5, midi=45, velocity=0.7)],
)
assert t_notes.kind == "notes"
assert len(t_notes.events) == 1
assert t_notes.events[0].midi == 45
# Drums track
t_drums = TrackDocument(
name="drums",
instrument="drums",
kind="drums",
stem="drums",
events=[DrumEvent(id="d_0001", beat=0.0, piece="kick", strength=0.9)],
)
assert t_drums.kind == "drums"
assert len(t_drums.events) == 1
assert t_drums.events[0].piece == "kick"
def test_vocals_f0_document():
from unmix.schema.vocals_f0 import VocalsF0Document
f0 = VocalsF0Document(
hop_sec=0.01,
start_sec=0.0,
hz=[None, None, 220.0, 222.0],
confidence=[0.0, 0.1, 0.95, 0.98],
)
dumped = json.loads(f0.model_dump_json())
assert dumped["hop_sec"] == 0.01
assert dumped["hz"][2] == 220.0

View File

@ -0,0 +1,76 @@
"""Tests for the input modes: AI backup vs. ground truth in vocals.json, pitch cache invalidation."""
import json
from unmix.pipeline.source_modes import (
invalidate_pitch_cache,
mode_label,
prepare_ai_vocals,
previous_vocals_source,
)
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
def _doc(text: str, start: float = 1.0) -> VocalsDocument:
syl = VocalSyllable(text=text, start=start, end=start + 0.5, midi=60.0, word_end=True)
return VocalsDocument(lines=[VocalLine(start=start, end=start + 0.5, syllables=[syl])])
def _text(doc: VocalsDocument) -> str:
return doc.lines[0].syllables[0].text
def test_first_run_returns_ai_and_backs_it_up(tmp_path):
out = tmp_path / "out"
out.mkdir()
(out / "vocals.json").write_text(_doc("ai").model_dump_json(), encoding="utf-8")
ai = prepare_ai_vocals(out, out / ".cache", "whisper")
assert _text(ai) == "ai"
assert (out / ".cache" / "vocals_ai.json").exists()
def test_run_after_ground_truth_write_uses_backup_not_reference(tmp_path):
out = tmp_path / "out"
cache = out / ".cache"
out.mkdir()
(out / "vocals.json").write_text(_doc("ai").model_dump_json(), encoding="utf-8")
prepare_ai_vocals(out, cache, "whisper") # first --ultrastar run backs up the AI result
(out / "vocals.json").write_text(_doc("ground-truth").model_dump_json(), encoding="utf-8")
# second run in the same folder: vocals.json now holds the reference
ai = prepare_ai_vocals(out, cache, "reference_ultrastar")
assert _text(ai) == "ai"
def test_reference_source_without_backup_gives_no_ai(tmp_path):
out = tmp_path / "out"
out.mkdir()
(out / "vocals.json").write_text(_doc("ground-truth").model_dump_json(), encoding="utf-8")
assert prepare_ai_vocals(out, out / ".cache", "reference_ultrastar") is None
def test_invalidate_pitch_cache_removes_only_pitch_stage(tmp_path):
(tmp_path / "s4_pitch.json").write_text("{}", encoding="utf-8")
(tmp_path / "s3_lyrics.json").write_text("{}", encoding="utf-8")
invalidate_pitch_cache(tmp_path)
invalidate_pitch_cache(tmp_path) # no error when already gone
assert not (tmp_path / "s4_pitch.json").exists()
assert (tmp_path / "s3_lyrics.json").exists()
def test_previous_vocals_source_and_mode_label(tmp_path):
meta = tmp_path / "meta.json"
assert previous_vocals_source(meta) is None
meta.write_text(json.dumps({"vocals_source": "reference_ultrastar"}), encoding="utf-8")
assert previous_vocals_source(meta) == "reference_ultrastar"
meta.write_text("not json", encoding="utf-8")
assert previous_vocals_source(meta) is None
assert mode_label(False) == "whisper"
assert mode_label(True) == "lyrics_aligned"

39
tests/test_strumming.py Normal file
View File

@ -0,0 +1,39 @@
"""Unit tests for strumming direction estimation and pattern aggregation."""
import numpy as np
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():
sr = 22050
audio = np.random.randn(sr).astype(np.float32)
# On-beat (beat 0.0) -> down
dir_down, conf_down = estimate_strum_direction(audio, sr, onset_sec=0.1, beat=0.0)
assert dir_down == "down"
assert conf_down >= 0.5
# Off-beat (beat 0.5) -> up
dir_up, conf_up = estimate_strum_direction(audio, sr, onset_sec=0.1, beat=0.5)
assert dir_up == "up"
assert conf_up >= 0.5
def test_aggregate_strum_patterns_island_strum():
# Famous "island strum": D . D U . U D U (slots: 0, 1, 2, 3, 4, 5, 6, 7 on 8th grid)
# slots: 0.0 (D), 1.0 (D), 1.5 (U), 2.5 (U), 3.0 (D), 3.5 (U)
events = [
StrumEvent(beat=0.0, direction="down", strength=0.9, confidence=0.8),
StrumEvent(beat=1.0, direction="down", strength=0.8, confidence=0.8),
StrumEvent(beat=1.5, direction="up", strength=0.7, confidence=0.7),
StrumEvent(beat=2.5, direction="up", strength=0.7, confidence=0.7),
StrumEvent(beat=3.0, direction="down", strength=0.8, confidence=0.8),
StrumEvent(beat=3.5, direction="up", strength=0.7, confidence=0.7),
]
patterns = aggregate_strum_patterns(events, total_beats=4.0, grid="8th", pattern_beats=4.0, section_beats=4.0)
assert len(patterns) == 1
assert patterns[0].pattern == "D . D U . U D U"
assert patterns[0].grid == "8th"

View File

@ -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():

View File

@ -0,0 +1,63 @@
"""Unit tests for tempo map builder and click track generator."""
import numpy as np
import pytest
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():
# 120 BPM = 0.5s per beat, 16 beats = 8.0s
beat_times = np.arange(0.5, 8.5, 0.5)
# Downbeats every 4 beats (indices 0, 4, 8, 12 -> 0.5, 2.5, 4.5, 6.5)
downbeat_times = beat_times[::4]
tempo_doc = build_tempo_map_from_beats(beat_times, downbeat_times)
# Should only create 1 anchor for steady tempo
assert len(tempo_doc.anchors) == 1
anchor = tempo_doc.anchors[0]
assert anchor.bpm == pytest.approx(120.0, abs=0.5)
assert anchor.sec == pytest.approx(0.5, abs=0.01)
assert tempo_doc.time_signature.numerator == 4
assert tempo_doc.downbeat_offset == 0
def test_build_tempo_map_3_4_time_signature():
# 3/4 time signature: downbeats every 3 beats
beat_times = np.arange(0.0, 9.0, 0.5) # 120 BPM
downbeat_times = beat_times[::3]
tempo_doc = build_tempo_map_from_beats(beat_times, downbeat_times)
assert tempo_doc.time_signature.numerator == 3
def test_build_tempo_map_sustained_tempo_change():
# Section 1: 120 BPM (0.5s per beat) for 16 beats -> 8.0s
sec1 = np.arange(0.0, 8.0, 0.5)
# Section 2: 150 BPM (0.4s per beat) for 16 beats -> 6.4s
sec2 = 8.0 + np.arange(0.0, 6.4, 0.4)
all_beats = np.concatenate([sec1, sec2])
tempo_doc = build_tempo_map_from_beats(all_beats, min_tempo_change_bpm=3.0, min_beats_for_change=6)
# Should detect 2 anchors: one around 120 BPM, one around 150 BPM
assert len(tempo_doc.anchors) >= 2
assert tempo_doc.anchors[0].bpm == pytest.approx(120.0, abs=1.0)
assert tempo_doc.anchors[1].bpm == pytest.approx(150.0, abs=2.0)
def test_generate_click_track():
tempo_doc = TempoDocument(
anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)],
time_signature=TimeSignature(numerator=4, denominator=4),
downbeat_offset=0,
)
sr = 44100
duration_sec = 4.0
clicks = generate_click_track(tempo_doc, duration_sec=duration_sec, sr=sr)
assert len(clicks) == int(duration_sec * sr)
# At sec=0.5, there should be non-zero audio (first beat click)
click_idx = int(0.5 * sr)
assert np.max(np.abs(clicks[click_idx : click_idx + 100])) > 0.1

218
tests/test_ultrastar.py Normal file
View File

@ -0,0 +1,218 @@
"""Unit tests for UltraStar writer and reader round-trip."""
from pathlib import Path
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):
song_dir = tmp_path / "song_pkg"
song_dir.mkdir(parents=True, exist_ok=True)
# 1. Prepare meta.json
meta = MetaDocument(
title="Test Song",
artist="Test Artist",
language="de",
duration_sec=30.0,
source_file=SourceFileInfo(path="/tmp/test.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))
# 2. Prepare tempo.json (120 BPM)
tempo = TempoDocument(anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)])
(song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2))
# 3. Prepare vocals.json
vocals = VocalsDocument(
lines=[
VocalLine(
start=0.5,
end=2.0,
syllables=[
VocalSyllable(text="Hal-", start=0.5, end=1.0, midi=60.0),
VocalSyllable(text="lo ", start=1.0, end=2.0, midi=62.0),
],
),
VocalLine(
start=3.0,
end=4.5,
syllables=[
VocalSyllable(text="Welt", start=3.0, end=4.5, midi=64.0),
],
),
]
)
(song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2))
# 4. Export to UltraStar song.txt
txt_path = export_ultrastar(song_dir)
assert txt_path.exists()
content = txt_path.read_text(encoding="utf-8")
assert "#TITLE:Test Song" in content
assert "#ARTIST:Test Artist" in content
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
parsed = parse_ultrastar(txt_path)
assert parsed.title == "Test Song"
assert parsed.artist == "Test Artist"
assert parsed.bpm == 120.0
assert parsed.gap_ms == 500.0
assert len(parsed.lines) == 2
line1 = parsed.lines[0]
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"
def test_parse_ultrastar_leading_space_word_convention(tmp_path):
from unmix.eval.metrics import extract_text_from_reference
from unmix.export.ultrastar import parse_ultrastar
f = tmp_path / "lead.txt"
f.write_text(
"#TITLE:T\n#ARTIST:A\n#BPM:120\n#GAP:0\n"
": 0 4 4 She\n: 8 6 9 came\n: 18 2 9 to\n: 22 4 9 ~r\n- 30\n: 32 4 2 me\nE\n",
encoding="utf-8",
)
song = parse_ultrastar(f)
assert extract_text_from_reference(song) == "She came to~r me"
assert song.lines[0][0].text == "She "
assert song.lines[0][1].text == "came "
# trailing-space convention is unchanged
g = tmp_path / "trail.txt"
g.write_text("#BPM:120\n#GAP:0\n: 0 4 4 We \n: 5 4 4 do \nE\n", encoding="utf-8")
assert extract_text_from_reference(parse_ultrastar(g)) == "We do"

9
testset.example.toml Normal file
View 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"

View File

@ -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,14 +22,14 @@ 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)
meta.py vocals.py chords.py strumming.py tempo.py
meta.py vocals.py chords.py tracks.py tempo.py
tempo.py # Tempo-Map-Logik (sec<->beat)
pipeline/
runner.py # Stufen-Runner, Cache, Hash-Invalidierung
@ -39,7 +39,9 @@ songsplit/
s4_pitch.py # CREPE -> Noten pro Silbe
s5_tempo.py # beat_this -> Tempo-Map
s6_chords.py # Akkorderkennung
s7_strumming.py # Onsets auf Gitarren-Stem
s7_tracks/ # optionale Instrumenten-Stufen, je Track-Art ein Modul
strumming.py # Onsets auf Gitarren-/Instrumental-Stem
(später: bass.py, drums.py, piano.py)
export/
ultrastar.py # Writer (später Reader)
eval/
@ -51,6 +53,8 @@ songsplit/
## 4. Song-Paket (Schnittstelle)
**Maßgeblich ist `songpack-spec.md`** (Container `.songpack`, Manifest, Varianten `full`/`data`, Import-Sicherheit, Instrumenten-Tracks). Dieser Abschnitt ist eine Kurzfassung und bei Abweichungen unterlegen.
### 4.1 Ordner
```
@ -60,7 +64,7 @@ songsplit/
stems/ vocals.wav instrumental.wav [drums.wav bass.wav guitar.wav piano.wav other.wav]
vocals.json
chords.json
strumming.json
tracks/ # guitar.json, bass.json, drums.json, … (kind: strumming | notes | drums)
song.txt # UltraStar-Export
.cache/ # Zwischenergebnisse, Stufen-Hashes
```
@ -106,7 +110,9 @@ Zwischen zwei Ankern konstantes Tempo. `beat` ist float (Viertel). Der letzte An
Label-Syntax: Harte-Notation (`C`, `Am`, `G7`, `Dsus4`, `F/A`, `N` für kein Akkord). Zusätzlich `key` in `meta.json`.
### 4.5 strumming.json (Beats)
### 4.5 Instrumenten-Tracks, `tracks/<name>.json` (Beats)
Ein Track pro Instrument mit `kind` = `strumming` | `notes` | `drums`. Aufbau aller drei Arten steht in der Spezifikation, hier das Beispiel für `strumming`:
```json
{"events": [{"beat": 0.0, "direction": "down", "strength": 0.9, "confidence": 0.5}],
@ -129,7 +135,7 @@ Titel, Interpret, Sprache, Dauer, Quelldatei (Pfad + Hash), Tonart, Capo-Vorschl
| 4 Pitch | `torchcrepe` (full) auf Vocals-Stem | midi pro Silbe | Hop 10 ms, Voicing-Schwelle, Median pro Silbe, Oktavfehler-Korrektur über Nachbarsilben |
| 5 Tempo | `beat_this` auf Instrumental/Drums | Tempo-Map | Anker nur bei echten Tempowechseln, sonst ein Anker |
| 6 Akkorde | Baseline Chordino (NNLS-Chroma); Kandidat: Transformer-Modell | chords.json | Beat-synchron quantisieren, Vergleich beider im Eval |
| 7 Strumming | Onsets (librosa) auf Gitarren-/Instrumental-Stem | strumming.json | Richtung grob über Spektralschwerpunkt-Verlauf; als Vorschlag kennzeichnen |
| 7 Tracks (optional) | Strumming: Onsets (librosa) auf Gitarren-/Instrumental-Stem; später Bass, Schlagzeug, Klavier | `tracks/<name>.json` | Je Track-Art eine eigene Teilstufe, einzeln aufrufbar (`--stage tracks:strumming`). Strumming-Richtung grob über Spektralschwerpunkt-Verlauf; alles als Vorschlag kennzeichnen |
Reihenfolge der Abhängigkeiten: 1 → 2 → (3 → 4) und (5 → 6, 7). Stufen 3/4 und 5–7 sind unabhängig voneinander.
@ -143,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)
@ -187,10 +193,13 @@ Stufe 5.
Stufe 6, Vergleich Chordino gegen Transformer-Kandidat im Eval (Referenz: von Hand notierte Akkorde für 2 Songs).
*Akzeptanz:* Akkordgenauigkeit pro Song gemessen; bessere Variante wird Standard, die andere bleibt wählbar.
**M5 – Strumming**
Stufe 7.
**M5 – Instrumenten-Tracks: Strumming**
Stufe 7, zunächst nur `kind: strumming`.
*Akzeptanz:* Onsets liegen auf dem Beat-Raster, Down/Up-Vorschlag und Muster pro Abschnitt werden erzeugt; als `experimental` markiert.
**M5a, M5b, M5c – weitere Tracks (optional, jeweils eigener Meilenstein)**
Bass (`notes`), Schlagzeug (`drums`), Klavier (`notes`). Jeder Track bekommt einen Eval gegen eine von Hand notierte Referenz und wird als `experimental` markiert, bis die Zahlen stimmen.
**M6 – Härtung**
Fehlerbehandlung, Logging, Dokumentation des Formats (`docs/format.md`), Beispielpaket im Repo (kurzer, lizenzfreier Song).

Some files were not shown because too many files have changed in this diff Show More