Compare commits
1 Commits
6331e89274
...
feat/song-
| Author | SHA1 | Date | |
|---|---|---|---|
| 914f9ecfef |
24
.gitea/workflows/song-analysis.yml
Normal file
24
.gitea/workflows/song-analysis.yml
Normal file
@ -0,0 +1,24 @@
|
||||
name: song-analysis-contract
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/song_analysis/**'
|
||||
- 'tools/test_song_analysis.py'
|
||||
- 'schemas/song-analysis-v*/**'
|
||||
- '.gitea/workflows/song-analysis.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'tools/song_analysis/**'
|
||||
- 'tools/test_song_analysis.py'
|
||||
- 'schemas/song-analysis-v*/**'
|
||||
- '.gitea/workflows/song-analysis.yml'
|
||||
jobs:
|
||||
python-contract:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
- run: python -m pip install 'jsonschema>=4.20,<5'
|
||||
- run: PYTHONPATH=tools python -m unittest tools.test_song_analysis
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@ -5,12 +5,12 @@ songs/*
|
||||
*.mp3
|
||||
*.wav
|
||||
*.zip
|
||||
tools/.venv
|
||||
tools/song_analysis/.venv
|
||||
tools/song_analysis/.cache
|
||||
tools/song_analysis/.python
|
||||
tools/song_analysis/vamp
|
||||
tools/song_analysis/.models
|
||||
tools/.venv/
|
||||
tools/song_analysis/.venv/
|
||||
tools/song_analysis/.cache/
|
||||
tools/song_analysis/.python/
|
||||
tools/song_analysis/vamp/
|
||||
tools/song_analysis/.models/
|
||||
__pycache__/
|
||||
|
||||
# Eigene Songs bleiben lokal; nur das Testchart gehört ins Repo (Beispielsongs folgen später)
|
||||
|
||||
53
AGENTS.md
53
AGENTS.md
@ -1,53 +0,0 @@
|
||||
# Regeln für Agenten und Mitarbeitende (Singtrainer)
|
||||
|
||||
Diese Datei gilt für alle, die in diesem Repository arbeiten (Claude Code, Codex, Menschen). `CLAUDE.md` verweist hierher.
|
||||
Antworten und Oberflächentexte auf Deutsch; neuer Code folgt Stil, Benennung und Kommentardichte der Umgebung.
|
||||
|
||||
## Parallel arbeiten: ein Arbeitsordner je Aufgabe (git worktree)
|
||||
|
||||
Mehrere Agenten im selben Ordner stören sich: Wer `git checkout` macht, verschiebt den anderen Branch und Dateien unter den
|
||||
Händen, und `git add -A` nimmt fremde, halbfertige Änderungen mit. Deshalb:
|
||||
|
||||
1. **Der Hauptordner `~/chuck/singstar` bleibt auf `main` und sauber.** Dort wird nicht entwickelt. Er enthält die lokalen
|
||||
Daten (Songs, Python-Umgebungen, Modelle, `target/`).
|
||||
2. **Jede Aufgabe bekommt einen eigenen Worktree und Branch:**
|
||||
```sh
|
||||
tools/worktree-new.sh <name> # legt ../singstar-wt/<name> auf dem neuen Branch feat/<name> an
|
||||
cd ../singstar-wt/<name>
|
||||
```
|
||||
Das Skript verknüpft die lokalen, nicht versionierten Daten (`songs/`, eigene `charts/*.toml`, Umgebung und Modelle des
|
||||
Analysewerkzeugs) per Symlink aus dem Hauptordner. Verknüpfungen sind in `.gitignore` ausgeschlossen.
|
||||
3. **Aufräumen nach dem Merge:** `tools/worktree-rm.sh <name>`. Nie einen Worktree mit `rm -rf` oder `git worktree remove` direkt
|
||||
löschen, solange Verknüpfungen darin liegen; das Skript löst sie vorher.
|
||||
4. **Nie `git checkout`/`switch`, `git reset --hard`, `git stash` oder `git clean` in einem Ordner, den du nicht selbst
|
||||
angelegt hast.** Den Branch eines anderen Ordners nicht verändern.
|
||||
5. **Nur eigene Dateien committen:** `git add <Pfade>`, nie `git add -A` oder `git add .`; vor jedem Commit `git status` lesen.
|
||||
6. **Zusammenführen:** Branch pushen und als Pull-Anfrage in Gitea mergen (die CI läuft dort), oder auf ausdrückliche Anweisung
|
||||
lokal vorspulen. **Gepusht wird nur auf ausdrückliche Anweisung** des Eigentümers.
|
||||
7. Ein Build im neuen Worktree baut zuerst alles neu (einige Minuten, eigener `target/`). Wer Platz und Zeit sparen will, setzt
|
||||
gemeinsam `CARGO_TARGET_DIR` (Cargo sperrt dann gleichzeitige Builds, es läuft nacheinander).
|
||||
|
||||
## Prüfen vor jedem Commit und Push
|
||||
|
||||
```sh
|
||||
cargo fmt --check && cargo clippy --all-targets --locked -- -D warnings && cargo test --locked
|
||||
cd tools && song_analysis/.venv/bin/python -m unittest test_song_analysis # nur wenn tools/song_analysis geändert wurde
|
||||
```
|
||||
`.githooks/pre-push` prüft das Rust-Teil lokal (einschalten: `git config core.hooksPath .githooks`); die CI
|
||||
(`.gitea/workflows/ci.yml`) prüft dasselbe bei Pull-Anfragen und Push auf `main`.
|
||||
|
||||
## Daten und Geheimnisse
|
||||
|
||||
- **Eigene Songs, Aufnahmen und Charts gehören nicht ins Repository** (`songs/`, `charts/*.toml` sind ausgeschlossen); einzige
|
||||
Ausnahmen: `charts/test.toml` und der Beispielsong `songs/take-it-slow/`. Liedtexte eigener Songs nicht in Tests,
|
||||
Beispiele, Commit-Texte oder Antworten kopieren.
|
||||
- **Keine Zugangsdaten** in Dateien, Commits oder Chat: `.env` ist ausgeschlossen, Tokens nur in lokalen Dateien. Den
|
||||
Registrierungstoken des CI-Runners nie ausgeben.
|
||||
- Bildschirmfotos der Oberfläche nur im virtuellen Bildschirm (`xvfb-run`, App mit `--sim`), nie vom echten Desktop.
|
||||
- SSH-Hostschlüsselprüfung nicht umgehen.
|
||||
|
||||
## Wichtige Orte
|
||||
|
||||
- `README.md` Kurzfassung, `docs/handbuch.md` ausführlich, `tools/song_analysis/README.md` Analysewerkzeug.
|
||||
- `src/config.rs`: alle Schwellen und Standardwerte zentral; keine Zahlen im Code verstreuen.
|
||||
- Audio-Callbacks sind sperrenfrei: keine Allokation, keine Locks, kein I/O dort.
|
||||
@ -2,7 +2,6 @@
|
||||
name = "singtrainer"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
|
||||
21
LICENSE
21
LICENSE
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 wlkns-dev
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@ -30,7 +30,7 @@ Entwickelt und getestet unter CachyOS (Arch-basiert) mit PipeWire; vorgesehene H
|
||||
|
||||
**CI-Runner:** `tools/ci-runner/` startet einen Gitea-Runner mit Zugriff auf den Docker-Socket des Rechners. Das gibt ihm Root-Rechte dort und führt Code aus Pull-Anfragen aus. Nur für Repositories verwenden, in die nur du schreibst.
|
||||
|
||||
**Disclaimer:** Der Singtrainer ist nicht verbunden mit oder gesponsert von SingStar, UltraStar oder Suno. Das Projekt wird im Ist-Zustand und ohne jegliche Garantie bereitgestellt – siehe [LICENSE](LICENSE).
|
||||
**Disclaimer:** Der Singtrainer ist nicht verbunden mit oder gesponsert von SingStar, UltraStar oder Suno. Das Projekt wird im Ist-Zustand und ohne jegliche Garantie bereitgestellt.
|
||||
|
||||
## How this was built
|
||||
|
||||
@ -136,7 +136,7 @@ Alle Funktionen, Kommandozeilenoptionen, Entwicklungshilfen (`--sim`, `--tab`, `
|
||||
|
||||
## License
|
||||
|
||||
Der eigene Code des Singtrainers ist lizenziert unter der [MIT-Lizenz](LICENSE).
|
||||
Eine Lizenz für den eigenen Code ist noch nicht festgelegt; bis eine `LICENSE`-Datei vorliegt, gilt: alle Rechte vorbehalten.
|
||||
|
||||
Der Beispielsong **Take It Slow** (`songs/take-it-slow/`, `charts/take-it-slow.toml`) wurde mit Suno (Pro-Abonnement) erzeugt. Musik, Gesang und Text sind KI-generiert; es gelten die Nutzungsbedingungen von Suno zum Zeitpunkt der Erzeugung (2026-11-01). Einzelheiten: [`songs/take-it-slow/LIZENZ.md`](songs/take-it-slow/LIZENZ.md). Eigene Songs liegen nicht im Repository.
|
||||
|
||||
|
||||
54
docs/superpowers/plans/2026-11-01-song-analysis-v2.md
Normal file
54
docs/superpowers/plans/2026-11-01-song-analysis-v2.md
Normal file
@ -0,0 +1,54 @@
|
||||
# Song Analysis v2 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Publish a v2 analysis contract with lyric provenance, stable timeline and correct metadata updates.
|
||||
|
||||
**Architecture:** Python writes v2 JSON while Rust reads both versions. Chord data remains raw; supplied lyrics use timed draft phrases to bound line alignment.
|
||||
|
||||
**Tech Stack:** Python 3.11, jsonschema, WhisperX, Rust serde.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-01-song-analysis-v2-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Preserve existing v1 files and manually edited outputs without `--force`.
|
||||
- All stored times use seconds from the normalized source origin.
|
||||
- Do not invent calibrated chord confidence.
|
||||
|
||||
## Review Focus
|
||||
|
||||
- v1 folder with strict Rust deserialization still loads.
|
||||
- Supplied lyric section and line boundaries survive.
|
||||
- Unmatched lyric line does not get an invented timestamp.
|
||||
- Automatic BPM changes when beat file changes.
|
||||
- Manual BPM survives a rerun.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Contract and metadata
|
||||
|
||||
**Files:** `schemas/song-analysis-v2/*`, `src/song_analysis.rs`, `tests/song_analysis_contract.rs`, `tools/song_analysis/cli.py`, `tools/test_song_analysis.py`
|
||||
|
||||
- [ ] Write failing Python and Rust tests for v2 fields and v1 compatibility.
|
||||
- [ ] Run tests and confirm expected failures.
|
||||
- [ ] Add v2 schemas, version-aware validation and metadata source handling, plus `--title`.
|
||||
- [ ] Run tests and confirm they pass.
|
||||
|
||||
### Task 2: Lyric sections and alignment
|
||||
|
||||
**Files:** `tools/song_analysis/{core.py,backends.py,cli.py}`, `tools/test_song_analysis.py`
|
||||
|
||||
- [ ] Write failing tests for line parsing, sections, quality and bounded alignment.
|
||||
- [ ] Run tests and confirm expected failures.
|
||||
- [ ] Implement line-aware alignment and quality fields.
|
||||
- [ ] Run tests and confirm they pass.
|
||||
|
||||
### Task 3: Reproducibility and guidance
|
||||
|
||||
**Files:** `tools/song_analysis/{requirements.txt,README.md}`, `.github/workflows/song-analysis.yml`, `tools/test_song_analysis.py`
|
||||
|
||||
- [ ] Pin madmom-infer to the installed commit.
|
||||
- [ ] Document timeline, unverified drafts, raw chords, time signature support and observed resource costs.
|
||||
- [ ] Add lightweight CI and opt-in audio smoke test.
|
||||
- [ ] Run Python tests, Rust contract test, schema validation and `git diff --check`.
|
||||
@ -0,0 +1,9 @@
|
||||
# Song Analysis v2 Design
|
||||
|
||||
The Python tool keeps raw chord times and `N` spans. Display consumers may snap boundaries to beats and flag spans shorter than 0.5 s; stored times remain unchanged. Chordino's `simplechord` output has no calibrated confidence, so `conf` remains null.
|
||||
|
||||
New runs write schema v2. The Rust loader accepts v1 and v2. V2 adds `meta.bpm_source` (`automatic` or `manual`), `meta.source_offset_s` (0), and optional `lyrics.lines[].source_line`, `section`, and `alignment_conf`. With supplied lyrics, input lines and section headings are preserved. WhisperX first transcribes the song to obtain timed phrases, then aligns each supplied line in its own matched phrase window. If matching fails, the line stays unaligned rather than receiving invented timing. A line confidence is the mean of aligned word scores; absent scores yield null. Without supplied lyrics, the output remains a draft with `verified=false`.
|
||||
|
||||
`--title` sets the title explicitly. BPM follows `beats.json` unless marked manual, including on reruns. Existing v1 folders remain readable and are not silently rewritten unless a new run writes metadata. The ffmpeg normalization keeps the input timeline origin, so `source_offset_s=0.0`. This does not compensate for encoder delay already present in the decoded source.
|
||||
|
||||
Tests cover metadata refresh, v1/v2 loading, lyric structure and windowing. Lightweight CI installs only jsonschema. The optional backend smoke test runs on generated audio in the full environment. CPU timing and observed peak memory are documented as measurements of the one 216 s run, not general guarantees.
|
||||
1
schemas/song-analysis-v2/beats.schema.json
Normal file
1
schemas/song-analysis-v2/beats.schema.json
Normal file
@ -0,0 +1 @@
|
||||
{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Beat times v2","type":"object","required":["beats","downbeats"],"properties":{"beats":{"type":"array","items":{"type":"number","minimum":0}},"downbeats":{"type":"array","items":{"type":"number","minimum":0}}},"additionalProperties":false}
|
||||
1
schemas/song-analysis-v2/chords.schema.json
Normal file
1
schemas/song-analysis-v2/chords.schema.json
Normal file
@ -0,0 +1 @@
|
||||
{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Chord spans v2","type":"array","items":{"type":"object","required":["chord","start","end","conf"],"properties":{"chord":{"type":"string","minLength":1},"start":{"type":"number","minimum":0},"end":{"type":"number","minimum":0},"conf":{"type":["number","null"],"minimum":0,"maximum":1}},"additionalProperties":false}}
|
||||
1
schemas/song-analysis-v2/lyrics.schema.json
Normal file
1
schemas/song-analysis-v2/lyrics.schema.json
Normal file
@ -0,0 +1 @@
|
||||
{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Aligned lyrics v2","type":"object","required":["verified","lines"],"properties":{"verified":{"type":"boolean"},"lines":{"type":"array","items":{"type":"object","required":["start","end","words"],"properties":{"start":{"type":["number","null"],"minimum":0},"end":{"type":["number","null"],"minimum":0},"source_line":{"type":"integer","minimum":1},"section":{"type":["string","null"]},"alignment_conf":{"type":["number","null"],"minimum":0,"maximum":1},"words":{"type":"array","items":{"type":"object","required":["w","start","end","conf"],"properties":{"w":{"type":"string","minLength":1},"start":{"type":"number","minimum":0},"end":{"type":"number","minimum":0},"conf":{"type":["number","null"],"minimum":0,"maximum":1}},"additionalProperties":false}}},"additionalProperties":false}}},"additionalProperties":false}
|
||||
1
schemas/song-analysis-v2/meta.schema.json
Normal file
1
schemas/song-analysis-v2/meta.schema.json
Normal file
@ -0,0 +1 @@
|
||||
{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Song analysis meta v2","type":"object","required":["title","bpm","bpm_source","key","duration","source_offset_s","schema_version","errors"],"properties":{"title":{"type":"string"},"bpm":{"type":["number","null"],"exclusiveMinimum":0},"bpm_source":{"enum":["automatic","manual"]},"key":{"type":["string","null"]},"duration":{"type":"number","minimum":0},"source_offset_s":{"const":0.0},"schema_version":{"const":2},"errors":{"type":"object","additionalProperties":{"type":"string"}}},"additionalProperties":false}
|
||||
1
schemas/song-analysis-v2/pitch.schema.json
Normal file
1
schemas/song-analysis-v2/pitch.schema.json
Normal file
@ -0,0 +1 @@
|
||||
{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Pitch curve v2","type":"object","required":["hop_ms","hz","conf"],"properties":{"hop_ms":{"const":10},"hz":{"type":"array","items":{"type":"number","minimum":0}},"conf":{"type":"array","items":{"type":"number","minimum":0,"maximum":1}}},"additionalProperties":false}
|
||||
@ -1,4 +1,4 @@
|
||||
//! Version 1 of `schemas/song-analysis-v1/`, with seconds relative to the normalized mix.
|
||||
//! Versions 1 and 2 of the song-analysis contract, with seconds relative to the source origin.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -10,8 +10,12 @@ use std::path::{Path, PathBuf};
|
||||
pub struct Meta {
|
||||
pub title: String,
|
||||
pub bpm: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub bpm_source: Option<String>,
|
||||
pub key: Option<String>,
|
||||
pub duration: f64,
|
||||
#[serde(default)]
|
||||
pub source_offset_s: Option<f64>,
|
||||
pub schema_version: u32,
|
||||
pub errors: BTreeMap<String, String>,
|
||||
}
|
||||
@ -52,8 +56,14 @@ pub struct Word {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Line {
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
pub start: Option<f64>,
|
||||
pub end: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub source_line: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub section: Option<String>,
|
||||
#[serde(default)]
|
||||
pub alignment_conf: Option<f64>,
|
||||
pub words: Vec<Word>,
|
||||
}
|
||||
|
||||
@ -101,12 +111,18 @@ pub fn load_analysis(dir: &Path) -> Result<Analysis> {
|
||||
let meta: Meta = serde_json::from_slice(
|
||||
&std::fs::read(&path).with_context(|| format!("{} lesen", path.display()))?,
|
||||
)?;
|
||||
if meta.schema_version != 1 {
|
||||
if meta.schema_version != 1 && meta.schema_version != 2 {
|
||||
bail!(
|
||||
"Unbekannte song-analysis schema_version {}",
|
||||
meta.schema_version
|
||||
);
|
||||
}
|
||||
if meta.schema_version == 2
|
||||
&& (meta.source_offset_s != Some(0.0)
|
||||
|| !matches!(meta.bpm_source.as_deref(), Some("automatic" | "manual")))
|
||||
{
|
||||
bail!("Ungültige v2-Metadaten: bpm_source oder source_offset_s fehlt");
|
||||
}
|
||||
let pitch: Option<Pitch> = read_optional(dir, "pitch.json")?;
|
||||
if pitch
|
||||
.as_ref()
|
||||
|
||||
@ -21,7 +21,28 @@ fn reads_optional_outputs_from_one_folder() {
|
||||
fn rejects_unknown_schema_version() {
|
||||
let dir = std::env::temp_dir().join(format!("song-analysis-version-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("meta.json"), r#"{"title":"Example","bpm":null,"key":null,"duration":3.0,"schema_version":2,"errors":{}}"#).unwrap();
|
||||
std::fs::write(dir.join("meta.json"), r#"{"title":"Example","bpm":null,"key":null,"duration":3.0,"schema_version":3,"errors":{}}"#).unwrap();
|
||||
assert!(load_analysis(&dir).is_err());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_v2_metadata_and_lyric_provenance() {
|
||||
let dir = std::env::temp_dir().join(format!("song-analysis-v2-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("meta.json"), r#"{"title":"Example","bpm":120.0,"bpm_source":"automatic","source_offset_s":0.0,"key":null,"duration":3.0,"schema_version":2,"errors":{}}"#).unwrap();
|
||||
std::fs::write(dir.join("lyrics.json"), r#"{"verified":true,"lines":[{"start":0.1,"end":0.3,"source_line":2,"section":"verse","alignment_conf":0.8,"words":[{"w":"Hello","start":0.1,"end":0.3,"conf":0.8}]}]}"#).unwrap();
|
||||
let result = load_analysis(&dir).unwrap();
|
||||
assert_eq!(result.meta.source_offset_s, Some(0.0));
|
||||
assert_eq!(result.lyrics.unwrap().lines[0].source_line, Some(2));
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_v2_metadata_without_timeline_origin() {
|
||||
let dir = std::env::temp_dir().join(format!("song-analysis-v2-missing-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("meta.json"), r#"{"title":"Example","bpm":120.0,"bpm_source":"automatic","key":null,"duration":3.0,"schema_version":2,"errors":{}}"#).unwrap();
|
||||
assert!(load_analysis(&dir).is_err());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
@ -28,21 +28,27 @@ Die obigen PyTorch-Builds laufen auf der CPU. Für GPU-Betrieb ist ein zur Grafi
|
||||
Aufruf (mit dieser Umgebung):
|
||||
|
||||
```bash
|
||||
tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --lyrics lyrics.txt
|
||||
tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --lyrics lyrics.txt --title "Songtitel"
|
||||
tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --force
|
||||
```
|
||||
|
||||
Optionen: `--language en` für die WhisperX-Sprache, `--whisper-model large-v3`, `--separator-bin /pfad/audio-separator`, `--model-dir /pfad/modelle`, `--roformer-model DATEI`. Wenn der BS-RoFormer bereits unter `~/AI/models/maestro/ckpts/roformer/` liegt, kann dieser Ordner mit `--model-dir` verwendet werden. Das Demucs-Modell heißt `htdemucs_ft.yaml`.
|
||||
Optionen: `--title "Songtitel"`, `--language en` für die WhisperX-Sprache, `--whisper-model large-v3`, `--separator-bin /pfad/audio-separator`, `--model-dir /pfad/modelle`, `--roformer-model DATEI`. Wenn der BS-RoFormer bereits unter `~/AI/models/maestro/ckpts/roformer/` liegt, kann dieser Ordner mit `--model-dir` verwendet werden. Das Demucs-Modell heißt `htdemucs_ft.yaml`.
|
||||
|
||||
## Ablauf und Dateien
|
||||
|
||||
1. ffmpeg erzeugt `_cache/original.wav` mit 44,1 kHz und Stereo. Dessen Beginn ist für alle Zeiten Sekunde 0.
|
||||
1. ffmpeg erzeugt `_cache/original.wav` mit 44,1 kHz und Stereo. Der Beginn des decodierten Quell-Audiostücks bleibt Sekunde 0; ffmpeg fügt keinen Pipeline-Versatz hinzu. `meta.source_offset_s` ist deshalb 0.0. Ein bereits im Quellmedium vorhandener Encoder-Vorlauf wird nicht herausgerechnet. `apad` verlängert Stems nur am Ende.
|
||||
2. `audio-separator` trennt Vocals und Instrumental mit BS-RoFormer; `htdemucs_ft` trennt das Instrumental in Drums, Bass und Other. Die vier Stems liegen unter `stems/`. `_cache/instrumental.wav` ist ein Zwischenprodukt für Wiederaufnahmen.
|
||||
3. madmom Downbeat Tracking berechnet `beats.json` und BPM. `vamp-simple-host` mit Chordino berechnet `chords.json`. Chordino liefert keine Kalibrierung der Akkordsicherheit; `conf` ist deshalb `null`.
|
||||
3. madmom Downbeat Tracking berechnet `beats.json` und BPM. Der Decoder sucht derzeit nur 3/4- und 4/4-Takte; 5/4 und andere Metren benötigen eine Erweiterung. `vamp-simple-host` mit Chordino berechnet `chords.json`. Dessen `simplechord`-Ausgabe liefert keine kalibrierte Akkordsicherheit; `conf` ist deshalb `null`. Ein Abstand zum zweitbesten Akkord wäre ohne Kalibrierung keine verlässliche Wahrscheinlichkeit. Akkordgrenzen bleiben auf den von Chordino erkannten Zeiten; die App darf sie zur Anzeige optional auf Beats einrasten, ohne die Rohdaten zu ändern. `N` bedeutet „kein erkannter Akkord“. Spannen unter 0,5 s sollte ein Verbraucher als mögliche Ausreißer markieren oder für eine vereinfachte Anzeige ausblenden; in der Datei bleiben sie erhalten.
|
||||
4. torchcrepe (PyTorch-Implementierung von CREPE) liefert `pitch.json` mit 10-ms-Raster. Frequenzen unter 0,5 Konfidenz werden als 0 Hz (unvoiced) geschrieben; die tatsächliche Konfidenz bleibt in `conf`. Basic Pitch verarbeitet denselben Vocal-Stem separat für `melody.mid` und den Other-Stem für `guitar.mid`.
|
||||
5. WhisperX richtet den gelieferten Text wortweise aus. Ohne `--lyrics` transkribiert WhisperX selbst, und `lyrics.json` trägt `verified: false`. Wörter ohne Zeiten werden ausgelassen. Die Zeilen entstehen aus Pausen über 0,6 s, Taktgrenzen und etwa 40 Zeichen.
|
||||
5. Mit `--lyrics` transkribiert WhisperX zunächst zeitgestempelte Phrasen. Jede nichtleere Eingabezeile wird anschließend in einem passenden Phrasenfenster einzeln ausgerichtet. `source_line` (1-basiert) und die letzte Abschnittsmarke wie `[Verse]` in `section` bleiben erhalten. Fehlt ein sicher passendes Fenster oder gelingen keine Wortzeiten, hat die Zeile `start: null`, `end: null`, leere `words` und `alignment_conf: null`; ein Mensch muss sie nachbearbeiten. `alignment_conf` ist der Mittelwert vorhandener Wort-Scores, multipliziert mit dem Anteil ausgerichteter Wörter. `verified: true` besagt nur, dass der Text vorgegeben wurde, nicht dass die Zeitzuordnung geprüft ist. Ohne `--lyrics` entsteht ein **ungeprüfter Entwurf** (`verified: false`); Wortlaut und Wortzeiten müssen kontrolliert werden. Diese automatischen Zeilen entstehen aus Pausen über 0,6 s, Taktgrenzen und etwa 40 Zeichen. Wörter ohne Zeiten werden ausgelassen. Ein echter Lauf mit `--lyrics` über einen ganzen Song wurde bisher nicht gegen Referenzwerte geprüft.
|
||||
6. madmom schätzt die Tonart für `meta.json`; bei fehlender Erkennung ist `key` null. Alle JSON-Dateien werden gegen `schemas/song-analysis-v1/` geprüft.
|
||||
|
||||
Jeder Schritt prüft seine Ausgabedateien. Ein normaler erneuter Lauf lässt vorhandene Dateien unverändert, einschließlich manueller Korrekturen. `--force` berechnet sie neu. Fehlgeschlagene Schritte stehen unter `meta.json.errors`; die CLI beendet sich dann mit Status 1. Unabhängige Schritte laufen weiter. `meta.json` wird für den aktuellen Fehlerstatus aktualisiert; seine manuell gesetzten Werte für `title`, `bpm`, `key` und `duration` bleiben ohne `--force` erhalten.
|
||||
Jeder Schritt prüft seine Ausgabedateien. Ein normaler erneuter Lauf lässt vorhandene Dateien unverändert, einschließlich manueller Korrekturen. `--force` berechnet sie neu. Fehlgeschlagene Schritte stehen unter `meta.json.errors`; die CLI beendet sich dann mit Status 1. Unabhängige Schritte laufen weiter. `meta.json` wird für den aktuellen Fehlerstatus aktualisiert. Ein manuell gesetztes BPM muss `bpm_source: "manual"` tragen; sonst wird es aus `beats.json` neu berechnet. `--title` setzt einen expliziten Titel. Manuell gesetzte Titel, Tonarten und Dauern bleiben ohne `--force` erhalten.
|
||||
|
||||
Die JSON-Strukturen haben `schema_version: 1` in `meta.json`. Alle Zeiten sind Sekunden als Fließkommazahlen. Für das Tool sind `conf: null` und fehlende Dateien mögliche Zustände. MIDI enthält normale Noten-Events; insbesondere die Gitarrentranskription ist keine Tabulatur. Die genannten Qualitätszahlen hängen stark vom Material ab und sind keine vom Werkzeug garantierten Fehlerschranken.
|
||||
Neue Ausgaben haben `schema_version: 2` in `meta.json`; der Rust-Lader akzeptiert auch v1. Die zugehörigen Schemas liegen unter `schemas/song-analysis-v2/`. Alle Zeiten sind Sekunden als Fließkommazahlen. Für das Tool sind `conf: null` und fehlende Dateien mögliche Zustände. MIDI enthält normale Noten-Events; insbesondere die Gitarrentranskription ist keine Tabulatur. Die genannten Qualitätszahlen hängen stark vom Material ab und sind keine vom Werkzeug garantierten Fehlerschranken.
|
||||
|
||||
## Tests und Ressourcen
|
||||
|
||||
Die leichten Vertragstests benötigen nur Python 3.11 und `jsonschema`: `PYTHONPATH=tools python -m unittest tools.test_song_analysis`. Die Gitea-CI führt sie bei Änderungen am Werkzeug oder Schema aus. Mit vollständig installierter Audio-Umgebung kann `PYTHONPATH=tools tools/song_analysis/.venv/bin/python -m unittest tools.test_song_analysis_smoke` einen erzeugten 1-Sekunden-Ton mit CREPE prüfen.
|
||||
|
||||
Beobachtung am 216-Sekunden-Beispiel auf Oberon (AMD Radeon 890M, isolierte Umgebung mit PyTorch `2.5.1+cpu`, also **GPU: nein**): BS-RoFormer etwa 11:55 min, Demucs `htdemucs_ft` etwa 6:19 min, CREPE mit 512-Frame-Batches etwa 2:32 min. Bei CREPE wurden maximal 1,99 GB Prozess-RSS gemessen; vor der Batch-Begrenzung erreichte der Gesamtprozess rund 22 GB und erzeugte Speicherdruck. Für Beats, Chordino, Basic Pitch und WhisperX liegen keine getrennt gemessenen Laufzeiten oder RSS-Spitzen vor. Diese Zahlen sind Messwerte eines Laufs, keine Zusicherung für andere Rechner oder Songs.
|
||||
|
||||
@ -2,12 +2,11 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from .core import parse_chordino
|
||||
from .core import bpm_from_beats, make_aligned_line, match_lyric_windows, parse_chordino, parse_lyrics
|
||||
|
||||
|
||||
def command(args: list[str], *, capture: bool = False, env: dict[str, str] | None = None) -> str:
|
||||
@ -70,8 +69,7 @@ def detect_beats(audio: Path) -> tuple[dict, float | None]:
|
||||
positions = DBNDownBeatTrackingProcessor(beats_per_bar=[3, 4], fps=100)(activations)
|
||||
beats = [float(row[0]) for row in positions]
|
||||
downbeats = [float(row[0]) for row in positions if int(row[1]) == 1]
|
||||
gaps = [b - a for a, b in zip(beats, beats[1:]) if 0.2 <= b - a <= 2]
|
||||
bpm = round(60 / statistics.median(gaps), 2) if gaps else None
|
||||
bpm = bpm_from_beats(beats)
|
||||
return {"beats": beats, "downbeats": downbeats}, bpm
|
||||
|
||||
|
||||
@ -138,8 +136,7 @@ def transcribe_midi(audio: Path, target: Path) -> None:
|
||||
staged.replace(target)
|
||||
|
||||
|
||||
def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
model_name: str) -> tuple[list[dict], bool]:
|
||||
def lyrics_words(audio: Path, language: str, model_name: str) -> list[dict]:
|
||||
import torch
|
||||
import whisperx
|
||||
|
||||
@ -148,20 +145,11 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
last_error = None
|
||||
for device in devices:
|
||||
try:
|
||||
if lyrics:
|
||||
text = " ".join(line.strip() for line in lyrics.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip() and not line.lstrip().startswith(("#", "[")))
|
||||
if not text:
|
||||
raise ValueError("Liedtext enthält keine Wörter")
|
||||
segments = [{"start": 0.0, "end": len(audio_data) / 16000, "text": text}]
|
||||
verified = True
|
||||
else:
|
||||
model = whisperx.load_model(model_name, device, compute_type="float16" if device == "cuda" else "int8")
|
||||
result = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2,
|
||||
language=language)
|
||||
segments = result["segments"]
|
||||
verified = False
|
||||
del model
|
||||
model = whisperx.load_model(model_name, device, compute_type="float16" if device == "cuda" else "int8")
|
||||
result = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2,
|
||||
language=language)
|
||||
segments = result["segments"]
|
||||
del model
|
||||
aligner, metadata = whisperx.load_align_model(language_code=language, device=device)
|
||||
aligned = whisperx.align(segments, aligner, metadata, audio_data, device,
|
||||
return_char_alignments=False)
|
||||
@ -174,7 +162,7 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
"conf": float(item["score"]) if item.get("score") is not None else None})
|
||||
if not words:
|
||||
raise RuntimeError("WhisperX lieferte keine ausgerichteten Wörter")
|
||||
return words, verified
|
||||
return words
|
||||
except (RuntimeError, MemoryError) as exc:
|
||||
last_error = exc
|
||||
if device == "cuda":
|
||||
@ -182,3 +170,40 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
continue
|
||||
raise
|
||||
raise RuntimeError(f"WhisperX fehlgeschlagen: {last_error}")
|
||||
|
||||
|
||||
def align_lyric_lines(audio: Path, lyrics: Path, language: str, model_name: str) -> list[dict]:
|
||||
"""Use timed draft phrases to keep each supplied line inside its own audio window."""
|
||||
import torch
|
||||
import whisperx
|
||||
|
||||
source_lines = parse_lyrics(lyrics.read_text(encoding="utf-8"))
|
||||
if not source_lines:
|
||||
raise ValueError("Liedtext enthält keine Wörter")
|
||||
audio_data = whisperx.load_audio(str(audio))
|
||||
devices = ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"]
|
||||
for device in devices:
|
||||
try:
|
||||
model = whisperx.load_model(model_name, device,
|
||||
compute_type="float16" if device == "cuda" else "int8")
|
||||
draft = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2,
|
||||
language=language)
|
||||
del model
|
||||
windows = match_lyric_windows(source_lines, draft["segments"])
|
||||
aligner, metadata = whisperx.load_align_model(language_code=language, device=device)
|
||||
result = []
|
||||
for source_line, window in zip(source_lines, windows):
|
||||
if window is None:
|
||||
result.append(make_aligned_line(source_line, []))
|
||||
continue
|
||||
start, end = window
|
||||
segment = [{"start": start, "end": end, "text": source_line["text"]}]
|
||||
aligned = whisperx.align(segment, aligner, metadata, audio_data, device,
|
||||
return_char_alignments=False)
|
||||
result.append(make_aligned_line(source_line, aligned.get("word_segments", [])))
|
||||
return result
|
||||
except (RuntimeError, MemoryError):
|
||||
if device == "cpu":
|
||||
raise
|
||||
torch.cuda.empty_cache()
|
||||
raise RuntimeError("WhisperX konnte keine Lyrics ausrichten")
|
||||
|
||||
@ -6,7 +6,7 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
from . import backends
|
||||
from .core import group_words, run_step, validate_json, validate_outputs, write_json
|
||||
from .core import bpm_from_beats, group_words, run_step, validate_json, validate_outputs, write_json
|
||||
|
||||
|
||||
def resolve_separator_bin(value: str) -> str:
|
||||
@ -18,6 +18,7 @@ def resolve_separator_bin(value: str) -> str:
|
||||
|
||||
|
||||
def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool = False,
|
||||
title: str | None = None,
|
||||
separator_bin: str = "audio-separator", model_dir: Path | None = None,
|
||||
roformer_model: str = "model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
||||
language: str = "en", whisper_model: str = "large-v3") -> dict:
|
||||
@ -91,14 +92,18 @@ def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool
|
||||
lambda: backends.transcribe_midi(vocals, out / "melody.mid"), errors, force)
|
||||
lyrics_path = out / "lyrics.json"
|
||||
def lyrics_step():
|
||||
words, verified = backends.lyrics_words(vocals, lyrics, language, whisper_model)
|
||||
downbeats = []
|
||||
if (out / "beats.json").exists():
|
||||
try:
|
||||
downbeats = json.loads((out / "beats.json").read_text(encoding="utf-8"))["downbeats"]
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
value = {"verified": verified, "lines": group_words(words, downbeats)}
|
||||
if lyrics:
|
||||
value = {"verified": True,
|
||||
"lines": backends.align_lyric_lines(vocals, lyrics, language, whisper_model)}
|
||||
else:
|
||||
words = backends.lyrics_words(vocals, language, whisper_model)
|
||||
downbeats = []
|
||||
if (out / "beats.json").exists():
|
||||
try:
|
||||
downbeats = json.loads((out / "beats.json").read_text(encoding="utf-8"))["downbeats"]
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
value = {"verified": False, "lines": group_words(words, downbeats)}
|
||||
validate_json("lyrics", value)
|
||||
write_json(lyrics_path, value)
|
||||
run_step("lyrics", [lyrics_path], lyrics_step, errors, force)
|
||||
@ -108,18 +113,20 @@ def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool
|
||||
lambda: backends.transcribe_midi(stems / "other.wav", out / "guitar.mid"),
|
||||
errors, force)
|
||||
|
||||
bpm = previous.get("bpm")
|
||||
bpm = None
|
||||
if (out / "beats.json").exists():
|
||||
try:
|
||||
beat_times = json.loads((out / "beats.json").read_text(encoding="utf-8"))["beats"]
|
||||
gaps = [b - a for a, b in zip(beat_times, beat_times[1:]) if 0.2 <= b - a <= 2]
|
||||
if gaps:
|
||||
import statistics
|
||||
bpm = round(60 / statistics.median(gaps), 2)
|
||||
bpm = bpm_from_beats(beat_times)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass
|
||||
if not force and previous.get("bpm") is not None:
|
||||
bpm_source = previous.get("bpm_source", "automatic")
|
||||
if previous.get("schema_version") == 1 and previous.get("bpm") is not None:
|
||||
bpm_source = "manual" if previous["bpm"] != bpm else "automatic"
|
||||
if not force and bpm_source == "manual" and previous.get("bpm") is not None:
|
||||
bpm = previous["bpm"]
|
||||
elif force:
|
||||
bpm_source = "automatic"
|
||||
validate_outputs(out, errors)
|
||||
key = previous.get("key")
|
||||
if mix.exists() and (force or key is None):
|
||||
@ -127,10 +134,10 @@ def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool
|
||||
key = backends.detect_key(mix)
|
||||
except Exception as exc:
|
||||
errors["key"] = f"{type(exc).__name__}: {exc}"
|
||||
meta = {"title": previous.get("title", source.stem) if not force else source.stem,
|
||||
"bpm": bpm, "key": key,
|
||||
meta = {"title": title if title is not None else (previous.get("title", source.stem) if not force else source.stem),
|
||||
"bpm": bpm, "bpm_source": bpm_source, "key": key,
|
||||
"duration": previous.get("duration", duration) if not force and previous.get("duration", 0) > 0 else duration,
|
||||
"schema_version": 1, "errors": errors}
|
||||
"source_offset_s": 0.0, "schema_version": 2, "errors": errors}
|
||||
try:
|
||||
validate_json("meta", meta)
|
||||
except Exception as exc:
|
||||
@ -144,6 +151,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("audio", type=Path)
|
||||
parser.add_argument("--out", required=True, type=Path)
|
||||
parser.add_argument("--lyrics", type=Path)
|
||||
parser.add_argument("--title")
|
||||
parser.add_argument("--force", action="store_true")
|
||||
parser.add_argument("--separator-bin", default="audio-separator")
|
||||
parser.add_argument("--model-dir", type=Path)
|
||||
@ -152,7 +160,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("--whisper-model", default="large-v3")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
meta = analyze(args.audio, args.out, args.lyrics, force=args.force,
|
||||
meta = analyze(args.audio, args.out, args.lyrics, force=args.force, title=args.title,
|
||||
separator_bin=args.separator_bin, model_dir=args.model_dir,
|
||||
roformer_model=args.roformer_model, language=args.language,
|
||||
whisper_model=args.whisper_model)
|
||||
|
||||
@ -2,9 +2,16 @@
|
||||
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
from difflib import SequenceMatcher
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA_DIR = Path(__file__).resolve().parents[2] / "schemas" / "song-analysis-v1"
|
||||
SCHEMA_DIR = Path(__file__).resolve().parents[2] / "schemas" / "song-analysis-v2"
|
||||
|
||||
|
||||
def bpm_from_beats(beats: list[float]) -> float | None:
|
||||
gaps = [b - a for a, b in zip(beats, beats[1:]) if 0.2 <= b - a <= 2]
|
||||
return round(60 / statistics.median(gaps), 2) if gaps else None
|
||||
|
||||
|
||||
def write_json(path: Path, value: object) -> None:
|
||||
@ -51,6 +58,66 @@ def group_words(words: list[dict], downbeats: list[float], max_chars: int = 40)
|
||||
return lines
|
||||
|
||||
|
||||
def parse_lyrics(text: str) -> list[dict]:
|
||||
"""Preserve sung line numbers and the most recent bracketed section label."""
|
||||
lines = []
|
||||
section = None
|
||||
for number, raw in enumerate(text.splitlines(), 1):
|
||||
stripped = raw.strip()
|
||||
if stripped.startswith("#") or not stripped:
|
||||
continue
|
||||
if stripped.startswith("[") and stripped.endswith("]"):
|
||||
section = stripped[1:-1].strip() or None
|
||||
continue
|
||||
lines.append({"text": stripped, "source_line": number, "section": section})
|
||||
return lines
|
||||
|
||||
|
||||
def match_lyric_windows(lines: list[dict], phrases: list[dict]) -> list[tuple[float, float] | None]:
|
||||
"""Match each input line to a later ASR phrase; leave uncertain lines unmatched."""
|
||||
windows = []
|
||||
cursor_phrase = 0
|
||||
cursor_word = 0
|
||||
for line in lines:
|
||||
target = re.findall(r"\w+", line["text"].casefold())
|
||||
best = (0.0, None)
|
||||
for index in range(cursor_phrase, len(phrases)):
|
||||
candidate = re.findall(r"\w+", phrases[index].get("text", "").casefold())
|
||||
for start in range(cursor_word if index == cursor_phrase else 0, len(candidate)):
|
||||
for length in range(max(1, len(target) - 2), len(target) + 3):
|
||||
end = min(len(candidate), start + length)
|
||||
score = SequenceMatcher(None, target, candidate[start:end]).ratio()
|
||||
if score > best[0]:
|
||||
best = (score, (index, start, end, len(candidate)))
|
||||
if best[0] >= 0.55 and best[1] is not None:
|
||||
index, start_word, end_word, count = best[1]
|
||||
phrase = phrases[index]
|
||||
start_time, end_time = float(phrase["start"]), float(phrase["end"])
|
||||
span = end_time - start_time
|
||||
windows.append((max(start_time, start_time + span * start_word / count - 0.3),
|
||||
min(end_time, start_time + span * end_word / count + 0.3)))
|
||||
cursor_phrase, cursor_word = index, end_word
|
||||
else:
|
||||
windows.append(None)
|
||||
return windows
|
||||
|
||||
|
||||
def make_aligned_line(source: dict, aligned: list[dict]) -> dict:
|
||||
words = [{"w": item["word"].strip(), "start": float(item["start"]),
|
||||
"end": float(item["end"]),
|
||||
"conf": float(item["score"]) if item.get("score") is not None else None}
|
||||
for item in aligned if item.get("word", "").strip()
|
||||
and item.get("start") is not None and item.get("end") is not None]
|
||||
scores = [word["conf"] for word in words if word["conf"] is not None]
|
||||
source_count = len(re.findall(r"\w+", source["text"]))
|
||||
coverage = min(1.0, len(words) / source_count) if source_count else 0.0
|
||||
return {"start": words[0]["start"] if words else None,
|
||||
"end": words[-1]["end"] if words else None,
|
||||
"source_line": source["source_line"], "section": source["section"],
|
||||
"alignment_conf": round(sum(scores) / len(scores) * coverage, 4) if scores else None,
|
||||
"words": words}
|
||||
|
||||
|
||||
_CHORD_EVENT = re.compile(r'^\s*([0-9]+(?:\.[0-9]+)?)\s*:\s*"?([^"\r\n]+?)"?\s*$')
|
||||
|
||||
|
||||
@ -88,8 +155,13 @@ def validate_json(kind: str, value: object) -> None:
|
||||
raise ValueError("beats: Zeiten sind nicht sortiert")
|
||||
if kind in ("chords", "lyrics"):
|
||||
spans = value if kind == "chords" else value["lines"]
|
||||
if any(item["end"] < item["start"] for item in spans):
|
||||
if any(item["end"] < item["start"] for item in spans
|
||||
if item["start"] is not None and item["end"] is not None):
|
||||
raise ValueError(f"{kind}: negativer Zeitbereich")
|
||||
if kind == "lyrics" and any((line["start"] is None) != (line["end"] is None)
|
||||
or (line["start"] is None and line["words"])
|
||||
for line in value["lines"]):
|
||||
raise ValueError("lyrics: nicht ausgerichtete Zeile braucht null-Zeiten und leere Wörter")
|
||||
|
||||
|
||||
def validate_outputs(out: Path, errors: dict[str, str]) -> None:
|
||||
|
||||
@ -10,7 +10,7 @@ transformers>=4.40,<5 # Version 5 deaktiviert PyTorch 2.5
|
||||
patchelf>=0.19.1 # Repariert bei Bedarf das GNU_STACK-Flag von CTranslate2 4.4
|
||||
scipy>=1.10
|
||||
soundfile>=0.12
|
||||
madmom-infer @ git+https://github.com/openmirlab/madmom-infer.git
|
||||
madmom-infer @ git+https://github.com/openmirlab/madmom-infer.git@bffead9be61857fd44b2e0d3a2510d9d94c8f2d2
|
||||
torchcrepe>=0.0.24
|
||||
basic-pitch>=0.4
|
||||
whisperx>=3.3
|
||||
|
||||
@ -5,9 +5,9 @@ import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from song_analysis.core import group_words, parse_chordino, run_step, validate_json
|
||||
from song_analysis.core import group_words, parse_chordino, parse_lyrics, match_lyric_windows, make_aligned_line, bpm_from_beats, run_step, validate_json
|
||||
from song_analysis.cli import analyze, resolve_separator_bin
|
||||
from song_analysis.backends import detect_beats, detect_pitch
|
||||
from song_analysis.backends import detect_beats
|
||||
|
||||
|
||||
class SongAnalysisTests(unittest.TestCase):
|
||||
@ -23,6 +23,37 @@ class SongAnalysisTests(unittest.TestCase):
|
||||
[["Hello", "there"], ["again"], ["friend"]])
|
||||
self.assertEqual(lines[0]["start"], 0.1)
|
||||
|
||||
def test_lyrics_preserve_source_lines_and_sections(self):
|
||||
lines = parse_lyrics("[Verse 1]\nHello there\n\n# comment\n[Chorus]\nSing along\n")
|
||||
self.assertEqual(lines, [
|
||||
{"text": "Hello there", "source_line": 2, "section": "Verse 1"},
|
||||
{"text": "Sing along", "source_line": 6, "section": "Chorus"},
|
||||
])
|
||||
|
||||
def test_lyrics_match_timed_phrases_without_inventing_missing_window(self):
|
||||
lines = parse_lyrics("[verse]\nHello there\nUnknown passage\nSing along")
|
||||
phrases = [{"start": 1.0, "end": 2.0, "text": "Hello there"},
|
||||
{"start": 9.0, "end": 10.0, "text": "Sing along"}]
|
||||
self.assertEqual(match_lyric_windows(lines, phrases), [(1.0, 2.0), None, (9.0, 10.0)])
|
||||
|
||||
def test_multiple_input_lines_can_match_one_long_phrase(self):
|
||||
lines = parse_lyrics("Hello there\nSing along")
|
||||
phrase = [{"start": 10.0, "end": 14.0, "text": "Hello there and sing along"}]
|
||||
windows = match_lyric_windows(lines, phrase)
|
||||
self.assertIsNotNone(windows[0])
|
||||
self.assertIsNotNone(windows[1])
|
||||
self.assertLess(windows[0][0], windows[1][0])
|
||||
|
||||
def test_lyric_line_quality_uses_available_word_scores(self):
|
||||
source = {"text": "Hello there", "source_line": 2, "section": "verse"}
|
||||
aligned = [{"word": "Hello", "start": 1.1, "end": 1.3, "score": 0.8},
|
||||
{"word": "there", "start": 1.4, "end": 1.6, "score": 0.6}]
|
||||
line = make_aligned_line(source, aligned)
|
||||
self.assertEqual(line["alignment_conf"], 0.7)
|
||||
self.assertEqual(line["source_line"], 2)
|
||||
self.assertEqual(line["start"], 1.1)
|
||||
self.assertEqual(make_aligned_line(source, [])["start"], None)
|
||||
|
||||
def test_chordino_events_end_at_next_event_or_duration(self):
|
||||
text = '0.000000: "C"\n1.250000: "Am"\n2.000000: "N"\n'
|
||||
self.assertEqual(parse_chordino(text, 3.0), [
|
||||
@ -62,23 +93,15 @@ class SongAnalysisTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
validate_json("pitch", {"hop_ms": 10, "hz": [440, 441], "conf": [0.9]})
|
||||
|
||||
def test_pitch_inference_limits_batch_size(self):
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
def test_lyric_line_cannot_have_one_missing_boundary(self):
|
||||
with self.assertRaises(ValueError):
|
||||
validate_json("lyrics", {"verified": True, "lines": [
|
||||
{"start": None, "end": 1.0, "words": []}
|
||||
]})
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
audio = Path(d) / "vocals.wav"
|
||||
sf.write(audio, np.zeros(16000, dtype=np.float32), 16000)
|
||||
def predict(signal, sample_rate, **kwargs):
|
||||
self.assertEqual(sample_rate, 16000)
|
||||
self.assertLessEqual(kwargs["batch_size"], 512)
|
||||
frames = 1 + signal.shape[1] // kwargs["hop_length"]
|
||||
return torch.zeros((1, frames)), torch.ones((1, frames))
|
||||
with patch("torchcrepe.predict", side_effect=predict):
|
||||
result = detect_pitch(audio)
|
||||
self.assertEqual(len(result["hz"]), 101)
|
||||
self.assertEqual(len(result["conf"]), 101)
|
||||
def test_bpm_from_beats_uses_median_of_plausible_intervals(self):
|
||||
self.assertEqual(bpm_from_beats([0, 0.5, 1.0, 10.0]), 120.0)
|
||||
self.assertIsNone(bpm_from_beats([]))
|
||||
|
||||
def test_madmom_decoder_receives_its_100_hz_frame_rate(self):
|
||||
module = types.ModuleType("madmom_infer.features.downbeats")
|
||||
@ -125,12 +148,34 @@ class SongAnalysisTests(unittest.TestCase):
|
||||
analyze(source, out)
|
||||
meta_path = out / "meta.json"
|
||||
meta = json.loads(meta_path.read_text())
|
||||
meta.update(title="Mein Titel", bpm=97.0, key="G major", duration=2.9)
|
||||
meta.update(title="Mein Titel", bpm=97.0, bpm_source="manual", key="G major", duration=2.9)
|
||||
meta_path.write_text(json.dumps(meta))
|
||||
result = analyze(source, out)
|
||||
self.assertEqual((result["title"], result["bpm"], result["key"], result["duration"]),
|
||||
("Mein Titel", 97.0, "G major", 2.9))
|
||||
self.assertIn("separator fehlt", result["errors"]["vocals"])
|
||||
self.assertEqual(result["schema_version"], 2)
|
||||
self.assertEqual(result["source_offset_s"], 0.0)
|
||||
self.assertEqual(result["bpm_source"], "manual")
|
||||
|
||||
def test_automatic_bpm_refreshes_from_edited_beats(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
out = Path(d)
|
||||
source = out / "input.wav"
|
||||
source.write_bytes(b"audio")
|
||||
(out / "_cache").mkdir()
|
||||
(out / "_cache" / "original.wav").write_bytes(b"wav")
|
||||
(out / "beats.json").write_text(json.dumps({"beats": [0, 0.5, 1], "downbeats": [0]}))
|
||||
with patch("song_analysis.backends.separate", side_effect=RuntimeError("skip")), \
|
||||
patch("song_analysis.backends.duration_of", return_value=2.0), \
|
||||
patch("song_analysis.backends.detect_key", return_value="C major"):
|
||||
first = analyze(source, out, title="Custom title")
|
||||
(out / "beats.json").write_text(json.dumps({"beats": [0, 1, 2], "downbeats": [0]}))
|
||||
second = analyze(source, out)
|
||||
self.assertEqual(first["bpm"], 120.0)
|
||||
self.assertEqual(second["bpm"], 60.0)
|
||||
self.assertEqual(second["bpm_source"], "automatic")
|
||||
self.assertEqual(second["title"], "Custom title")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
42
tools/test_song_analysis_smoke.py
Normal file
42
tools/test_song_analysis_smoke.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""Optional audio backend smoke test; run only in the full analysis environment."""
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
|
||||
from song_analysis.backends import detect_pitch
|
||||
|
||||
|
||||
class AudioSmokeTests(unittest.TestCase):
|
||||
def test_one_second_tone_has_a_bounded_pitch_batch(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
audio = Path(d) / "tone.wav"
|
||||
t = np.arange(16000, dtype=np.float32) / 16000
|
||||
sf.write(audio, 0.2 * np.sin(2 * np.pi * 440 * t), 16000)
|
||||
def predict(signal, sample_rate, **kwargs):
|
||||
self.assertEqual(sample_rate, 16000)
|
||||
self.assertLessEqual(kwargs["batch_size"], 512)
|
||||
frames = 1 + signal.shape[1] // kwargs["hop_length"]
|
||||
return torch.full((1, frames), 440.0), torch.ones((1, frames))
|
||||
with patch("torchcrepe.predict", side_effect=predict):
|
||||
result = detect_pitch(audio)
|
||||
self.assertEqual(len(result["hz"]), 101)
|
||||
self.assertEqual(result["hz"][50], 440.0)
|
||||
|
||||
def test_one_second_tone_runs_crepe(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
audio = Path(d) / "tone.wav"
|
||||
t = np.arange(16000, dtype=np.float32) / 16000
|
||||
sf.write(audio, 0.2 * np.sin(2 * np.pi * 440 * t), 16000)
|
||||
result = detect_pitch(audio)
|
||||
self.assertEqual(len(result["hz"]), 101)
|
||||
self.assertTrue(any(400 < hz < 480 for hz in result["hz"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -1,31 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Legt einen eigenen Arbeitsordner (git worktree) für eine Aufgabe an.
|
||||
# tools/worktree-new.sh <name> [basis-branch] (Standard-Basis: main)
|
||||
# Ergebnis: ../singstar-wt/<name> auf dem neuen Branch feat/<name>, mit Verknüpfungen auf die lokalen, nicht versionierten
|
||||
# Daten des Hauptordners. Regeln: siehe AGENTS.md.
|
||||
set -eu
|
||||
name="${1:-}"
|
||||
base="${2:-main}"
|
||||
case "$name" in
|
||||
""|*[!a-z0-9-]*) echo "Aufruf: tools/worktree-new.sh <name> [basis] (Name nur aus a-z, 0-9 und -)" >&2; exit 2 ;;
|
||||
esac
|
||||
# Der erste Eintrag von `git worktree list` ist immer der Hauptordner, egal von welchem Worktree aus man aufruft.
|
||||
main_dir="$(git worktree list --porcelain | awk '/^worktree /{print $2; exit}')"
|
||||
dest="$(dirname "$main_dir")/singstar-wt/$name"
|
||||
branch="feat/$name"
|
||||
[ -e "$dest" ] && { echo "Existiert schon: $dest" >&2; exit 1; }
|
||||
git worktree add -b "$branch" "$dest" "$base"
|
||||
|
||||
link() { # link <relativer Pfad>: Verknüpfung auf den Hauptordner, falls dort vorhanden und im Worktree frei
|
||||
src="$main_dir/$1"; tgt="$dest/$1"
|
||||
[ -e "$src" ] && [ ! -e "$tgt" ] && [ ! -L "$tgt" ] && { mkdir -p "$(dirname "$tgt")"; ln -s "$src" "$tgt"; }
|
||||
return 0
|
||||
}
|
||||
for p in tools/.venv tools/song_analysis/.venv tools/song_analysis/.cache tools/song_analysis/.models \
|
||||
tools/song_analysis/.python tools/song_analysis/vamp; do link "$p"; done
|
||||
# Eigene Songs und Charts einzeln (die Beispieldateien sind im Worktree schon vorhanden und werden nicht überdeckt).
|
||||
for f in "$main_dir"/songs/* "$main_dir"/charts/*.toml; do
|
||||
[ -e "$f" ] && link "${f#"$main_dir"/}"
|
||||
done
|
||||
echo "Fertig: $dest (Branch $branch)"
|
||||
echo "Hinweis: Der erste Build dort dauert einige Minuten (eigener target/). Aufräumen später: tools/worktree-rm.sh $name"
|
||||
@ -1,16 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Entfernt einen Arbeitsordner, der mit tools/worktree-new.sh angelegt wurde.
|
||||
# tools/worktree-rm.sh <name>
|
||||
# Löst zuerst die Verknüpfungen auf lokale Daten (ohne ihnen zu folgen) und verweigert bei ungespeicherten Änderungen.
|
||||
set -eu
|
||||
name="${1:-}"
|
||||
case "$name" in ""|*[!a-z0-9-]*) echo "Aufruf: tools/worktree-rm.sh <name>" >&2; exit 2 ;; esac
|
||||
main_dir="$(git worktree list --porcelain | awk '/^worktree /{print $2; exit}')"
|
||||
dest="$(dirname "$main_dir")/singstar-wt/$name"
|
||||
[ -d "$dest" ] || { echo "Kein Worktree: $dest" >&2; exit 1; }
|
||||
if [ -n "$(git -C "$dest" status --porcelain --untracked-files=no)" ]; then
|
||||
echo "Ungespeicherte Änderungen in $dest – bitte erst committen oder verwerfen." >&2; exit 1
|
||||
fi
|
||||
find "$dest" -type l -delete # nur die Verknüpfungen entfernen, nicht ihre Ziele
|
||||
git worktree remove "$dest"
|
||||
echo "Entfernt: $dest. Der Branch feat/$name bleibt; nach dem Merge: git branch -d feat/$name"
|
||||
Reference in New Issue
Block a user