Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
"""音符切分测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.audio import preprocess
|
||||
from qbh.melody import Melody
|
||||
from qbh.notes import segment_notes, smooth_midi
|
||||
from qbh.pitch import extract_pitch
|
||||
from qbh.synth import render_melody
|
||||
|
||||
|
||||
def _melody(midis, note_s=0.5) -> Melody:
|
||||
midis = np.asarray(midis, dtype=float)
|
||||
return Melody(midis, np.arange(midis.size) * note_s, np.full(midis.size, note_s * 0.9))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("timbre", ["song", "hum"])
|
||||
def test_segment_recovers_scale(timbre):
|
||||
truth = _melody([60, 62, 64, 67, 69, 67, 64, 60])
|
||||
audio = render_melody(truth, 16000, timbre=timbre, seed=3)
|
||||
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||
got = segment_notes(track)
|
||||
|
||||
assert got.n_notes == truth.n_notes
|
||||
# 音高逐音对齐(允许 0.3 半音误差)
|
||||
assert np.max(np.abs(got.midis - truth.midis)) < 0.3
|
||||
|
||||
|
||||
def test_segment_fuses_repeated_notes():
|
||||
truth = _melody([60, 60, 60, 62, 64])
|
||||
audio = render_melody(truth, 16000, timbre="hum", seed=5)
|
||||
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||
got = segment_notes(track)
|
||||
# 三个连续同音会被融合成一个(时长累加)
|
||||
assert got.n_notes == 3
|
||||
assert got.midis[0] == pytest.approx(60.0, abs=0.3)
|
||||
assert got.durs[0] > truth.durs[0] * 1.5
|
||||
|
||||
|
||||
def test_segment_empty_audio():
|
||||
track = extract_pitch(np.zeros(16000, dtype=np.float32), 16000)
|
||||
got = segment_notes(track)
|
||||
assert got.is_empty
|
||||
|
||||
|
||||
def test_segment_drops_very_short_notes():
|
||||
truth = _melody([60, 62, 64, 65, 67])
|
||||
truth.durs[2] = 0.02 # 20ms,低于 min_note_ms
|
||||
audio = render_melody(truth, 16000, timbre="song", seed=11)
|
||||
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||
got = segment_notes(track)
|
||||
assert got.n_notes < truth.n_notes
|
||||
|
||||
|
||||
def test_smooth_midi_keeps_nan():
|
||||
values = np.array([60.0, np.nan, 62.0, np.nan, 64.0])
|
||||
out = smooth_midi(values, 3)
|
||||
assert np.isnan(out[1]) and np.isnan(out[3])
|
||||
assert not np.isnan(out[0]) and not np.isnan(out[4])
|
||||
|
||||
|
||||
def test_segment_onset_is_monotonic():
|
||||
truth = _melody([60, 64, 67, 72, 67, 64], note_s=0.6)
|
||||
audio = render_melody(truth, 16000, timbre="hum", seed=13)
|
||||
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||
got = segment_notes(track)
|
||||
assert np.all(np.diff(got.starts) > 0)
|
||||
assert got.starts[0] == pytest.approx(0.0, abs=1e-6)
|
||||
Reference in New Issue
Block a user