Compare commits
15 Commits
m4-chords
...
999a3c3a9d
| Author | SHA1 | Date | |
|---|---|---|---|
| 999a3c3a9d | |||
| af11f507cf | |||
| 6d7d88e799 | |||
| e73c4ec328 | |||
| fd17b63c7a | |||
| 6428e8be7d | |||
| 2a2da717e8 | |||
| a874afe7cd | |||
| bc62fa1c56 | |||
| a6dd0a649a | |||
| 44311d007f | |||
| 9db639ea9e | |||
| f1d55c4bcb | |||
| 760bad7435 | |||
| 7ec6b3274b |
4
.gitignore
vendored
4
.gitignore
vendored
@ -41,6 +41,10 @@ testdata/
|
|||||||
*.flac
|
*.flac
|
||||||
*.ogg
|
*.ogg
|
||||||
|
|
||||||
|
# Allow synthetic demo audio
|
||||||
|
!examples/demo_song/stems/*.wav
|
||||||
|
pragmatic_readme_template*.md
|
||||||
|
|
||||||
# IDE
|
# IDE
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
10
README.md
10
README.md
@ -25,7 +25,11 @@ songsplit doctor
|
|||||||
|
|
||||||
# Gesamte Analyse oder bestimmte Stufen ausführen
|
# 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> [--lang de] [--stems 4|6] [--quality fast|best]
|
||||||
songsplit analyze <datei> -o <ordner> --stage chords [--force]
|
songsplit analyze <datei> -o <ordner> --stage tracks:strumming [--force]
|
||||||
|
|
||||||
|
# Songpack packen und sicher entpacken
|
||||||
|
songsplit pack <ordner> [-o <datei.songpack>] [--variant full|data]
|
||||||
|
songsplit unpack <datei.songpack> [-o <ordner>]
|
||||||
|
|
||||||
# Export nach UltraStar (ab M2)
|
# Export nach UltraStar (ab M2)
|
||||||
songsplit export-ultrastar <ordner>
|
songsplit export-ultrastar <ordner>
|
||||||
@ -49,5 +53,5 @@ uv run ruff format --check
|
|||||||
- [x] **M2 – Gesang**: Stufe 3 (`whisper-large-v3` + `pyphen`-Silbentrennung mit proportionalem Timing), Stufe 4 (`torchcrepe-full` mit Medianhöhe & Oktavfehler-Korrektur), UltraStar-Export (`song.txt`) & Reader, Eval-Framework mit Timing-MAE, Pitch-Genauigkeit (strikt & oktav-äquivalent) und WER via `jiwer`.
|
- [x] **M2 – Gesang**: Stufe 3 (`whisper-large-v3` + `pyphen`-Silbentrennung mit proportionalem Timing), Stufe 4 (`torchcrepe-full` mit Medianhöhe & Oktavfehler-Korrektur), UltraStar-Export (`song.txt`) & Reader, Eval-Framework mit Timing-MAE, Pitch-Genauigkeit (strikt & oktav-äquivalent) und WER via `jiwer`.
|
||||||
- [x] **M3 – Tempo-Map**: Stufe 5 (`beat_this` Beat- & Downbeat-Tracking mit `librosa`-Fallback), intelligente Segmentierung (Anker nur bei echten Tempowechseln), Metronom-Klick-Track-Synthese (`.cache/click_track.wav`), BPM/GAP-Ableitung für UltraStar.
|
- [x] **M3 – Tempo-Map**: Stufe 5 (`beat_this` Beat- & Downbeat-Tracking mit `librosa`-Fallback), intelligente Segmentierung (Anker nur bei echten Tempowechseln), Metronom-Klick-Track-Synthese (`.cache/click_track.wav`), BPM/GAP-Ableitung für UltraStar.
|
||||||
- [x] **M4 – Akkorde**: Stufe 6 (Harte-Notation, Beat-synchrone Quantisierung über Tempo-Map, `chordino` & `template` Backends, Tonarterkennung nach Krumhansl-Schmuckler in `meta.json`).
|
- [x] **M4 – Akkorde**: Stufe 6 (Harte-Notation, Beat-synchrone Quantisierung über Tempo-Map, `chordino` & `template` Backends, Tonarterkennung nach Krumhansl-Schmuckler in `meta.json`).
|
||||||
- [ ] **M5 – Strumming**: Stufe 7 (librosa Onsets / Strumming-Muster).
|
- [x] **M5 – Strumming**: Stufe 7 (Onset-Erkennung auf Gitarren-/Instrumental-Stem, Spektralschwerpunkt- & Beatphasen-Gradient für Down/Up-Richtungsvorschlag, Beat-Raster-Quantisierung, Muster-Verdichtung `D . D U . U D U`, als `experimental` markiert).
|
||||||
- [ ] **M6 – Härtung**: Fehlerbehandlung, Logging, Dokumentation, Beispielpaket.
|
- [x] **M6 – Härtung**: Fehlerbehandlung, strukturiertes Logging, Formatspezifikation ([docs/format.md](docs/format.md)), lizenzfreies synthetisches Beispielpaket ([examples/demo_song/](examples/demo_song/)).
|
||||||
|
|||||||
277
docs/format.md
Normal file
277
docs/format.md
Normal file
@ -0,0 +1,277 @@
|
|||||||
|
# Song-Paket Format Spezifikation (v1.0)
|
||||||
|
|
||||||
|
Dieses Dokument definiert das Dateiformat des **Song-Pakets** als verbindliche Schnittstelle zwischen der Analyse-Pipeline (`songsplit`) und nachgelagerten Anwendungen (z. B. der Rust-Gesangstrainer-App und Editoren).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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:
|
||||||
|
- Header: `#TITLE`, `#ARTIST`, `#MP3`, `#BPM` ($4 \times$ Viertelnoten-BPM), `#GAP` (Offset in ms), `#LANGUAGE`.
|
||||||
|
- Notenzeilen: `: <start_beat> <duration> <pitch_rel_c4> <text>`
|
||||||
|
- Pausen/Umbruch: `- <beat>`
|
||||||
|
- Ende: `E`
|
||||||
30
examples/demo_song/chords.json
Normal file
30
examples/demo_song/chords.json
Normal 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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
11
examples/demo_song/export/song.txt
Normal file
11
examples/demo_song/export/song.txt
Normal 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
|
||||||
129
examples/demo_song/manifest.json
Normal file
129
examples/demo_song/manifest.json
Normal 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-02T11:21:17.734955+00:00",
|
||||||
|
"generator": {
|
||||||
|
"name": "songsplit",
|
||||||
|
"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": "tracks/guitar.json",
|
||||||
|
"role": "track",
|
||||||
|
"schema_version": "1.0",
|
||||||
|
"sha256": "64f072e2bb2d17cca3ea18798d3c9448089f204e3ef40b04fab1ab8203b1eeea",
|
||||||
|
"size": 1091,
|
||||||
|
"stem": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "export/song.txt",
|
||||||
|
"role": "ultrastar",
|
||||||
|
"schema_version": null,
|
||||||
|
"sha256": "1989999030e4d14bd7feee99899cf0eedc7efd0b2dcd0edbefb529e664230dc4",
|
||||||
|
"size": 152,
|
||||||
|
"stem": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stages": {}
|
||||||
|
}
|
||||||
79
examples/demo_song/meta.json
Normal file
79
examples/demo_song/meta.json
Normal 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": {}
|
||||||
|
}
|
||||||
11
examples/demo_song/song.txt
Normal file
11
examples/demo_song/song.txt
Normal 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
|
||||||
BIN
examples/demo_song/stems/bass.wav
Normal file
BIN
examples/demo_song/stems/bass.wav
Normal file
Binary file not shown.
BIN
examples/demo_song/stems/drums.wav
Normal file
BIN
examples/demo_song/stems/drums.wav
Normal file
Binary file not shown.
BIN
examples/demo_song/stems/instrumental.wav
Normal file
BIN
examples/demo_song/stems/instrumental.wav
Normal file
Binary file not shown.
BIN
examples/demo_song/stems/other.wav
Normal file
BIN
examples/demo_song/stems/other.wav
Normal file
Binary file not shown.
BIN
examples/demo_song/stems/vocals.wav
Normal file
BIN
examples/demo_song/stems/vocals.wav
Normal file
Binary file not shown.
54
examples/demo_song/strumming.json
Normal file
54
examples/demo_song/strumming.json
Normal 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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
27
examples/demo_song/tempo.json
Normal file
27
examples/demo_song/tempo.json
Normal 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
|
||||||
|
}
|
||||||
58
examples/demo_song/tracks/guitar.json
Normal file
58
examples/demo_song/tracks/guitar.json
Normal 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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
56
examples/demo_song/vocals.json
Normal file
56
examples/demo_song/vocals.json
Normal 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
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
610
examples/demo_song/vocals_f0.json
Normal file
610
examples/demo_song/vocals_f0.json
Normal 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
|
||||||
|
]
|
||||||
|
}
|
||||||
384
songpack-spec.md
Normal file
384
songpack-spec.md
Normal 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": "songsplit", "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 `songsplit 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
|
||||||
@ -81,6 +81,34 @@ def eval_cmd(
|
|||||||
run_evaluation(testset_config)
|
run_evaluation(testset_config)
|
||||||
|
|
||||||
|
|
||||||
|
@app.command(name="pack")
|
||||||
|
def pack_cmd(
|
||||||
|
song_dir: Path = typer.Argument(..., help="Songpack directory to pack", exists=True),
|
||||||
|
output: Path | None = typer.Option(None, "-o", "--output", help="Output .songpack file path"),
|
||||||
|
variant: str = typer.Option(
|
||||||
|
"full", "--variant", help="Package variant: 'full' (with stems) or 'data' (without stems)"
|
||||||
|
),
|
||||||
|
) -> None:
|
||||||
|
"""Pack a songpack directory into a .songpack archive."""
|
||||||
|
from songsplit.container import pack_songpack
|
||||||
|
|
||||||
|
res = pack_songpack(song_dir, output_path=output, variant=variant) # type: ignore[arg-type]
|
||||||
|
print(str(res))
|
||||||
|
|
||||||
|
|
||||||
|
@app.command(name="unpack")
|
||||||
|
def unpack_cmd(
|
||||||
|
songpack_file: Path = typer.Argument(..., help="Path to .songpack archive", exists=True),
|
||||||
|
output_dir: Path | None = typer.Option(None, "-o", "--output", help="Destination folder for unpacked songpack"),
|
||||||
|
) -> None:
|
||||||
|
"""Securely unpack a .songpack archive into a song directory."""
|
||||||
|
from songsplit.container import unpack_songpack
|
||||||
|
|
||||||
|
dest = output_dir or songpack_file.with_suffix("")
|
||||||
|
res = unpack_songpack(songpack_file, dest)
|
||||||
|
print(str(res))
|
||||||
|
|
||||||
|
|
||||||
@app.command()
|
@app.command()
|
||||||
def doctor() -> None:
|
def doctor() -> None:
|
||||||
"""Check environment, ffmpeg installation, GPUs, and PyTorch availability."""
|
"""Check environment, ffmpeg installation, GPUs, and PyTorch availability."""
|
||||||
|
|||||||
295
src/songsplit/container.py
Normal file
295
src/songsplit/container.py
Normal 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 songsplit.pipeline.runner import compute_file_sha256
|
||||||
|
from songsplit.schema.manifest import ManifestDocument, ManifestFileInfo
|
||||||
|
|
||||||
|
logger = logging.getLogger("songsplit.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
|
||||||
@ -82,6 +82,12 @@ def export_ultrastar(song_dir: Path) -> Path:
|
|||||||
f"#LANGUAGE:{language}",
|
f"#LANGUAGE:{language}",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# Pass through additional header fields from meta.ultrastar
|
||||||
|
if meta and hasattr(meta, "ultrastar") and meta.ultrastar:
|
||||||
|
for k, v in meta.ultrastar.items():
|
||||||
|
if k.upper() not in ["TITLE", "ARTIST", "MP3", "BPM", "GAP", "LANGUAGE"]:
|
||||||
|
out_lines.append(f"#{k.upper()}:{v}")
|
||||||
|
|
||||||
def sec_to_ultrastar_beat(sec: float) -> int:
|
def sec_to_ultrastar_beat(sec: float) -> int:
|
||||||
rel_sec = max(0.0, sec - (gap_ms / 1000.0))
|
rel_sec = max(0.0, sec - (gap_ms / 1000.0))
|
||||||
if tempo and tempo.anchors:
|
if tempo and tempo.anchors:
|
||||||
@ -91,12 +97,14 @@ def export_ultrastar(song_dir: Path) -> Path:
|
|||||||
beats_per_sec = base_bpm / 60.0
|
beats_per_sec = base_bpm / 60.0
|
||||||
return max(0, int(round(rel_sec * beats_per_sec * 4.0)))
|
return max(0, int(round(rel_sec * beats_per_sec * 4.0)))
|
||||||
|
|
||||||
|
tag_map = {"normal": ":", "golden": "*", "freestyle": "F", "rap": "R"}
|
||||||
|
|
||||||
current_beat = 0
|
current_beat = 0
|
||||||
for line_idx, line in enumerate(vocals.lines):
|
for line_idx, line in enumerate(vocals.lines):
|
||||||
if not line.syllables:
|
if not line.syllables:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
for syl in line.syllables:
|
for syl_idx, syl in enumerate(line.syllables):
|
||||||
syl_start_beat = sec_to_ultrastar_beat(syl.start)
|
syl_start_beat = sec_to_ultrastar_beat(syl.start)
|
||||||
syl_end_beat = sec_to_ultrastar_beat(syl.end)
|
syl_end_beat = sec_to_ultrastar_beat(syl.end)
|
||||||
duration_beats = max(1, syl_end_beat - syl_start_beat)
|
duration_beats = max(1, syl_end_beat - syl_start_beat)
|
||||||
@ -108,11 +116,15 @@ def export_ultrastar(song_dir: Path) -> Path:
|
|||||||
current_beat = syl_start_beat + duration_beats
|
current_beat = syl_start_beat + duration_beats
|
||||||
|
|
||||||
# UltraStar pitch relative to C4 (MIDI 60)
|
# UltraStar pitch relative to C4 (MIDI 60)
|
||||||
pitch = int(round(syl.midi - 60.0))
|
midi_val = syl.midi if syl.midi is not None else 60.0
|
||||||
tag = "*" if syl.golden else ":"
|
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
|
# Preserve trailing space or text (don't add trailing space to the last syllable of a line)
|
||||||
txt = syl.text
|
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}")
|
out_lines.append(f"{tag} {syl_start_beat} {duration_beats} {pitch} {txt}")
|
||||||
|
|
||||||
# Add line break if not the last line
|
# Add line break if not the last line
|
||||||
@ -124,10 +136,20 @@ def export_ultrastar(song_dir: Path) -> Path:
|
|||||||
out_lines.append("E")
|
out_lines.append("E")
|
||||||
out_lines.append("")
|
out_lines.append("")
|
||||||
|
|
||||||
with open(output_txt, "w", encoding="utf-8") as f:
|
content_str = "\n".join(out_lines)
|
||||||
f.write("\n".join(out_lines))
|
|
||||||
|
|
||||||
return output_txt
|
# 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:
|
class UltraStarNote:
|
||||||
@ -218,7 +240,7 @@ def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
# Note line: : 10 4 2 text
|
# Note line: : 10 4 2 text
|
||||||
match = re.match(r"^([:*F])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line)
|
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line)
|
||||||
if match:
|
if match:
|
||||||
ntype, s_beat, dur, pitch, text = match.groups()
|
ntype, s_beat, dur, pitch, text = match.groups()
|
||||||
note = UltraStarNote(
|
note = UltraStarNote(
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
import sys
|
import sys
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
@ -10,6 +11,8 @@ from typing import Any
|
|||||||
|
|
||||||
from songsplit.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
|
from songsplit.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
|
||||||
|
|
||||||
|
logger = logging.getLogger("songsplit.pipeline")
|
||||||
|
|
||||||
|
|
||||||
def compute_file_sha256(file_path: Path, chunk_size: int = 65536) -> str:
|
def compute_file_sha256(file_path: Path, chunk_size: int = 65536) -> str:
|
||||||
"""Compute sha256 hash of a file."""
|
"""Compute sha256 hash of a file."""
|
||||||
@ -63,8 +66,12 @@ class PipelineContext:
|
|||||||
|
|
||||||
return MetaDocument(
|
return MetaDocument(
|
||||||
duration_sec=0.0,
|
duration_sec=0.0,
|
||||||
source_file=SourceFileInfo(
|
source=SourceFileInfo(
|
||||||
|
filename=self.source_file.name,
|
||||||
path=str(self.source_file),
|
path=str(self.source_file),
|
||||||
|
kind="video"
|
||||||
|
if self.source_file.suffix.lower() in [".mp4", ".mkv", ".mov", ".webm", ".avi"]
|
||||||
|
else "audio",
|
||||||
sha256=source_hash,
|
sha256=source_hash,
|
||||||
size_bytes=size_bytes,
|
size_bytes=size_bytes,
|
||||||
),
|
),
|
||||||
@ -85,6 +92,20 @@ class Stage(ABC):
|
|||||||
model_name: str
|
model_name: str
|
||||||
model_version: str = "1.0.0"
|
model_version: str = "1.0.0"
|
||||||
dependencies: list[str] = []
|
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
|
@abstractmethod
|
||||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||||
@ -123,7 +144,8 @@ class Stage(ABC):
|
|||||||
|
|
||||||
def is_cached(self, ctx: PipelineContext) -> bool:
|
def is_cached(self, ctx: PipelineContext) -> bool:
|
||||||
"""Check if stage output is already computed and valid in cache."""
|
"""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():
|
if not cache_file.exists():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@ -142,7 +164,8 @@ class Stage(ABC):
|
|||||||
|
|
||||||
def write_cache_entry(self, ctx: PipelineContext, cache_hash: str) -> None:
|
def write_cache_entry(self, ctx: PipelineContext, cache_hash: str) -> None:
|
||||||
"""Record successful stage run in cache."""
|
"""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 = {
|
data = {
|
||||||
"stage": self.name,
|
"stage": self.name,
|
||||||
"version": self.version,
|
"version": self.version,
|
||||||
@ -178,8 +201,26 @@ class PipelineRunner:
|
|||||||
def get_stages_to_run(self, ctx: PipelineContext) -> list[Stage]:
|
def get_stages_to_run(self, ctx: PipelineContext) -> list[Stage]:
|
||||||
"""Resolve ordered list of stages to run."""
|
"""Resolve ordered list of stages to run."""
|
||||||
if ctx.target_stage:
|
if ctx.target_stage:
|
||||||
if ctx.target_stage not in self.stages_by_name:
|
target = ctx.target_stage
|
||||||
raise ValueError(f"Unknown target stage: '{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
|
# Collect target stage and all its transitive dependencies
|
||||||
needed = set()
|
needed = set()
|
||||||
|
|
||||||
@ -189,7 +230,7 @@ class PipelineRunner:
|
|||||||
if dep not in needed:
|
if dep not in needed:
|
||||||
add_deps(dep)
|
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]
|
selected = [s for s in self.stages_by_name.values() if s.name in needed]
|
||||||
else:
|
else:
|
||||||
selected = list(self.stages_by_name.values())
|
selected = list(self.stages_by_name.values())
|
||||||
@ -225,6 +266,7 @@ class PipelineRunner:
|
|||||||
failed_deps = [d for d in stage.dependencies if d in failed_stages]
|
failed_deps = [d for d in stage.dependencies if d in failed_stages]
|
||||||
if failed_deps:
|
if failed_deps:
|
||||||
msg = f"Skipping {stage.name} because dependencies failed: {failed_deps}"
|
msg = f"Skipping {stage.name} because dependencies failed: {failed_deps}"
|
||||||
|
logger.warning(msg)
|
||||||
sys.stderr.write(f"[WARN] {msg}\n")
|
sys.stderr.write(f"[WARN] {msg}\n")
|
||||||
meta.stages_failed[stage.name] = msg
|
meta.stages_failed[stage.name] = msg
|
||||||
failed_stages.add(stage.name)
|
failed_stages.add(stage.name)
|
||||||
@ -232,11 +274,13 @@ class PipelineRunner:
|
|||||||
|
|
||||||
# Check cache
|
# Check cache
|
||||||
if not ctx.force and stage.is_cached(ctx):
|
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")
|
sys.stderr.write(f"[INFO] Stage {stage.name} is up to date (cached).\n")
|
||||||
if stage.name not in meta.stages_done:
|
if stage.name not in meta.stages_done:
|
||||||
meta.stages_done.append(stage.name)
|
meta.stages_done.append(stage.name)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
logger.info("Running stage: %s...", stage.name)
|
||||||
sys.stderr.write(f"[INFO] Running stage: {stage.name}...\n")
|
sys.stderr.write(f"[INFO] Running stage: {stage.name}...\n")
|
||||||
try:
|
try:
|
||||||
cache_hash = stage.compute_cache_hash(ctx)
|
cache_hash = stage.compute_cache_hash(ctx)
|
||||||
@ -259,9 +303,19 @@ class PipelineRunner:
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
err_msg = f"{type(e).__name__}: {str(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")
|
sys.stderr.write(f"[ERROR] Stage {stage.name} failed: {err_msg}\n")
|
||||||
meta.stages_failed[stage.name] = err_msg
|
meta.stages_failed[stage.name] = err_msg
|
||||||
failed_stages.add(stage.name)
|
failed_stages.add(stage.name)
|
||||||
|
|
||||||
ctx.save_meta(meta)
|
ctx.save_meta(meta)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from songsplit.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
|
return meta
|
||||||
|
|||||||
@ -56,7 +56,7 @@ def split_word_into_syllables_timed(
|
|||||||
duration = max(0.01, end - start)
|
duration = max(0.01, end - start)
|
||||||
|
|
||||||
if len(syllables) == 1:
|
if len(syllables) == 1:
|
||||||
return [{"text": syllables[0], "start": start, "end": end}]
|
return [{"text": syllables[0], "start": start, "end": end, "word_end": True}]
|
||||||
|
|
||||||
total_chars = sum(max(1, len(s.strip())) for s in syllables)
|
total_chars = sum(max(1, len(s.strip())) for s in syllables)
|
||||||
timed = []
|
timed = []
|
||||||
@ -64,13 +64,21 @@ def split_word_into_syllables_timed(
|
|||||||
|
|
||||||
for i, syl in enumerate(syllables):
|
for i, syl in enumerate(syllables):
|
||||||
char_len = max(1, len(syl.strip()))
|
char_len = max(1, len(syl.strip()))
|
||||||
if i == len(syllables) - 1:
|
is_last = i == len(syllables) - 1
|
||||||
|
if is_last:
|
||||||
syl_end = end
|
syl_end = end
|
||||||
else:
|
else:
|
||||||
syl_dur = duration * (char_len / total_chars)
|
syl_dur = duration * (char_len / total_chars)
|
||||||
syl_end = cur_t + syl_dur
|
syl_end = cur_t + syl_dur
|
||||||
|
|
||||||
timed.append({"text": syl, "start": cur_t, "end": syl_end})
|
timed.append(
|
||||||
|
{
|
||||||
|
"text": syl,
|
||||||
|
"start": cur_t,
|
||||||
|
"end": syl_end,
|
||||||
|
"word_end": is_last,
|
||||||
|
}
|
||||||
|
)
|
||||||
cur_t = syl_end
|
cur_t = syl_end
|
||||||
|
|
||||||
return timed
|
return timed
|
||||||
|
|||||||
@ -146,14 +146,18 @@ class PitchStage(Stage):
|
|||||||
|
|
||||||
# Process each line and syllable
|
# Process each line and syllable
|
||||||
vocal_lines: list[VocalLine] = []
|
vocal_lines: list[VocalLine] = []
|
||||||
|
line_counter = 0
|
||||||
|
syl_counter = 0
|
||||||
|
|
||||||
for line_dict in lyrics_data.get("lines", []):
|
for line_dict in lyrics_data.get("lines", []):
|
||||||
|
line_counter += 1
|
||||||
line_syllables_raw = []
|
line_syllables_raw = []
|
||||||
|
|
||||||
for syl_dict in line_dict.get("syllables", []):
|
for syl_dict in line_dict.get("syllables", []):
|
||||||
s_start = float(syl_dict["start"])
|
s_start = float(syl_dict["start"])
|
||||||
s_end = float(syl_dict["end"])
|
s_end = float(syl_dict["end"])
|
||||||
text = syl_dict["text"]
|
text = syl_dict["text"]
|
||||||
|
w_end = syl_dict.get("word_end", False)
|
||||||
|
|
||||||
# Frames within syllable
|
# Frames within syllable
|
||||||
mask = (frame_times >= s_start) & (frame_times <= s_end)
|
mask = (frame_times >= s_start) & (frame_times <= s_end)
|
||||||
@ -178,27 +182,38 @@ class PitchStage(Stage):
|
|||||||
"end": s_end,
|
"end": s_end,
|
||||||
"midi": median_midi,
|
"midi": median_midi,
|
||||||
"confidence": float(np.clip(conf, 0.0, 1.0)),
|
"confidence": float(np.clip(conf, 0.0, 1.0)),
|
||||||
|
"word_end": w_end,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
# Apply octave error correction within phrase
|
# Apply octave error correction within phrase
|
||||||
corrected_sylls = correct_octave_errors(line_syllables_raw)
|
corrected_sylls = correct_octave_errors(line_syllables_raw)
|
||||||
|
|
||||||
syl_objects = [
|
syl_objects = []
|
||||||
VocalSyllable(
|
for s in corrected_sylls:
|
||||||
text=s["text"],
|
syl_counter += 1
|
||||||
start=s["start"],
|
raw_text = s["text"]
|
||||||
end=s["end"],
|
has_space = raw_text.endswith(" ")
|
||||||
midi=s["midi"],
|
clean_text = raw_text.rstrip()
|
||||||
confidence=s["confidence"],
|
is_word_end = s.get("word_end", has_space)
|
||||||
source="auto",
|
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",
|
||||||
|
)
|
||||||
)
|
)
|
||||||
for s in corrected_sylls
|
|
||||||
]
|
|
||||||
|
|
||||||
if syl_objects:
|
if syl_objects:
|
||||||
vocal_lines.append(
|
vocal_lines.append(
|
||||||
VocalLine(
|
VocalLine(
|
||||||
|
id=f"l_{line_counter:04d}",
|
||||||
|
voice=0,
|
||||||
start=line_dict["start"],
|
start=line_dict["start"],
|
||||||
end=line_dict["end"],
|
end=line_dict["end"],
|
||||||
syllables=syl_objects,
|
syllables=syl_objects,
|
||||||
@ -220,3 +235,26 @@ class PitchStage(Stage):
|
|||||||
output_file.parent.mkdir(parents=True, exist_ok=True)
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(output_file, "w", encoding="utf-8") as f:
|
with open(output_file, "w", encoding="utf-8") as f:
|
||||||
f.write(doc.model_dump_json(indent=2))
|
f.write(doc.model_dump_json(indent=2))
|
||||||
|
|
||||||
|
# Write optional vocals_f0.json per Section 6
|
||||||
|
try:
|
||||||
|
from songsplit.schema.vocals_f0 import VocalsF0Document
|
||||||
|
|
||||||
|
hop_sec = hop_length / crepe_sr
|
||||||
|
f0_hz: list[float | None] = [
|
||||||
|
round(float(h), 2) if p >= voicing_thresh and h > 50 else None
|
||||||
|
for h, p in zip(pitch_hz, periodicity, strict=False)
|
||||||
|
]
|
||||||
|
f0_conf = [round(float(p), 2) for p in periodicity]
|
||||||
|
f0_doc = VocalsF0Document(
|
||||||
|
schema_version="1.0",
|
||||||
|
hop_sec=round(hop_sec, 4),
|
||||||
|
start_sec=0.0,
|
||||||
|
hz=f0_hz,
|
||||||
|
confidence=f0_conf,
|
||||||
|
)
|
||||||
|
f0_path = ctx.output_dir / "vocals_f0.json"
|
||||||
|
with open(f0_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(f0_doc.model_dump_json())
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|||||||
@ -198,10 +198,19 @@ class ChordsStage(Stage):
|
|||||||
# Estimate key and save in meta.json
|
# Estimate key and save in meta.json
|
||||||
mono_audio = audio_data.mean(axis=-1) if audio_data.ndim > 1 else audio_data
|
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)
|
chroma = librosa.feature.chroma_cqt(y=mono_audio, sr=sr)
|
||||||
detected_key = estimate_key(chroma.mean(axis=1))
|
detected_key_str = estimate_key(chroma.mean(axis=1))
|
||||||
|
|
||||||
|
from songsplit.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 = ctx.load_or_init_meta()
|
||||||
meta.key = detected_key
|
meta.key = KeyInfo(tonic=key_tonic, mode=key_mode, confidence=0.8)
|
||||||
ctx.save_meta(meta)
|
ctx.save_meta(meta)
|
||||||
|
|
||||||
params = self.get_params(ctx)
|
params = self.get_params(ctx)
|
||||||
@ -288,6 +297,9 @@ class ChordsStage(Stage):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
for idx, ev in enumerate(chord_events):
|
||||||
|
ev.id = f"c_{idx + 1:04d}"
|
||||||
|
|
||||||
chords_doc = ChordsDocument(
|
chords_doc = ChordsDocument(
|
||||||
schema_version="1.0",
|
schema_version="1.0",
|
||||||
generated_by=GeneratedBy(
|
generated_by=GeneratedBy(
|
||||||
|
|||||||
@ -1,30 +1,23 @@
|
|||||||
"""Stage 7: Strumming pattern analysis -> strumming.json."""
|
"""Stage 7: Strumming pattern analysis -> tracks/guitar.json (wrapper for s7_tracks/strumming)."""
|
||||||
|
|
||||||
from pathlib import Path
|
from songsplit.pipeline.s7_tracks.strumming import (
|
||||||
from typing import Any
|
StrummingTrackStage,
|
||||||
|
aggregate_strum_patterns,
|
||||||
from songsplit.pipeline.runner import PipelineContext, Stage
|
estimate_strum_direction,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class StrummingStage(Stage):
|
class StrummingStage(StrummingTrackStage):
|
||||||
name = "s7_strumming"
|
"""Backward-compatible alias for StrummingTrackStage."""
|
||||||
version = "1.0.0"
|
|
||||||
model_name = "librosa-onsets"
|
|
||||||
model_version = "1.0.0"
|
|
||||||
dependencies = ["s5_tempo"]
|
|
||||||
|
|
||||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
def __init__(self, track_name: str = "guitar", grid: str = "8th") -> None:
|
||||||
return [
|
super().__init__(track_name=track_name, grid=grid) # type: ignore[arg-type]
|
||||||
ctx.stems_dir / "instrumental.wav",
|
self.name = "s7_strumming"
|
||||||
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]:
|
__all__ = [
|
||||||
return {"grid": "8th"}
|
"StrummingStage",
|
||||||
|
"StrummingTrackStage",
|
||||||
def run(self, ctx: PipelineContext) -> None:
|
"estimate_strum_direction",
|
||||||
# Implementation in M5
|
"aggregate_strum_patterns",
|
||||||
raise NotImplementedError("Stage s7_strumming will be implemented in M5.")
|
]
|
||||||
|
|||||||
5
src/songsplit/pipeline/s7_tracks/__init__.py
Normal file
5
src/songsplit/pipeline/s7_tracks/__init__.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
"""Instrument track stages (tracks/<name>.json)."""
|
||||||
|
|
||||||
|
from songsplit.pipeline.s7_tracks.strumming import StrummingTrackStage
|
||||||
|
|
||||||
|
__all__ = ["StrummingTrackStage"]
|
||||||
261
src/songsplit/pipeline/s7_tracks/strumming.py
Normal file
261
src/songsplit/pipeline/s7_tracks/strumming.py
Normal 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 songsplit.pipeline.runner import PipelineContext, Stage
|
||||||
|
from songsplit.schema.base import GeneratedBy
|
||||||
|
from songsplit.schema.tempo import TempoDocument
|
||||||
|
from songsplit.schema.tracks import StrumDirection, StrumEvent, StrumGrid, StrumPattern, TrackDocument
|
||||||
|
from songsplit.tempo import sec_to_beat
|
||||||
|
|
||||||
|
|
||||||
|
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))
|
||||||
@ -1,24 +1,58 @@
|
|||||||
"""Song-Paket data schemas."""
|
"""Songpack data schemas."""
|
||||||
|
|
||||||
from songsplit.schema.base import DataSource, GeneratedBy, SongPackageBase
|
from songsplit.schema.base import DataSource, EditableItem, GeneratedBy, SongPackageBase
|
||||||
from songsplit.schema.chords import ChordEvent, ChordsDocument
|
from songsplit.schema.chords import ChordEvent, ChordsDocument
|
||||||
from songsplit.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
|
from songsplit.schema.manifest import (
|
||||||
|
FileRole,
|
||||||
|
GeneratorInfo,
|
||||||
|
ManifestDocument,
|
||||||
|
ManifestFileInfo,
|
||||||
|
ManifestStageInfo,
|
||||||
|
StageStatus,
|
||||||
|
StemName,
|
||||||
|
)
|
||||||
|
from songsplit.schema.meta import (
|
||||||
|
AudioRefInfo,
|
||||||
|
CapoSuggestion,
|
||||||
|
KeyInfo,
|
||||||
|
MetaDocument,
|
||||||
|
ModelInfo,
|
||||||
|
SourceFileInfo,
|
||||||
|
)
|
||||||
from songsplit.schema.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
|
from songsplit.schema.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
|
||||||
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
|
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignatureEntry
|
||||||
|
from songsplit.schema.tracks import DrumEvent, DrumPiece, NoteEvent, TrackDocument, TrackKind
|
||||||
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||||
|
from songsplit.schema.vocals_f0 import VocalsF0Document
|
||||||
|
|
||||||
|
# Backward compatibility alias
|
||||||
|
TimeSignature = TimeSignatureEntry
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"DataSource",
|
"DataSource",
|
||||||
|
"EditableItem",
|
||||||
"GeneratedBy",
|
"GeneratedBy",
|
||||||
"SongPackageBase",
|
"SongPackageBase",
|
||||||
"SourceFileInfo",
|
"SourceFileInfo",
|
||||||
|
"AudioRefInfo",
|
||||||
|
"KeyInfo",
|
||||||
|
"CapoSuggestion",
|
||||||
"ModelInfo",
|
"ModelInfo",
|
||||||
"MetaDocument",
|
"MetaDocument",
|
||||||
|
"ManifestDocument",
|
||||||
|
"ManifestFileInfo",
|
||||||
|
"ManifestStageInfo",
|
||||||
|
"FileRole",
|
||||||
|
"StemName",
|
||||||
|
"StageStatus",
|
||||||
|
"GeneratorInfo",
|
||||||
"VocalSyllable",
|
"VocalSyllable",
|
||||||
"VocalLine",
|
"VocalLine",
|
||||||
"VocalsDocument",
|
"VocalsDocument",
|
||||||
|
"VocalsF0Document",
|
||||||
"TempoAnchor",
|
"TempoAnchor",
|
||||||
"TimeSignature",
|
"TimeSignature",
|
||||||
|
"TimeSignatureEntry",
|
||||||
"TempoDocument",
|
"TempoDocument",
|
||||||
"ChordEvent",
|
"ChordEvent",
|
||||||
"ChordsDocument",
|
"ChordsDocument",
|
||||||
@ -26,4 +60,9 @@ __all__ = [
|
|||||||
"StrumEvent",
|
"StrumEvent",
|
||||||
"StrumPattern",
|
"StrumPattern",
|
||||||
"StrummingDocument",
|
"StrummingDocument",
|
||||||
|
"NoteEvent",
|
||||||
|
"DrumEvent",
|
||||||
|
"DrumPiece",
|
||||||
|
"TrackDocument",
|
||||||
|
"TrackKind",
|
||||||
]
|
]
|
||||||
|
|||||||
@ -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
|
from typing import Any, Literal
|
||||||
|
|
||||||
@ -18,8 +18,19 @@ class GeneratedBy(BaseModel):
|
|||||||
params: dict[str, Any] = Field(default_factory=dict)
|
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):
|
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")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
|||||||
@ -1,27 +1,26 @@
|
|||||||
"""Schema for chords.json."""
|
"""Schema for chords.json."""
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import ConfigDict, Field
|
||||||
|
|
||||||
from songsplit.schema.base import DataSource, SongPackageBase
|
from songsplit.schema.base import EditableItem, SongPackageBase
|
||||||
|
|
||||||
|
|
||||||
class ChordEvent(BaseModel):
|
class ChordEvent(EditableItem):
|
||||||
"""A chord segment defined in beats."""
|
"""A chord segment defined in musical beats."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
id: str = "c_0001"
|
||||||
start_beat: float
|
start_beat: float
|
||||||
end_beat: float
|
end_beat: float
|
||||||
label: str
|
label: str
|
||||||
root: str | None = None
|
root: str | None = None
|
||||||
quality: str | None = None
|
quality: str | None = None
|
||||||
bass: 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):
|
class ChordsDocument(SongPackageBase):
|
||||||
"""Song-Paket chords document (chords.json)."""
|
"""Songpack chords document (chords.json)."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
|||||||
83
src/songsplit/schema/manifest.py
Normal file
83
src/songsplit/schema/manifest.py
Normal 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 = "songsplit"
|
||||||
|
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)
|
||||||
@ -1,5 +1,7 @@
|
|||||||
"""Schema for meta.json."""
|
"""Schema for meta.json."""
|
||||||
|
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
from songsplit.schema.base import SongPackageBase
|
from songsplit.schema.base import SongPackageBase
|
||||||
@ -10,9 +12,49 @@ class SourceFileInfo(BaseModel):
|
|||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
path: str
|
filename: str = ""
|
||||||
sha256: str
|
path: str = ""
|
||||||
size_bytes: int
|
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):
|
class ModelInfo(BaseModel):
|
||||||
@ -26,18 +68,29 @@ class ModelInfo(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class MetaDocument(SongPackageBase):
|
class MetaDocument(SongPackageBase):
|
||||||
"""Song-Paket metadata document (meta.json)."""
|
"""Songpack metadata document (meta.json)."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
title: str | None = None
|
title: str | None = None
|
||||||
artist: str | None = None
|
artist: str | None = None
|
||||||
|
album: str | None = None
|
||||||
|
year: int | None = None
|
||||||
language: str | None = None
|
language: str | None = None
|
||||||
duration_sec: float = Field(ge=0.0)
|
duration_sec: float = Field(default=0.0, ge=0.0)
|
||||||
source_file: SourceFileInfo
|
source: SourceFileInfo = Field(default_factory=SourceFileInfo)
|
||||||
key: str | None = None
|
audio_ref: AudioRefInfo | None = None
|
||||||
|
audio_offset_sec: float = 0.0
|
||||||
|
key: KeyInfo | str | None = None
|
||||||
capo: int | 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)
|
models_used: list[ModelInfo] = Field(default_factory=list)
|
||||||
created_at: str
|
created_at: str | None = None
|
||||||
stages_done: list[str] = Field(default_factory=list)
|
stages_done: list[str] = Field(default_factory=list)
|
||||||
stages_failed: dict[str, str] = Field(default_factory=dict)
|
stages_failed: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
# Backward compatibility helper
|
||||||
|
@property
|
||||||
|
def source_file(self) -> SourceFileInfo:
|
||||||
|
return self.source
|
||||||
|
|||||||
@ -1,41 +1,17 @@
|
|||||||
"""Schema for strumming.json."""
|
"""Backward-compatible re-export of strumming types from tracks."""
|
||||||
|
|
||||||
from typing import Literal
|
from songsplit.schema.tracks import (
|
||||||
|
StrumDirection,
|
||||||
|
StrumEvent,
|
||||||
|
StrumGrid,
|
||||||
|
StrummingDocument,
|
||||||
|
StrumPattern,
|
||||||
|
)
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
__all__ = [
|
||||||
|
"StrumDirection",
|
||||||
from songsplit.schema.base import DataSource, SongPackageBase
|
"StrumEvent",
|
||||||
|
"StrumGrid",
|
||||||
StrumDirection = Literal["down", "up", "unknown"]
|
"StrumPattern",
|
||||||
|
"StrummingDocument",
|
||||||
|
]
|
||||||
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)
|
|
||||||
|
|||||||
@ -1,34 +1,47 @@
|
|||||||
"""Schema for tempo.json."""
|
"""Schema for tempo.json."""
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import ConfigDict, Field
|
||||||
|
|
||||||
from songsplit.schema.base import SongPackageBase
|
from songsplit.schema.base import EditableItem, SongPackageBase
|
||||||
|
|
||||||
|
|
||||||
class TempoAnchor(BaseModel):
|
class TempoAnchor(EditableItem):
|
||||||
"""A tempo anchor defining constant BPM starting from a given time/beat."""
|
"""A tempo anchor defining constant BPM starting from a given time/beat."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
id: str = "t_0001"
|
||||||
sec: float
|
sec: float
|
||||||
beat: float
|
beat: float
|
||||||
bpm: float = Field(gt=0.0)
|
bpm: float = Field(gt=0.0)
|
||||||
|
|
||||||
|
|
||||||
class TimeSignature(BaseModel):
|
class TimeSignatureEntry(EditableItem):
|
||||||
"""Musical time signature, e.g. 4/4."""
|
"""Musical time signature starting at a given beat."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
id: str = "ts_0001"
|
||||||
|
beat: float = 0.0
|
||||||
numerator: int = Field(default=4, gt=0)
|
numerator: int = Field(default=4, gt=0)
|
||||||
denominator: int = Field(default=4, gt=0)
|
denominator: int = Field(default=4, gt=0)
|
||||||
|
|
||||||
|
|
||||||
|
# Backward-compatible alias
|
||||||
|
TimeSignature = TimeSignatureEntry
|
||||||
|
|
||||||
|
|
||||||
class TempoDocument(SongPackageBase):
|
class TempoDocument(SongPackageBase):
|
||||||
"""Song-Paket tempo document (tempo.json)."""
|
"""Songpack tempo document (tempo.json)."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
anchors: list[TempoAnchor] = Field(default_factory=list)
|
anchors: list[TempoAnchor] = Field(default_factory=list)
|
||||||
time_signature: TimeSignature = Field(default_factory=TimeSignature)
|
time_signatures: list[TimeSignatureEntry] = Field(default_factory=list)
|
||||||
downbeat_offset: int = 0
|
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)
|
||||||
|
|||||||
90
src/songsplit/schema/tracks.py
Normal file
90
src/songsplit/schema/tracks.py
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
"""Schema for instrument tracks (tracks/<name>.json)."""
|
||||||
|
|
||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
|
from pydantic import ConfigDict, Field
|
||||||
|
|
||||||
|
from songsplit.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)
|
||||||
@ -1,36 +1,49 @@
|
|||||||
"""Schema for vocals.json."""
|
"""Schema for vocals.json."""
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from typing import Literal
|
||||||
|
|
||||||
from songsplit.schema.base import DataSource, SongPackageBase
|
from pydantic import ConfigDict, Field
|
||||||
|
|
||||||
|
from songsplit.schema.base import EditableItem, SongPackageBase
|
||||||
|
|
||||||
|
SyllableType = Literal["normal", "golden", "freestyle", "rap"]
|
||||||
|
|
||||||
|
|
||||||
class VocalSyllable(BaseModel):
|
class VocalSyllable(EditableItem):
|
||||||
"""A single syllable with timing, pitch, and confidence."""
|
"""A single syllable with timing, pitch, type, and word boundary."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
id: str = "s_0001"
|
||||||
text: str
|
text: str
|
||||||
start: float = Field(ge=0.0)
|
start: float = Field(ge=0.0)
|
||||||
end: float = Field(ge=0.0)
|
end: float = Field(ge=0.0)
|
||||||
midi: float
|
midi: float | None = None
|
||||||
|
type: SyllableType = "normal"
|
||||||
|
word_end: bool = False
|
||||||
golden: bool = False
|
golden: bool = False
|
||||||
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
|
|
||||||
source: DataSource = "auto"
|
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(BaseModel):
|
class VocalLine(EditableItem):
|
||||||
"""A line of lyrics consisting of one or more syllables."""
|
"""A line of lyrics consisting of one or more syllables."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
id: str = "l_0001"
|
||||||
|
voice: int = 0
|
||||||
start: float = Field(ge=0.0)
|
start: float = Field(ge=0.0)
|
||||||
end: float = Field(ge=0.0)
|
end: float = Field(ge=0.0)
|
||||||
syllables: list[VocalSyllable] = Field(default_factory=list)
|
syllables: list[VocalSyllable] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
class VocalsDocument(SongPackageBase):
|
class VocalsDocument(SongPackageBase):
|
||||||
"""Song-Paket vocals document (vocals.json)."""
|
"""Songpack vocals document (vocals.json)."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
|||||||
16
src/songsplit/schema/vocals_f0.py
Normal file
16
src/songsplit/schema/vocals_f0.py
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
"""Schema for vocals_f0.json."""
|
||||||
|
|
||||||
|
from pydantic import ConfigDict, Field
|
||||||
|
|
||||||
|
from songsplit.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)
|
||||||
@ -162,9 +162,18 @@ def build_tempo_map_from_beats(
|
|||||||
continue
|
continue
|
||||||
i += 1
|
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(
|
return TempoDocument(
|
||||||
anchors=anchors,
|
anchors=anchors,
|
||||||
time_signature=time_sig,
|
time_signatures=[ts_entry],
|
||||||
downbeat_offset=downbeat_offset,
|
downbeat_offset=downbeat_offset,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
98
tests/test_container.py
Normal file
98
tests/test_container.py
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
"""Tests for songpack container packing and secure unpacking."""
|
||||||
|
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from songsplit.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
146
tests/test_demo_package.py
Normal 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 songsplit.container import pack_songpack, unpack_songpack
|
||||||
|
from songsplit.export.ultrastar import parse_ultrastar
|
||||||
|
from songsplit.schema.chords import ChordsDocument
|
||||||
|
from songsplit.schema.manifest import ManifestDocument
|
||||||
|
from songsplit.schema.meta import MetaDocument
|
||||||
|
from songsplit.schema.strumming import StrummingDocument
|
||||||
|
from songsplit.schema.tempo import TempoDocument
|
||||||
|
from songsplit.schema.tracks import TrackDocument
|
||||||
|
from songsplit.schema.vocals import VocalsDocument
|
||||||
|
from songsplit.schema.vocals_f0 import VocalsF0Document
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
77
tests/test_pipeline_m5.py
Normal file
77
tests/test_pipeline_m5.py
Normal 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 songsplit.pipeline import PipelineContext
|
||||||
|
from songsplit.pipeline.s7_strumming import StrummingStage
|
||||||
|
from songsplit.schema.meta import MetaDocument, SourceFileInfo
|
||||||
|
from songsplit.schema.strumming import StrummingDocument
|
||||||
|
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
||||||
|
|
||||||
|
|
||||||
|
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"
|
||||||
@ -149,3 +149,83 @@ def test_strumming_document_roundtrip_and_spec_example():
|
|||||||
|
|
||||||
dumped = json.loads(doc.model_dump_json())
|
dumped = json.loads(doc.model_dump_json())
|
||||||
assert dumped["events"][0]["direction"] == "down"
|
assert dumped["events"][0]["direction"] == "down"
|
||||||
|
|
||||||
|
|
||||||
|
def test_manifest_document_roundtrip():
|
||||||
|
from songsplit.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 songsplit.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 songsplit.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
|
||||||
|
|||||||
39
tests/test_strumming.py
Normal file
39
tests/test_strumming.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
"""Unit tests for strumming direction estimation and pattern aggregation."""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from songsplit.pipeline.s7_strumming import aggregate_strum_patterns, estimate_strum_direction
|
||||||
|
from songsplit.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"
|
||||||
@ -29,7 +29,7 @@ songsplit/
|
|||||||
cli.py # typer-App
|
cli.py # typer-App
|
||||||
config.py # Modellwahl, Devices, Pfade
|
config.py # Modellwahl, Devices, Pfade
|
||||||
schema/ # pydantic-Modelle (siehe 4)
|
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)
|
tempo.py # Tempo-Map-Logik (sec<->beat)
|
||||||
pipeline/
|
pipeline/
|
||||||
runner.py # Stufen-Runner, Cache, Hash-Invalidierung
|
runner.py # Stufen-Runner, Cache, Hash-Invalidierung
|
||||||
@ -39,7 +39,9 @@ songsplit/
|
|||||||
s4_pitch.py # CREPE -> Noten pro Silbe
|
s4_pitch.py # CREPE -> Noten pro Silbe
|
||||||
s5_tempo.py # beat_this -> Tempo-Map
|
s5_tempo.py # beat_this -> Tempo-Map
|
||||||
s6_chords.py # Akkorderkennung
|
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/
|
export/
|
||||||
ultrastar.py # Writer (später Reader)
|
ultrastar.py # Writer (später Reader)
|
||||||
eval/
|
eval/
|
||||||
@ -51,6 +53,8 @@ songsplit/
|
|||||||
|
|
||||||
## 4. Song-Paket (Schnittstelle)
|
## 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
|
### 4.1 Ordner
|
||||||
|
|
||||||
```
|
```
|
||||||
@ -60,7 +64,7 @@ songsplit/
|
|||||||
stems/ vocals.wav instrumental.wav [drums.wav bass.wav guitar.wav piano.wav other.wav]
|
stems/ vocals.wav instrumental.wav [drums.wav bass.wav guitar.wav piano.wav other.wav]
|
||||||
vocals.json
|
vocals.json
|
||||||
chords.json
|
chords.json
|
||||||
strumming.json
|
tracks/ # guitar.json, bass.json, drums.json, … (kind: strumming | notes | drums)
|
||||||
song.txt # UltraStar-Export
|
song.txt # UltraStar-Export
|
||||||
.cache/ # Zwischenergebnisse, Stufen-Hashes
|
.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`.
|
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
|
```json
|
||||||
{"events": [{"beat": 0.0, "direction": "down", "strength": 0.9, "confidence": 0.5}],
|
{"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 |
|
| 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 |
|
| 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 |
|
| 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.
|
Reihenfolge der Abhängigkeiten: 1 → 2 → (3 → 4) und (5 → 6, 7). Stufen 3/4 und 5–7 sind unabhängig voneinander.
|
||||||
|
|
||||||
@ -187,10 +193,13 @@ Stufe 5.
|
|||||||
Stufe 6, Vergleich Chordino gegen Transformer-Kandidat im Eval (Referenz: von Hand notierte Akkorde für 2 Songs).
|
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.
|
*Akzeptanz:* Akkordgenauigkeit pro Song gemessen; bessere Variante wird Standard, die andere bleibt wählbar.
|
||||||
|
|
||||||
**M5 – Strumming**
|
**M5 – Instrumenten-Tracks: Strumming**
|
||||||
Stufe 7.
|
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.
|
*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**
|
**M6 – Härtung**
|
||||||
Fehlerbehandlung, Logging, Dokumentation des Formats (`docs/format.md`), Beispielpaket im Repo (kurzer, lizenzfreier Song).
|
Fehlerbehandlung, Logging, Dokumentation des Formats (`docs/format.md`), Beispielpaket im Repo (kurzer, lizenzfreier Song).
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user