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, 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 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_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), [ {"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_lyric_line_cannot_have_one_missing_boundary(self): with self.assertRaises(ValueError): validate_json("lyrics", {"verified": True, "lines": [ {"start": None, "end": 1.0, "words": []} ]}) 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") 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, 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__": unittest.main()