Compare commits
5 Commits
6331e89274
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| dde1511c3d | |||
| 7d00ae45d8 | |||
| a7c81cee3e | |||
| 41c4ca8b22 | |||
| 914f9ecfef |
65
.gitea/workflows/release.yml
Normal file
65
.gitea/workflows/release.yml
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
# Baut das Arch-Paket (pacman) in einem Arch-Container und hängt es bei einem Versions-Tag als Release an.
|
||||||
|
# - Pull-Anfrage, die packaging/ ändert: Trockenlauf (Paket bauen und als Artefakt bereitstellen, kein Release)
|
||||||
|
# - Tag v* (z. B. v0.1.0): Paket bauen und Release mit dem Paket anlegen; Tags mit -test: nur als Entwurf (Probelauf)
|
||||||
|
# Der Runner (tools/ci-runner) braucht dafür nur Docker; der Arch-Container wird dort gezogen.
|
||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*']
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- 'packaging/**'
|
||||||
|
- '.gitea/workflows/release.yml'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
arch-package:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: archlinux:base-devel
|
||||||
|
steps:
|
||||||
|
# Node und git müssen im Container da sein, bevor actions/checkout läuft.
|
||||||
|
- name: Werkzeuge installieren
|
||||||
|
run: pacman -Syu --noconfirm --needed git nodejs rust alsa-lib
|
||||||
|
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# makepkg verweigert die Arbeit als root: eigener Benutzer.
|
||||||
|
- name: Paket bauen
|
||||||
|
run: |
|
||||||
|
useradd -m builder
|
||||||
|
chown -R builder:builder .
|
||||||
|
su builder -c 'cd packaging/arch && makepkg -f --nocheck --noconfirm'
|
||||||
|
ls -la packaging/arch/*.pkg.tar.zst
|
||||||
|
|
||||||
|
- uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: pacman-paket
|
||||||
|
path: packaging/arch/*.pkg.tar.zst
|
||||||
|
|
||||||
|
# Tags mit „-test“ erzeugen einen Entwurf (nur für Mitarbeitende sichtbar), andere Tags mit „-“ (v0.2.0-rc1) eine
|
||||||
|
# Vorabversion, reine Versionen (v0.1.0) ein normales, öffentliches Release.
|
||||||
|
- name: Release anlegen und Paket anhängen (nur bei Tags)
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
TAG: ${{ github.ref_name }}
|
||||||
|
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
pkg="$(ls packaging/arch/*.pkg.tar.zst | head -1)"
|
||||||
|
name="$(basename "$pkg")"
|
||||||
|
draft=false; prerelease=false
|
||||||
|
case "$TAG" in *-test*) draft=true ;; esac
|
||||||
|
case "$TAG" in *-*) prerelease=true ;; esac
|
||||||
|
body="Arch-Paket (pacman): sudo pacman -U $name"
|
||||||
|
resp="$(curl -fsS -X POST "$API/releases" -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||||
|
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":\"$body\",\"draft\":$draft,\"prerelease\":$prerelease}")"
|
||||||
|
id="$(printf '%s' "$resp" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)"
|
||||||
|
[ -n "$id" ] || { echo "Release-ID nicht gefunden: $resp" >&2; exit 1; }
|
||||||
|
curl -fsS -X POST "$API/releases/$id/assets?name=$name" -H "Authorization: token $TOKEN" \
|
||||||
|
-F "attachment=@$pkg" > /dev/null
|
||||||
|
# Selbstprüfung: das Paket muss im Release hängen (auch bei einem Entwurf, den man von außen nicht sieht).
|
||||||
|
check="$(curl -fsS "$API/releases/$id" -H "Authorization: token $TOKEN")"
|
||||||
|
printf '%s' "$check" | grep -q "\"name\":\"$name\"" || { echo "Paket fehlt im Release $TAG: $check" >&2; exit 1; }
|
||||||
|
echo "Release $TAG (Entwurf: $draft, Vorabversion: $prerelease): $name ist angehängt."
|
||||||
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
|
||||||
5
.gitignore
vendored
5
.gitignore
vendored
@ -28,3 +28,8 @@ tools/ci-runner/config.yaml
|
|||||||
|
|
||||||
# Audio des Beispielsongs (nach den allgemeinen *.mp3-Regeln, damit die Ausnahme gilt)
|
# Audio des Beispielsongs (nach den allgemeinen *.mp3-Regeln, damit die Ausnahme gilt)
|
||||||
!songs/take-it-slow/*.mp3
|
!songs/take-it-slow/*.mp3
|
||||||
|
|
||||||
|
# makepkg-Ausgaben
|
||||||
|
packaging/arch/src/
|
||||||
|
packaging/arch/pkg/
|
||||||
|
*.pkg.tar.zst
|
||||||
|
|||||||
13
README.md
13
README.md
@ -38,9 +38,18 @@ Der Code entstand mit starker Unterstützung durch KI: die App und die Werkzeuge
|
|||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
Es gibt keine fertigen Releases; die App wird aus dem Quelltext gebaut.
|
Für Arch Linux / CachyOS gibt es ein pacman-Paket; sonst wird die App aus dem Quelltext gebaut.
|
||||||
|
|
||||||
### Arch Linux / CachyOS
|
### Arch Linux / CachyOS: Paket
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd packaging/arch && makepkg -f # baut singtrainer-<Version>-1-x86_64.pkg.tar.zst (ein paar Minuten)
|
||||||
|
sudo pacman -U singtrainer-*.pkg.tar.zst
|
||||||
|
```
|
||||||
|
|
||||||
|
Das Paket installiert das Programm (`singtrainer`), einen Starter im Menü und die Beispiele (Testchart und der Song „Take It Slow“ unter `/usr/share/singtrainer/`). Ein fertig gebautes Paket hängt an den Releases des Repositories (`.gitea/workflows/release.yml`). Deinstallieren: `sudo pacman -R singtrainer`. Deine eigenen Songs liegen weiter unter `~/.local/share/singtrainer/`.
|
||||||
|
|
||||||
|
### Arch Linux / CachyOS: Abhängigkeiten zum Selbstbauen
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo pacman -S --needed rust alsa-lib pipewire pipewire-alsa pipewire-pulse pkgconf ffmpeg
|
sudo pacman -S --needed rust alsa-lib pipewire pipewire-alsa pipewire-pulse pkgconf ffmpeg
|
||||||
|
|||||||
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.
|
||||||
66
packaging/arch/PKGBUILD
Normal file
66
packaging/arch/PKGBUILD
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
# Maintainer: wlkns-dev <s.wilkens@gmx.net>
|
||||||
|
#
|
||||||
|
# Paket aus dem Checkout dieses Repositories (keine Quelldatei-Downloads):
|
||||||
|
# cd packaging/arch && makepkg -f # baut singtrainer-<Version>-1-x86_64.pkg.tar.zst
|
||||||
|
# sudo pacman -U singtrainer-*.pkg.tar.zst
|
||||||
|
# Die Version kommt aus Cargo.toml. Gebaut wird in $srcdir/target (sauber, dauert einige Minuten); mit
|
||||||
|
# `CARGO_TARGET_DIR=<Ordner> makepkg -f` lässt sich ein bestehendes target/ wiederverwenden.
|
||||||
|
|
||||||
|
pkgname=singtrainer
|
||||||
|
pkgver=0.1.0
|
||||||
|
pkgrel=1
|
||||||
|
pkgdesc='Desktop-App zum Singüben mit eigenen Songs: Tonhöhe live, Mitsingen mit Wertung, Akkorde, Stimmfinder'
|
||||||
|
arch=('x86_64')
|
||||||
|
url='https://git.wlkns.org/wlkns-dev/singalong'
|
||||||
|
license=('MIT')
|
||||||
|
depends=('alsa-lib' 'gcc-libs')
|
||||||
|
makedepends=('cargo')
|
||||||
|
optdepends=('ffmpeg: Musik und Original-Gesang beim Transponieren mitverschieben (Filter rubberband)'
|
||||||
|
'pipewire-alsa: Audio über PipeWire statt direkt über ALSA')
|
||||||
|
options=('!lto')
|
||||||
|
|
||||||
|
_repo="$(realpath "$startdir/../..")"
|
||||||
|
|
||||||
|
pkgver() {
|
||||||
|
grep -m1 '^version' "$_repo/Cargo.toml" | cut -d'"' -f2
|
||||||
|
}
|
||||||
|
|
||||||
|
prepare() {
|
||||||
|
cd "$_repo"
|
||||||
|
export RUSTUP_TOOLCHAIN=stable
|
||||||
|
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
|
||||||
|
}
|
||||||
|
|
||||||
|
build() {
|
||||||
|
cd "$_repo"
|
||||||
|
export RUSTUP_TOOLCHAIN=stable
|
||||||
|
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$srcdir/target}"
|
||||||
|
cargo build --frozen --release
|
||||||
|
}
|
||||||
|
|
||||||
|
check() {
|
||||||
|
cd "$_repo"
|
||||||
|
export RUSTUP_TOOLCHAIN=stable
|
||||||
|
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$srcdir/target}"
|
||||||
|
cargo test --frozen --release --bin singtrainer
|
||||||
|
}
|
||||||
|
|
||||||
|
package() {
|
||||||
|
cd "$_repo"
|
||||||
|
local target="${CARGO_TARGET_DIR:-$srcdir/target}"
|
||||||
|
install -Dm755 "$target/release/singtrainer" "$pkgdir/usr/bin/singtrainer"
|
||||||
|
install -Dm644 packaging/arch/singtrainer.desktop "$pkgdir/usr/share/applications/singtrainer.desktop"
|
||||||
|
|
||||||
|
# Beispiele: Testchart und der Beispielsong (Chart-Pfade sind relativ, ../songs/… trifft /usr/share/singtrainer/songs).
|
||||||
|
local share="$pkgdir/usr/share/singtrainer"
|
||||||
|
install -Dm644 charts/test.toml "$share/charts/test.toml"
|
||||||
|
install -Dm644 charts/take-it-slow.toml "$share/charts/take-it-slow.toml"
|
||||||
|
install -Dm644 songs/take-it-slow/vocals.mp3 "$share/songs/take-it-slow/vocals.mp3"
|
||||||
|
install -Dm644 songs/take-it-slow/backing.mp3 "$share/songs/take-it-slow/backing.mp3"
|
||||||
|
install -Dm644 songs/take-it-slow/lyrics.txt "$share/songs/take-it-slow/lyrics.txt"
|
||||||
|
install -Dm644 songs/take-it-slow/LIZENZ.md "$share/songs/take-it-slow/LIZENZ.md"
|
||||||
|
|
||||||
|
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||||
|
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||||
|
install -Dm644 docs/handbuch.md "$pkgdir/usr/share/doc/$pkgname/handbuch.md"
|
||||||
|
}
|
||||||
10
packaging/arch/singtrainer.desktop
Normal file
10
packaging/arch/singtrainer.desktop
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Singtrainer
|
||||||
|
GenericName=Gesangstrainer
|
||||||
|
Comment=Singen üben: Tonhöhe live, Mitsingen mit Wertung, Akkorde und Stimmfinder
|
||||||
|
Exec=singtrainer
|
||||||
|
Icon=audio-input-microphone
|
||||||
|
Terminal=false
|
||||||
|
Categories=AudioVideo;Audio;Music;
|
||||||
|
Keywords=Singen;Gesang;Karaoke;Tonhöhe;Stimme;
|
||||||
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}
|
||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::path::PathBuf;
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@ -499,6 +499,14 @@ impl Default for VoiceConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
|
/// Ordner mit den mitgelieferten Beispielen einer Installation (`charts/`, `songs/`): `/usr/share/singtrainer`,
|
||||||
|
/// überschreibbar mit `SINGTRAINER_SHARE_DIR` (für Tests und zum Ausprobieren eines Pakets ohne Installation).
|
||||||
|
pub fn share_dir() -> PathBuf {
|
||||||
|
std::env::var_os("SINGTRAINER_SHARE_DIR")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| PathBuf::from("/usr/share/singtrainer"))
|
||||||
|
}
|
||||||
|
|
||||||
/// Datenverzeichnis (Sessions, Aufnahmen): `$XDG_DATA_HOME/singtrainer` bzw. `~/.local/share/singtrainer`.
|
/// Datenverzeichnis (Sessions, Aufnahmen): `$XDG_DATA_HOME/singtrainer` bzw. `~/.local/share/singtrainer`.
|
||||||
pub fn data_dir() -> PathBuf {
|
pub fn data_dir() -> PathBuf {
|
||||||
let base = std::env::var_os("XDG_DATA_HOME")
|
let base = std::env::var_os("XDG_DATA_HOME")
|
||||||
@ -555,3 +563,61 @@ mod tests {
|
|||||||
assert_eq!(c.audio.tone_gain, 0.2);
|
assert_eq!(c.audio.tone_gain, 0.2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Chart, das beim Start geladen wird: der eingestellte Pfad, solange es ihn gibt. Fehlt der Standardpfad
|
||||||
|
/// (`charts/test.toml`, etwa weil die App aus einem anderen Ordner gestartet oder installiert wurde), dient der
|
||||||
|
/// mitgelieferte Beispielsong aus `share`, falls vorhanden. Ein ausdrücklich eingestellter anderer Pfad bleibt unberührt.
|
||||||
|
pub fn startup_chart(configured: &str, share: &Path) -> String {
|
||||||
|
const DEFAULT: &str = "charts/test.toml";
|
||||||
|
if configured != DEFAULT || Path::new(configured).exists() {
|
||||||
|
return configured.to_string();
|
||||||
|
}
|
||||||
|
let example = share.join("charts").join("take-it-slow.toml");
|
||||||
|
if example.is_file() {
|
||||||
|
example.display().to_string()
|
||||||
|
} else {
|
||||||
|
configured.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod startup_chart_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn tmp(tag: &str) -> PathBuf {
|
||||||
|
let d = std::env::temp_dir().join(format!("startchart-{tag}-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&d);
|
||||||
|
std::fs::create_dir_all(d.join("charts")).unwrap();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_default_falls_back_to_the_installed_example_but_nothing_else_changes() {
|
||||||
|
let share = tmp("share");
|
||||||
|
// Kein Beispiel installiert: unverändert.
|
||||||
|
assert_eq!(
|
||||||
|
startup_chart("charts/test.toml", &share),
|
||||||
|
"charts/test.toml"
|
||||||
|
);
|
||||||
|
std::fs::write(share.join("charts/take-it-slow.toml"), "title=\"x\"").unwrap();
|
||||||
|
// Standardpfad existiert nicht (Test läuft im Paketordner, nicht im Repo): Beispiel aus share.
|
||||||
|
let cwd = tmp("cwd");
|
||||||
|
let prev = std::env::current_dir().unwrap();
|
||||||
|
std::env::set_current_dir(&cwd).unwrap();
|
||||||
|
let got = startup_chart("charts/test.toml", &share);
|
||||||
|
// Ausdrücklich gewählter Pfad bleibt, auch wenn er fehlt.
|
||||||
|
let custom = startup_chart("mein/lied.toml", &share);
|
||||||
|
// Existiert der Standardpfad, bleibt er.
|
||||||
|
std::fs::write(cwd.join("charts/test.toml"), "title=\"t\"").unwrap();
|
||||||
|
let kept = startup_chart("charts/test.toml", &share);
|
||||||
|
std::env::set_current_dir(prev).unwrap();
|
||||||
|
assert!(
|
||||||
|
got.ends_with("charts/take-it-slow.toml") && got.starts_with(share.to_str().unwrap()),
|
||||||
|
"{got}"
|
||||||
|
);
|
||||||
|
assert_eq!(custom, "mein/lied.toml");
|
||||||
|
assert_eq!(kept, "charts/test.toml");
|
||||||
|
let _ = std::fs::remove_dir_all(share);
|
||||||
|
let _ = std::fs::remove_dir_all(cwd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -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 anyhow::{Context, Result, bail};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@ -10,8 +10,12 @@ use std::path::{Path, PathBuf};
|
|||||||
pub struct Meta {
|
pub struct Meta {
|
||||||
pub title: String,
|
pub title: String,
|
||||||
pub bpm: Option<f64>,
|
pub bpm: Option<f64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub bpm_source: Option<String>,
|
||||||
pub key: Option<String>,
|
pub key: Option<String>,
|
||||||
pub duration: f64,
|
pub duration: f64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub source_offset_s: Option<f64>,
|
||||||
pub schema_version: u32,
|
pub schema_version: u32,
|
||||||
pub errors: BTreeMap<String, String>,
|
pub errors: BTreeMap<String, String>,
|
||||||
}
|
}
|
||||||
@ -52,8 +56,14 @@ pub struct Word {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Line {
|
pub struct Line {
|
||||||
pub start: f64,
|
pub start: Option<f64>,
|
||||||
pub end: 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>,
|
pub words: Vec<Word>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,12 +111,18 @@ pub fn load_analysis(dir: &Path) -> Result<Analysis> {
|
|||||||
let meta: Meta = serde_json::from_slice(
|
let meta: Meta = serde_json::from_slice(
|
||||||
&std::fs::read(&path).with_context(|| format!("{} lesen", path.display()))?,
|
&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!(
|
bail!(
|
||||||
"Unbekannte song-analysis schema_version {}",
|
"Unbekannte song-analysis schema_version {}",
|
||||||
meta.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")?;
|
let pitch: Option<Pitch> = read_optional(dir, "pitch.json")?;
|
||||||
if pitch
|
if pitch
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|||||||
@ -87,6 +87,9 @@ pub fn list_charts(dirs: &[std::path::PathBuf]) -> Vec<ChartEntry> {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
// Gleicher Titel in mehreren Ordnern (z. B. Entwicklungsordner und Installation): die frühere Fundstelle gewinnt.
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
out.retain(|e| seen.insert(e.title.to_lowercase()));
|
||||||
out.sort_by_key(|e| e.title.to_lowercase());
|
out.sort_by_key(|e| e.title.to_lowercase());
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
@ -1215,6 +1218,7 @@ impl App {
|
|||||||
self.charts = list_charts(&[
|
self.charts = list_charts(&[
|
||||||
std::path::PathBuf::from("charts"),
|
std::path::PathBuf::from("charts"),
|
||||||
Config::data_dir().join("charts"),
|
Config::data_dir().join("charts"),
|
||||||
|
Config::share_dir().join("charts"),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2324,6 +2328,24 @@ mod tests {
|
|||||||
["Anton", "zebra Lied"]
|
["Anton", "zebra Lied"]
|
||||||
);
|
);
|
||||||
assert!(list[0].path.ends_with("a.toml"));
|
assert!(list[0].path.ends_with("a.toml"));
|
||||||
|
// Derselbe Titel in zwei Ordnern (Entwicklungsordner und Installation) erscheint nur einmal, die frühere
|
||||||
|
// Fundstelle gewinnt.
|
||||||
|
let other = dir.join("zweiter");
|
||||||
|
std::fs::create_dir_all(&other).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
other.join("anton-kopie.toml"),
|
||||||
|
format!("title=\"anton\"\n{note}"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let twice = list_charts(&[dir.clone(), other.clone()]);
|
||||||
|
assert_eq!(
|
||||||
|
twice
|
||||||
|
.iter()
|
||||||
|
.filter(|e| e.title.eq_ignore_ascii_case("anton"))
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert!(twice[0].path.ends_with("a.toml"), "{:?}", twice[0].path);
|
||||||
// Die mitgelieferten Songs erscheinen in der Auswahl.
|
// Die mitgelieferten Songs erscheinen in der Auswahl.
|
||||||
let repo =
|
let repo =
|
||||||
list_charts(&[std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("charts")]);
|
list_charts(&[std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("charts")]);
|
||||||
|
|||||||
@ -167,6 +167,9 @@ impl App {
|
|||||||
let mut config = Config::load();
|
let mut config = Config::load();
|
||||||
if let Some(p) = &chart_arg {
|
if let Some(p) = &chart_arg {
|
||||||
config.session.chart_path = p.clone();
|
config.session.chart_path = p.clone();
|
||||||
|
} else {
|
||||||
|
config.session.chart_path =
|
||||||
|
crate::config::startup_chart(&config.session.chart_path, &Config::share_dir());
|
||||||
}
|
}
|
||||||
let chart_result = NoteChart::load(Path::new(&config.session.chart_path));
|
let chart_result = NoteChart::load(Path::new(&config.session.chart_path));
|
||||||
let chart_error = chart_result.as_ref().err().map(|e| format!("{e:#}"));
|
let chart_error = chart_result.as_ref().err().map(|e| format!("{e:#}"));
|
||||||
|
|||||||
@ -21,7 +21,28 @@ fn reads_optional_outputs_from_one_folder() {
|
|||||||
fn rejects_unknown_schema_version() {
|
fn rejects_unknown_schema_version() {
|
||||||
let dir = std::env::temp_dir().join(format!("song-analysis-version-{}", std::process::id()));
|
let dir = std::env::temp_dir().join(format!("song-analysis-version-{}", std::process::id()));
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
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());
|
assert!(load_analysis(&dir).is_err());
|
||||||
std::fs::remove_dir_all(dir).unwrap();
|
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):
|
Aufruf (mit dieser Umgebung):
|
||||||
|
|
||||||
```bash
|
```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
|
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
|
## 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.
|
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`.
|
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.
|
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 json
|
||||||
import os
|
import os
|
||||||
import statistics
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
from pathlib import Path
|
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:
|
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)
|
positions = DBNDownBeatTrackingProcessor(beats_per_bar=[3, 4], fps=100)(activations)
|
||||||
beats = [float(row[0]) for row in positions]
|
beats = [float(row[0]) for row in positions]
|
||||||
downbeats = [float(row[0]) for row in positions if int(row[1]) == 1]
|
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 = bpm_from_beats(beats)
|
||||||
bpm = round(60 / statistics.median(gaps), 2) if gaps else None
|
|
||||||
return {"beats": beats, "downbeats": downbeats}, bpm
|
return {"beats": beats, "downbeats": downbeats}, bpm
|
||||||
|
|
||||||
|
|
||||||
@ -138,8 +136,7 @@ def transcribe_midi(audio: Path, target: Path) -> None:
|
|||||||
staged.replace(target)
|
staged.replace(target)
|
||||||
|
|
||||||
|
|
||||||
def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
def lyrics_words(audio: Path, language: str, model_name: str) -> list[dict]:
|
||||||
model_name: str) -> tuple[list[dict], bool]:
|
|
||||||
import torch
|
import torch
|
||||||
import whisperx
|
import whisperx
|
||||||
|
|
||||||
@ -148,20 +145,11 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
|||||||
last_error = None
|
last_error = None
|
||||||
for device in devices:
|
for device in devices:
|
||||||
try:
|
try:
|
||||||
if lyrics:
|
model = whisperx.load_model(model_name, device, compute_type="float16" if device == "cuda" else "int8")
|
||||||
text = " ".join(line.strip() for line in lyrics.read_text(encoding="utf-8").splitlines()
|
result = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2,
|
||||||
if line.strip() and not line.lstrip().startswith(("#", "[")))
|
language=language)
|
||||||
if not text:
|
segments = result["segments"]
|
||||||
raise ValueError("Liedtext enthält keine Wörter")
|
del model
|
||||||
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
|
|
||||||
aligner, metadata = whisperx.load_align_model(language_code=language, device=device)
|
aligner, metadata = whisperx.load_align_model(language_code=language, device=device)
|
||||||
aligned = whisperx.align(segments, aligner, metadata, audio_data, device,
|
aligned = whisperx.align(segments, aligner, metadata, audio_data, device,
|
||||||
return_char_alignments=False)
|
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})
|
"conf": float(item["score"]) if item.get("score") is not None else None})
|
||||||
if not words:
|
if not words:
|
||||||
raise RuntimeError("WhisperX lieferte keine ausgerichteten Wörter")
|
raise RuntimeError("WhisperX lieferte keine ausgerichteten Wörter")
|
||||||
return words, verified
|
return words
|
||||||
except (RuntimeError, MemoryError) as exc:
|
except (RuntimeError, MemoryError) as exc:
|
||||||
last_error = exc
|
last_error = exc
|
||||||
if device == "cuda":
|
if device == "cuda":
|
||||||
@ -182,3 +170,40 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
|||||||
continue
|
continue
|
||||||
raise
|
raise
|
||||||
raise RuntimeError(f"WhisperX fehlgeschlagen: {last_error}")
|
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 pathlib import Path
|
||||||
|
|
||||||
from . import backends
|
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:
|
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,
|
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,
|
separator_bin: str = "audio-separator", model_dir: Path | None = None,
|
||||||
roformer_model: str = "model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
roformer_model: str = "model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
||||||
language: str = "en", whisper_model: str = "large-v3") -> dict:
|
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)
|
lambda: backends.transcribe_midi(vocals, out / "melody.mid"), errors, force)
|
||||||
lyrics_path = out / "lyrics.json"
|
lyrics_path = out / "lyrics.json"
|
||||||
def lyrics_step():
|
def lyrics_step():
|
||||||
words, verified = backends.lyrics_words(vocals, lyrics, language, whisper_model)
|
if lyrics:
|
||||||
downbeats = []
|
value = {"verified": True,
|
||||||
if (out / "beats.json").exists():
|
"lines": backends.align_lyric_lines(vocals, lyrics, language, whisper_model)}
|
||||||
try:
|
else:
|
||||||
downbeats = json.loads((out / "beats.json").read_text(encoding="utf-8"))["downbeats"]
|
words = backends.lyrics_words(vocals, language, whisper_model)
|
||||||
except (OSError, ValueError, KeyError):
|
downbeats = []
|
||||||
pass
|
if (out / "beats.json").exists():
|
||||||
value = {"verified": verified, "lines": group_words(words, downbeats)}
|
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)
|
validate_json("lyrics", value)
|
||||||
write_json(lyrics_path, value)
|
write_json(lyrics_path, value)
|
||||||
run_step("lyrics", [lyrics_path], lyrics_step, errors, force)
|
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"),
|
lambda: backends.transcribe_midi(stems / "other.wav", out / "guitar.mid"),
|
||||||
errors, force)
|
errors, force)
|
||||||
|
|
||||||
bpm = previous.get("bpm")
|
bpm = None
|
||||||
if (out / "beats.json").exists():
|
if (out / "beats.json").exists():
|
||||||
try:
|
try:
|
||||||
beat_times = json.loads((out / "beats.json").read_text(encoding="utf-8"))["beats"]
|
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]
|
bpm = bpm_from_beats(beat_times)
|
||||||
if gaps:
|
|
||||||
import statistics
|
|
||||||
bpm = round(60 / statistics.median(gaps), 2)
|
|
||||||
except (OSError, ValueError, KeyError, TypeError):
|
except (OSError, ValueError, KeyError, TypeError):
|
||||||
pass
|
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"]
|
bpm = previous["bpm"]
|
||||||
|
elif force:
|
||||||
|
bpm_source = "automatic"
|
||||||
validate_outputs(out, errors)
|
validate_outputs(out, errors)
|
||||||
key = previous.get("key")
|
key = previous.get("key")
|
||||||
if mix.exists() and (force or key is None):
|
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)
|
key = backends.detect_key(mix)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
errors["key"] = f"{type(exc).__name__}: {exc}"
|
errors["key"] = f"{type(exc).__name__}: {exc}"
|
||||||
meta = {"title": previous.get("title", source.stem) if not force else source.stem,
|
meta = {"title": title if title is not None else (previous.get("title", source.stem) if not force else source.stem),
|
||||||
"bpm": bpm, "key": key,
|
"bpm": bpm, "bpm_source": bpm_source, "key": key,
|
||||||
"duration": previous.get("duration", duration) if not force and previous.get("duration", 0) > 0 else duration,
|
"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:
|
try:
|
||||||
validate_json("meta", meta)
|
validate_json("meta", meta)
|
||||||
except Exception as exc:
|
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("audio", type=Path)
|
||||||
parser.add_argument("--out", required=True, type=Path)
|
parser.add_argument("--out", required=True, type=Path)
|
||||||
parser.add_argument("--lyrics", type=Path)
|
parser.add_argument("--lyrics", type=Path)
|
||||||
|
parser.add_argument("--title")
|
||||||
parser.add_argument("--force", action="store_true")
|
parser.add_argument("--force", action="store_true")
|
||||||
parser.add_argument("--separator-bin", default="audio-separator")
|
parser.add_argument("--separator-bin", default="audio-separator")
|
||||||
parser.add_argument("--model-dir", type=Path)
|
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")
|
parser.add_argument("--whisper-model", default="large-v3")
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
try:
|
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,
|
separator_bin=args.separator_bin, model_dir=args.model_dir,
|
||||||
roformer_model=args.roformer_model, language=args.language,
|
roformer_model=args.roformer_model, language=args.language,
|
||||||
whisper_model=args.whisper_model)
|
whisper_model=args.whisper_model)
|
||||||
|
|||||||
@ -2,9 +2,16 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
import statistics
|
||||||
|
from difflib import SequenceMatcher
|
||||||
from pathlib import Path
|
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:
|
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
|
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*$')
|
_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")
|
raise ValueError("beats: Zeiten sind nicht sortiert")
|
||||||
if kind in ("chords", "lyrics"):
|
if kind in ("chords", "lyrics"):
|
||||||
spans = value if kind == "chords" else value["lines"]
|
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")
|
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:
|
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
|
patchelf>=0.19.1 # Repariert bei Bedarf das GNU_STACK-Flag von CTranslate2 4.4
|
||||||
scipy>=1.10
|
scipy>=1.10
|
||||||
soundfile>=0.12
|
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
|
torchcrepe>=0.0.24
|
||||||
basic-pitch>=0.4
|
basic-pitch>=0.4
|
||||||
whisperx>=3.3
|
whisperx>=3.3
|
||||||
|
|||||||
@ -5,9 +5,9 @@ import unittest
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
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.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):
|
class SongAnalysisTests(unittest.TestCase):
|
||||||
@ -23,6 +23,37 @@ class SongAnalysisTests(unittest.TestCase):
|
|||||||
[["Hello", "there"], ["again"], ["friend"]])
|
[["Hello", "there"], ["again"], ["friend"]])
|
||||||
self.assertEqual(lines[0]["start"], 0.1)
|
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):
|
def test_chordino_events_end_at_next_event_or_duration(self):
|
||||||
text = '0.000000: "C"\n1.250000: "Am"\n2.000000: "N"\n'
|
text = '0.000000: "C"\n1.250000: "Am"\n2.000000: "N"\n'
|
||||||
self.assertEqual(parse_chordino(text, 3.0), [
|
self.assertEqual(parse_chordino(text, 3.0), [
|
||||||
@ -62,23 +93,15 @@ class SongAnalysisTests(unittest.TestCase):
|
|||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
validate_json("pitch", {"hop_ms": 10, "hz": [440, 441], "conf": [0.9]})
|
validate_json("pitch", {"hop_ms": 10, "hz": [440, 441], "conf": [0.9]})
|
||||||
|
|
||||||
def test_pitch_inference_limits_batch_size(self):
|
def test_lyric_line_cannot_have_one_missing_boundary(self):
|
||||||
import numpy as np
|
with self.assertRaises(ValueError):
|
||||||
import soundfile as sf
|
validate_json("lyrics", {"verified": True, "lines": [
|
||||||
import torch
|
{"start": None, "end": 1.0, "words": []}
|
||||||
|
]})
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as d:
|
def test_bpm_from_beats_uses_median_of_plausible_intervals(self):
|
||||||
audio = Path(d) / "vocals.wav"
|
self.assertEqual(bpm_from_beats([0, 0.5, 1.0, 10.0]), 120.0)
|
||||||
sf.write(audio, np.zeros(16000, dtype=np.float32), 16000)
|
self.assertIsNone(bpm_from_beats([]))
|
||||||
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_madmom_decoder_receives_its_100_hz_frame_rate(self):
|
def test_madmom_decoder_receives_its_100_hz_frame_rate(self):
|
||||||
module = types.ModuleType("madmom_infer.features.downbeats")
|
module = types.ModuleType("madmom_infer.features.downbeats")
|
||||||
@ -125,12 +148,34 @@ class SongAnalysisTests(unittest.TestCase):
|
|||||||
analyze(source, out)
|
analyze(source, out)
|
||||||
meta_path = out / "meta.json"
|
meta_path = out / "meta.json"
|
||||||
meta = json.loads(meta_path.read_text())
|
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))
|
meta_path.write_text(json.dumps(meta))
|
||||||
result = analyze(source, out)
|
result = analyze(source, out)
|
||||||
self.assertEqual((result["title"], result["bpm"], result["key"], result["duration"]),
|
self.assertEqual((result["title"], result["bpm"], result["key"], result["duration"]),
|
||||||
("Mein Titel", 97.0, "G major", 2.9))
|
("Mein Titel", 97.0, "G major", 2.9))
|
||||||
self.assertIn("separator fehlt", result["errors"]["vocals"])
|
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__":
|
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()
|
||||||
Reference in New Issue
Block a user