feat: version song analysis contract and preserve lyric lines
All checks were successful
song-analysis-contract / python-contract (push) Successful in 46s
CI / rust (pull_request) Successful in 2m41s
song-analysis-contract / python-contract (pull_request) Successful in 5s

This commit is contained in:
2026-11-01 11:24:21 +01:00
parent cd72278c88
commit 914f9ecfef
17 changed files with 401 additions and 74 deletions

View File

@ -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__":