forked from wlkns-dev/stimmwerk
- tools/analyze + tools/song_analysis: Trennung in Stems, Takte, Akkorde, Tonhöhe und Text mit Wortzeiten (eigene Python-3.11-Umgebung, README, Tests) - schemas/song-analysis-v1: JSON-Schemas der Ausgabe - src/lib.rs, src/song_analysis.rs: liest die Ausgabe (Version 1); Integrationstest in tests/ - .gitignore: Umgebung, Modelle und Zwischenspeicher des Werkzeugs Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
138 lines
6.7 KiB
Python
138 lines
6.7 KiB
Python
import json
|
|
import tempfile
|
|
import types
|
|
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.cli import analyze, resolve_separator_bin
|
|
from song_analysis.backends import detect_beats, detect_pitch
|
|
|
|
|
|
class SongAnalysisTests(unittest.TestCase):
|
|
def test_lines_split_at_pause_downbeat_and_length(self):
|
|
words = [
|
|
{"w": "Hello", "start": 0.1, "end": 0.3, "conf": 0.9},
|
|
{"w": "there", "start": 0.4, "end": 0.6, "conf": 0.8},
|
|
{"w": "again", "start": 1.4, "end": 1.7, "conf": 0.7},
|
|
{"w": "friend", "start": 2.1, "end": 2.4, "conf": 0.6},
|
|
]
|
|
lines = group_words(words, [2.0], max_chars=40)
|
|
self.assertEqual([[w["w"] for w in line["words"]] for line in lines],
|
|
[["Hello", "there"], ["again"], ["friend"]])
|
|
self.assertEqual(lines[0]["start"], 0.1)
|
|
|
|
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), [
|
|
{"chord": "C", "start": 0.0, "end": 1.25, "conf": None},
|
|
{"chord": "Am", "start": 1.25, "end": 2.0, "conf": None},
|
|
{"chord": "N", "start": 2.0, "end": 3.0, "conf": None},
|
|
])
|
|
|
|
def test_cached_step_preserves_manual_edit_and_force_replaces_it(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
path = Path(d) / "beats.json"
|
|
path.write_text('{"manual":true}')
|
|
calls = []
|
|
errors = {}
|
|
def produce():
|
|
calls.append(1)
|
|
path.write_text('{"beats":[],"downbeats":[]}')
|
|
run_step("beats", [path], produce, errors, force=False)
|
|
self.assertEqual(calls, [])
|
|
self.assertEqual(json.loads(path.read_text()), {"manual": True})
|
|
run_step("beats", [path], produce, errors, force=True)
|
|
self.assertEqual(len(calls), 1)
|
|
self.assertEqual(json.loads(path.read_text())["beats"], [])
|
|
|
|
def test_failed_step_records_error_without_blocking_next_step(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
out = Path(d)
|
|
errors = {}
|
|
def fail():
|
|
raise RuntimeError("model unavailable")
|
|
run_step("stems", [out / "vocals.wav"], fail, errors, force=False)
|
|
run_step("beats", [out / "beats.json"], lambda: (out / "beats.json").write_text("{}"), errors, force=False)
|
|
self.assertIn("model unavailable", errors["stems"])
|
|
self.assertTrue((out / "beats.json").exists())
|
|
|
|
def test_schema_rejects_invalid_pitch_lengths(self):
|
|
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
|
|
|
|
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_madmom_decoder_receives_its_100_hz_frame_rate(self):
|
|
module = types.ModuleType("madmom_infer.features.downbeats")
|
|
class Activations:
|
|
def __call__(self, _):
|
|
return "activations"
|
|
class Decoder:
|
|
def __init__(self, *, beats_per_bar, fps=None):
|
|
if fps != 100:
|
|
raise TypeError("fps required")
|
|
def __call__(self, _):
|
|
return [(0.0, 1), (0.5, 2), (1.0, 3)]
|
|
module.RNNDownBeatProcessor = Activations
|
|
module.DBNDownBeatTrackingProcessor = Decoder
|
|
with patch.dict("sys.modules", {"madmom_infer": types.ModuleType("madmom_infer"),
|
|
"madmom_infer.features": types.ModuleType("madmom_infer.features"),
|
|
"madmom_infer.features.downbeats": module}):
|
|
result, bpm = detect_beats(Path("unused.wav"))
|
|
self.assertEqual(result, {"beats": [0.0, 0.5, 1.0], "downbeats": [0.0]})
|
|
self.assertEqual(bpm, 120.0)
|
|
|
|
def test_default_separator_comes_from_current_python_environment(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
exe = Path(d) / "audio-separator"
|
|
exe.write_text("#!/bin/sh\n")
|
|
with patch("song_analysis.cli.sys.executable", str(Path(d) / "python")):
|
|
self.assertEqual(resolve_separator_bin("audio-separator"), str(exe))
|
|
self.assertEqual(resolve_separator_bin("/custom/sep"), "/custom/sep")
|
|
|
|
def test_meta_keeps_manual_values_while_updating_errors(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
source = Path(d) / "song.wav"
|
|
source.write_bytes(b"audio")
|
|
out = Path(d) / "out"
|
|
def fake_normalize(_, target):
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
target.write_bytes(b"wav")
|
|
with patch("song_analysis.backends.normalize", side_effect=fake_normalize), \
|
|
patch("song_analysis.backends.duration_of", return_value=3.0), \
|
|
patch("song_analysis.backends.separate", side_effect=RuntimeError("separator fehlt")), \
|
|
patch("song_analysis.backends.detect_beats", side_effect=RuntimeError("beats fehlen")), \
|
|
patch("song_analysis.backends.detect_chords", side_effect=RuntimeError("chords fehlen")), \
|
|
patch("song_analysis.backends.detect_key", side_effect=RuntimeError("key fehlt")):
|
|
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_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"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|