Compare commits
7 Commits
m4-chords
...
bc62fa1c56
| Author | SHA1 | Date | |
|---|---|---|---|
| bc62fa1c56 | |||
| a6dd0a649a | |||
| 44311d007f | |||
| 9db639ea9e | |||
| f1d55c4bcb | |||
| 760bad7435 | |||
| 7ec6b3274b |
3
.gitignore
vendored
3
.gitignore
vendored
@ -41,6 +41,9 @@ testdata/
|
||||
*.flac
|
||||
*.ogg
|
||||
|
||||
# Allow synthetic demo audio
|
||||
!examples/demo_song/stems/*.wav
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
@ -49,5 +49,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] **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`).
|
||||
- [ ] **M5 – Strumming**: Stufe 7 (librosa Onsets / Strumming-Muster).
|
||||
- [ ] **M6 – Härtung**: Fehlerbehandlung, Logging, Dokumentation, Beispielpaket.
|
||||
- [x] **M5 – Strumming**: Stufe 7 (Onset-Erkennung auf Gitarren-/Instrumental-Stem, Spektralschwerpunkt- & Beatphasen-Gradient für Down/Up-Richtungsvorschlag, Beat-Raster-Quantisierung, Muster-Verdichtung `D . D U . U D U`, als `experimental` markiert).
|
||||
- [x] **M6 – Härtung**: Fehlerbehandlung, strukturiertes Logging, Formatspezifikation ([docs/format.md](docs/format.md)), lizenzfreies synthetisches Beispielpaket ([examples/demo_song/](examples/demo_song/)).
|
||||
|
||||
269
docs/format.md
Normal file
269
docs/format.md
Normal file
@ -0,0 +1,269 @@
|
||||
# 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
|
||||
|
||||
Ein Song-Paket befindet sich in einem dedizierten Verzeichnis:
|
||||
|
||||
```
|
||||
<song-ordner>/
|
||||
meta.json # Metadaten, Track-Info, Modelle, Status
|
||||
tempo.json # Tempo-Map (Anker, Taktart, Downbeat)
|
||||
stems/ # Isolierte Audiodateien (44.1 kHz, 16-Bit Stereo WAV)
|
||||
vocals.wav # Gesangsspur (Pflicht)
|
||||
instrumental.wav # Gesamtes Playback ohne Gesang (Pflicht)
|
||||
drums.wav # Schlagzeug (optional bei 4- oder 6-Stem Trennung)
|
||||
bass.wav # Bass (optional)
|
||||
other.wav # Sonstige Instrumente (optional)
|
||||
guitar.wav # Gitarre (optional bei 6-Stem Trennung)
|
||||
piano.wav # Klavier (optional bei 6-Stem Trennung)
|
||||
vocals.json # Liedtext, Silben-Timing, Tonhöhe (Sekundenbasis)
|
||||
chords.json # Akkordverlauf (Beat-Basis)
|
||||
strumming.json # Gitarren-Anschläge und Rhythmusmuster (Beat-Basis)
|
||||
song.txt # UltraStar-Deluxe Export
|
||||
.cache/ # Stufen-Hashes und temporäre Zwischenergebnisse
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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`
|
||||
26
examples/demo_song/chords.json
Normal file
26
examples/demo_song/chords.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"generated_by": null,
|
||||
"chords": [
|
||||
{
|
||||
"start_beat": 0.0,
|
||||
"end_beat": 4.0,
|
||||
"label": "Am",
|
||||
"root": "A",
|
||||
"quality": "min",
|
||||
"bass": "A",
|
||||
"confidence": 0.9,
|
||||
"source": "auto"
|
||||
},
|
||||
{
|
||||
"start_beat": 4.0,
|
||||
"end_beat": 6.0,
|
||||
"label": "C",
|
||||
"root": "C",
|
||||
"quality": "maj",
|
||||
"bass": "C",
|
||||
"confidence": 0.88,
|
||||
"source": "auto"
|
||||
}
|
||||
]
|
||||
}
|
||||
53
examples/demo_song/meta.json
Normal file
53
examples/demo_song/meta.json
Normal file
@ -0,0 +1,53 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"generated_by": null,
|
||||
"title": "Demo Song",
|
||||
"artist": "Synthetic Artist",
|
||||
"language": "en",
|
||||
"duration_sec": 3.0,
|
||||
"source_file": {
|
||||
"path": "examples/demo_song/stems/vocals.wav",
|
||||
"sha256": "0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"size_bytes": 529200
|
||||
},
|
||||
"key": "Am",
|
||||
"capo": 0,
|
||||
"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"
|
||||
}
|
||||
],
|
||||
"created_at": "2026-11-02T12:00:00Z",
|
||||
"stages_done": [
|
||||
"s1_extract",
|
||||
"s2_stems",
|
||||
"s3_lyrics",
|
||||
"s4_pitch",
|
||||
"s5_tempo",
|
||||
"s6_chords",
|
||||
"s7_strumming"
|
||||
],
|
||||
"stages_failed": {}
|
||||
}
|
||||
10
examples/demo_song/song.txt
Normal file
10
examples/demo_song/song.txt
Normal file
@ -0,0 +1,10 @@
|
||||
#TITLE:Demo Song
|
||||
#ARTIST:Synthetic Artist
|
||||
#MP3:stems/vocals.wav
|
||||
#BPM:480.00
|
||||
#GAP:500
|
||||
#LANGUAGE:en
|
||||
: 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.
42
examples/demo_song/strumming.json
Normal file
42
examples/demo_song/strumming.json
Normal file
@ -0,0 +1,42 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"generated_by": null,
|
||||
"events": [
|
||||
{
|
||||
"beat": 0.0,
|
||||
"direction": "down",
|
||||
"strength": 0.9,
|
||||
"confidence": 0.85,
|
||||
"source": "auto"
|
||||
},
|
||||
{
|
||||
"beat": 0.5,
|
||||
"direction": "up",
|
||||
"strength": 0.7,
|
||||
"confidence": 0.8,
|
||||
"source": "auto"
|
||||
},
|
||||
{
|
||||
"beat": 1.0,
|
||||
"direction": "down",
|
||||
"strength": 0.85,
|
||||
"confidence": 0.85,
|
||||
"source": "auto"
|
||||
},
|
||||
{
|
||||
"beat": 1.5,
|
||||
"direction": "up",
|
||||
"strength": 0.75,
|
||||
"confidence": 0.82,
|
||||
"source": "auto"
|
||||
}
|
||||
],
|
||||
"patterns": [
|
||||
{
|
||||
"start_beat": 0.0,
|
||||
"end_beat": 4.0,
|
||||
"pattern": "D U D U",
|
||||
"grid": "8th"
|
||||
}
|
||||
]
|
||||
}
|
||||
16
examples/demo_song/tempo.json
Normal file
16
examples/demo_song/tempo.json
Normal file
@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"generated_by": null,
|
||||
"anchors": [
|
||||
{
|
||||
"sec": 0.0,
|
||||
"beat": 0.0,
|
||||
"bpm": 120.0
|
||||
}
|
||||
],
|
||||
"time_signature": {
|
||||
"numerator": 4,
|
||||
"denominator": 4
|
||||
},
|
||||
"downbeat_offset": 0
|
||||
}
|
||||
39
examples/demo_song/vocals.json
Normal file
39
examples/demo_song/vocals.json
Normal file
@ -0,0 +1,39 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"generated_by": null,
|
||||
"lines": [
|
||||
{
|
||||
"start": 0.5,
|
||||
"end": 2.5,
|
||||
"syllables": [
|
||||
{
|
||||
"text": "Hel",
|
||||
"start": 0.5,
|
||||
"end": 1.0,
|
||||
"midi": 57.0,
|
||||
"golden": false,
|
||||
"confidence": 0.95,
|
||||
"source": "auto"
|
||||
},
|
||||
{
|
||||
"text": "lo ",
|
||||
"start": 1.0,
|
||||
"end": 1.5,
|
||||
"midi": 57.0,
|
||||
"golden": false,
|
||||
"confidence": 0.92,
|
||||
"source": "auto"
|
||||
},
|
||||
{
|
||||
"text": "world",
|
||||
"start": 1.5,
|
||||
"end": 2.5,
|
||||
"midi": 60.0,
|
||||
"golden": false,
|
||||
"confidence": 0.98,
|
||||
"source": "auto"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import UTC, datetime
|
||||
@ -10,6 +11,8 @@ from typing import Any
|
||||
|
||||
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:
|
||||
"""Compute sha256 hash of a file."""
|
||||
@ -225,6 +228,7 @@ class PipelineRunner:
|
||||
failed_deps = [d for d in stage.dependencies if d in failed_stages]
|
||||
if failed_deps:
|
||||
msg = f"Skipping {stage.name} because dependencies failed: {failed_deps}"
|
||||
logger.warning(msg)
|
||||
sys.stderr.write(f"[WARN] {msg}\n")
|
||||
meta.stages_failed[stage.name] = msg
|
||||
failed_stages.add(stage.name)
|
||||
@ -232,11 +236,13 @@ class PipelineRunner:
|
||||
|
||||
# Check cache
|
||||
if not ctx.force and stage.is_cached(ctx):
|
||||
logger.info("Stage %s is up to date (cached).", stage.name)
|
||||
sys.stderr.write(f"[INFO] Stage {stage.name} is up to date (cached).\n")
|
||||
if stage.name not in meta.stages_done:
|
||||
meta.stages_done.append(stage.name)
|
||||
continue
|
||||
|
||||
logger.info("Running stage: %s...", stage.name)
|
||||
sys.stderr.write(f"[INFO] Running stage: {stage.name}...\n")
|
||||
try:
|
||||
cache_hash = stage.compute_cache_hash(ctx)
|
||||
@ -259,6 +265,7 @@ class PipelineRunner:
|
||||
|
||||
except Exception as e:
|
||||
err_msg = f"{type(e).__name__}: {str(e)}"
|
||||
logger.error("Stage %s failed: %s", stage.name, err_msg, exc_info=True)
|
||||
sys.stderr.write(f"[ERROR] Stage {stage.name} failed: {err_msg}\n")
|
||||
meta.stages_failed[stage.name] = err_msg
|
||||
failed_stages.add(stage.name)
|
||||
|
||||
@ -1,30 +1,226 @@
|
||||
"""Stage 7: Strumming pattern analysis -> strumming.json."""
|
||||
"""Stage 7: Strumming pattern analysis -> strumming.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.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
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."""
|
||||
# Analyze 50ms window right after onset
|
||||
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]
|
||||
# Compute spectral centroid
|
||||
centroids = librosa.feature.spectral_centroid(y=chunk, sr=sr, hop_length=128)[0]
|
||||
if len(centroids) >= 2:
|
||||
centroid_slope = centroids[-1] - centroids[0]
|
||||
# Downstrum hits bass strings first then treble (centroid moves higher or bass-dominant)
|
||||
if centroid_slope > 0:
|
||||
direction = "down"
|
||||
confidence += 0.1
|
||||
else:
|
||||
direction = "up"
|
||||
confidence += 0.1
|
||||
|
||||
# Beat phase prior: On-beats (integer beats) are predominantly down strums
|
||||
beat_frac = beat - np.floor(beat)
|
||||
# Close to on-beat (0.0): down strum
|
||||
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
|
||||
# Close to off-beat (0.5): up strum
|
||||
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: str = "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)
|
||||
|
||||
# Gather events in this section
|
||||
sec_events = [e for e in events if sec_start <= e.beat < sec_end]
|
||||
if not sec_events:
|
||||
continue
|
||||
|
||||
# Vote for each slot in the pattern (modulo pattern_beats)
|
||||
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_tokens = []
|
||||
for votes in slot_votes:
|
||||
if votes:
|
||||
# Majority symbol
|
||||
symbol = "D" if votes.count("D") >= votes.count("U") else "U"
|
||||
pattern_tokens.append(symbol)
|
||||
else:
|
||||
pattern_tokens.append(".")
|
||||
|
||||
pattern_str = " ".join(pattern_tokens)
|
||||
patterns.append(
|
||||
StrumPattern(
|
||||
start_beat=round(sec_start, 2),
|
||||
end_beat=round(sec_end, 2),
|
||||
pattern=pattern_str,
|
||||
grid=grid,
|
||||
)
|
||||
)
|
||||
|
||||
return patterns
|
||||
|
||||
|
||||
class StrummingStage(Stage):
|
||||
"""Stage 7 detects strumming onsets and patterns on the guitar/instrumental stem."""
|
||||
|
||||
name = "s7_strumming"
|
||||
version = "1.0.0"
|
||||
model_name = "librosa-onsets"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s5_tempo"]
|
||||
|
||||
def __init__(self, grid: str = "8th"):
|
||||
self.grid = grid
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [
|
||||
ctx.stems_dir / "instrumental.wav",
|
||||
ctx.output_dir / "tempo.json",
|
||||
]
|
||||
guitar_path = ctx.stems_dir / "guitar.wav"
|
||||
inst_path = ctx.stems_dir / "instrumental.wav"
|
||||
if guitar_path.exists():
|
||||
return [guitar_path, ctx.output_dir / "tempo.json"]
|
||||
return [inst_path, ctx.output_dir / "tempo.json"]
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.output_dir / "strumming.json"]
|
||||
|
||||
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||
return {"grid": "8th"}
|
||||
return {
|
||||
"grid": self.grid,
|
||||
"status": "experimental",
|
||||
"hop_length": 512,
|
||||
}
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
# Implementation in M5
|
||||
raise NotImplementedError("Stage s7_strumming will be implemented in M5.")
|
||||
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 = 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)
|
||||
|
||||
# Normalize onset envelope for strength computation
|
||||
max_env = float(np.max(onset_env)) if len(onset_env) > 0 and np.max(onset_env) > 0 else 1.0
|
||||
|
||||
# Map onsets onto beat grid
|
||||
raw_events_by_grid: dict[float, StrumEvent] = {}
|
||||
|
||||
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
|
||||
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 multiple onsets fall on the same grid slot, keep the strongest
|
||||
if quantized_beat not in raw_events_by_grid or strength > raw_events_by_grid[quantized_beat].strength:
|
||||
raw_events_by_grid[quantized_beat] = StrumEvent(
|
||||
beat=round(quantized_beat, 3),
|
||||
direction=direction,
|
||||
strength=round(strength, 2),
|
||||
confidence=conf,
|
||||
source="auto",
|
||||
)
|
||||
|
||||
events = sorted(raw_events_by_grid.values(), key=lambda e: e.beat)
|
||||
|
||||
total_duration = sf.info(str(audio_path)).duration
|
||||
total_beats = sec_to_beat(total_duration, tempo_doc)
|
||||
|
||||
patterns = aggregate_strum_patterns(events, total_beats, grid=grid)
|
||||
|
||||
doc = StrummingDocument(
|
||||
schema_version="1.0",
|
||||
generated_by=GeneratedBy(
|
||||
stage=self.name,
|
||||
model=self.model_name,
|
||||
model_version=self.version,
|
||||
params=params,
|
||||
),
|
||||
events=events,
|
||||
patterns=patterns,
|
||||
)
|
||||
|
||||
output_file = self.get_outputs(ctx)[0]
|
||||
output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
f.write(doc.model_dump_json(indent=2))
|
||||
|
||||
98
tests/test_demo_package.py
Normal file
98
tests/test_demo_package.py
Normal file
@ -0,0 +1,98 @@
|
||||
"""Test the demo song package in examples/demo_song."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import soundfile as sf
|
||||
|
||||
from songsplit.export.ultrastar import parse_ultrastar
|
||||
from songsplit.schema.chords import ChordsDocument
|
||||
from songsplit.schema.meta import MetaDocument
|
||||
from songsplit.schema.strumming import StrummingDocument
|
||||
from songsplit.schema.tempo import TempoDocument
|
||||
from songsplit.schema.vocals import VocalsDocument
|
||||
|
||||
|
||||
def test_demo_package_structure():
|
||||
demo_dir = Path("examples/demo_song")
|
||||
assert demo_dir.is_dir()
|
||||
|
||||
required_files = [
|
||||
"meta.json",
|
||||
"tempo.json",
|
||||
"vocals.json",
|
||||
"chords.json",
|
||||
"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")
|
||||
|
||||
# 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
|
||||
|
||||
# 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
|
||||
|
||||
# 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"
|
||||
|
||||
# Strumming
|
||||
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 / "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"]
|
||||
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"
|
||||
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"
|
||||
Reference in New Issue
Block a user