Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
"""pytest 公共夹具。
|
||||
|
||||
测试尽量不依赖磁盘上的真实曲库:多数用例用合成的小旋律,只有 API 端到端
|
||||
测试才会构建一个临时曲库(并跳过音频渲染以加速)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from qbh.config import DEFAULT, Config # noqa: E402
|
||||
from qbh.melody import Melody # noqa: E402
|
||||
from qbh.synth import render_melody # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def cfg() -> Config:
|
||||
return DEFAULT
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def c_major_melody() -> Melody:
|
||||
"""C 大调音阶上的一段旋律(8 个音)。"""
|
||||
midis = [60, 62, 64, 67, 69, 67, 64, 62]
|
||||
starts = np.arange(8) * 0.5
|
||||
durs = np.full(8, 0.45)
|
||||
return Melody(np.array(midis, float), starts, durs, "scale", "C大调音阶")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def long_melody() -> Melody:
|
||||
"""20 个音的旋律,用于片段/子序列相关测试。"""
|
||||
midis = [60, 62, 64, 65, 67, 69, 71, 72, 71, 69, 67, 65, 64, 62, 60, 62, 64, 67, 69, 72]
|
||||
starts = np.arange(20) * 0.5
|
||||
durs = np.full(20, 0.45)
|
||||
return Melody(np.array(midis, float), starts, durs, "long", "长旋律")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tiny_library(cfg: Config):
|
||||
"""三条合成旋律构成的极简曲库(内存 SQLite)。"""
|
||||
from qbh.library import Library
|
||||
from qbh.store import Store
|
||||
|
||||
store = Store(":memory:")
|
||||
library = Library(store, cfg, midi_dir=Path("__nonexistent__"), audio_dir=Path("__nonexistent__"))
|
||||
melodies = [
|
||||
Melody(np.array([60, 62, 64, 67, 69, 67, 64, 62], float),
|
||||
np.arange(8) * 0.5, np.full(8, 0.45), "m_a", "旋律A"),
|
||||
Melody(np.array([72, 71, 69, 67, 65, 64, 62, 60], float),
|
||||
np.arange(8) * 0.5, np.full(8, 0.45), "m_b", "旋律B"),
|
||||
Melody(np.array([60, 60, 67, 67, 69, 69, 67], float),
|
||||
np.arange(7) * 0.5, np.full(7, 0.45), "m_c", "旋律C"),
|
||||
]
|
||||
for melody in melodies:
|
||||
library.add_melody(melody, song_id=melody.song_id, title=melody.title,
|
||||
source="test", render_audio=False)
|
||||
yield library
|
||||
store.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hum_audio(c_major_melody, cfg):
|
||||
"""把 C 大调旋律渲染成「哼唱」音频。"""
|
||||
return render_melody(c_major_melody, cfg.sample_rate, timbre="hum", seed=7)
|
||||
@@ -0,0 +1,177 @@
|
||||
"""FastAPI 接口测试(使用临时曲库,跳过音频渲染以加速)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
_TMP_DIR = Path(tempfile.mkdtemp(prefix="qbh_api_test_"))
|
||||
os.environ["QBH_DB"] = str(_TMP_DIR / "test.db")
|
||||
os.environ["QBH_AUDIO_DIR"] = str(_TMP_DIR / "audio")
|
||||
os.environ["QBH_SKIP_AUDIO"] = "1"
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from app.main import app # noqa: E402
|
||||
from qbh.audio import encode_wav_bytes # noqa: E402
|
||||
from qbh.synth import render_melody # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def query_wav(client):
|
||||
"""用后端自己的曲库造一条可检索的查询音频。"""
|
||||
from app.main import state
|
||||
|
||||
melody = state.library.melodies()[0]
|
||||
audio = render_melody(melody.transpose(3), 16000, timbre="hum", seed=31)
|
||||
return encode_wav_bytes(audio, 16000), melody.song_id
|
||||
|
||||
|
||||
def test_status(client):
|
||||
data = client.get("/api/status").json()
|
||||
assert data["n_songs"] > 0
|
||||
assert data["n_grams"] > 0
|
||||
assert "config" in data
|
||||
|
||||
|
||||
def test_songs_list(client):
|
||||
data = client.get("/api/songs").json()
|
||||
assert len(data["songs"]) > 0
|
||||
song = data["songs"][0]
|
||||
for key in ("id", "title", "n_notes", "source", "tags"):
|
||||
assert key in song
|
||||
|
||||
|
||||
def test_song_detail(client):
|
||||
song_id = client.get("/api/songs").json()["songs"][0]["id"]
|
||||
data = client.get(f"/api/songs/{song_id}").json()
|
||||
assert data["song"]["id"] == song_id
|
||||
assert data["melody"]["midis"]
|
||||
assert data["contour"] == data["melody"]["contour"] if "contour" in data["melody"] else True
|
||||
|
||||
|
||||
def test_song_detail_404(client):
|
||||
assert client.get("/api/songs/does-not-exist").status_code == 404
|
||||
|
||||
|
||||
def test_index_page(client):
|
||||
response = client.get("/")
|
||||
assert response.status_code == 200
|
||||
assert "基于旋律的音乐哼唱检索系统" in response.text
|
||||
|
||||
|
||||
def test_static_assets(client):
|
||||
for asset in ("/static/app.js", "/static/style.css"):
|
||||
assert client.get(asset).status_code == 200
|
||||
|
||||
|
||||
def test_search_multipart(client, query_wav):
|
||||
blob, song_id = query_wav
|
||||
response = client.post(
|
||||
"/api/search",
|
||||
files={"file": ("query.wav", blob, "audio/wav")},
|
||||
data={"top_k": "5"},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
data = response.json()
|
||||
assert data["hits"]
|
||||
assert data["query"]["n_notes"] > 0
|
||||
assert data["elapsed_ms"] >= 0
|
||||
assert any(hit["song_id"] == song_id for hit in data["hits"])
|
||||
|
||||
|
||||
def test_search_base64(client, query_wav):
|
||||
blob, _ = query_wav
|
||||
response = client.post(
|
||||
"/api/search",
|
||||
json={"audio_base64": base64.b64encode(blob).decode("ascii"), "top_k": 3},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
assert len(response.json()["hits"]) <= 3
|
||||
|
||||
|
||||
def test_search_rejects_garbage(client):
|
||||
response = client.post(
|
||||
"/api/search",
|
||||
files={"file": ("bad.wav", b"not audio at all", "audio/wav")},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_demo_endpoint(client):
|
||||
response = client.post("/api/demo", json={"difficulty": "easy", "seed": 123, "top_k": 5})
|
||||
assert response.status_code == 200, response.text
|
||||
data = response.json()
|
||||
assert data["hits"]
|
||||
assert data["demo"]["answer"]
|
||||
assert data["demo"]["qid"]
|
||||
assert data["track"]["voiced_ratio"] > 0
|
||||
|
||||
audio = client.get(data["demo"]["audio_url"])
|
||||
assert audio.status_code == 200
|
||||
assert audio.headers["content-type"] == "audio/wav"
|
||||
|
||||
|
||||
def test_auth_flow(client):
|
||||
assert client.get("/api/auth/me").json()["logged_in"] is False
|
||||
|
||||
response = client.post(
|
||||
"/api/auth/register", json={"username": "tester", "password": "secret123"}
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
assert client.get("/api/auth/me").json()["logged_in"] is True
|
||||
|
||||
# 重复注册
|
||||
response = client.post(
|
||||
"/api/auth/register", json={"username": "tester", "password": "secret123"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
assert client.post("/api/auth/logout").status_code == 200
|
||||
assert client.get("/api/auth/me").json()["logged_in"] is False
|
||||
|
||||
response = client.post(
|
||||
"/api/auth/login", json={"username": "tester", "password": "secret123"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
response = client.post("/api/auth/login", json={"username": "tester", "password": "bad"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_history_endpoint(client):
|
||||
client.post("/api/demo", json={"difficulty": "easy", "seed": 55, "top_k": 3})
|
||||
data = client.get("/api/history?limit=5").json()
|
||||
assert "history" in data
|
||||
assert len(data["history"]) > 0
|
||||
assert "top_song" in data["history"][0]
|
||||
|
||||
|
||||
def test_library_rebuild(client):
|
||||
response = client.post("/api/library/rebuild")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["ok"] is True
|
||||
assert client.get("/api/status").json()["n_songs"] > 0
|
||||
|
||||
|
||||
def test_eval_run(client):
|
||||
response = client.post(
|
||||
"/api/eval/run", json={"difficulty": "easy", "per_song": 1, "seed": 1, "top_k": 5}
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
report = response.json()["report"]
|
||||
assert report["n_queries"] > 0
|
||||
assert 0.0 <= report["top1"] <= 1.0
|
||||
|
||||
latest = client.get("/api/eval/latest").json()
|
||||
assert latest["available"] is True
|
||||
@@ -0,0 +1,117 @@
|
||||
"""音频输入与预处理测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.audio import (
|
||||
bandpass,
|
||||
denoise,
|
||||
encode_wav_bytes,
|
||||
frame_signal,
|
||||
normalize,
|
||||
read_audio,
|
||||
read_wav_bytes,
|
||||
resample,
|
||||
rms_db,
|
||||
trim_silence,
|
||||
write_wav,
|
||||
)
|
||||
|
||||
|
||||
def _tone(freq: float, seconds: float, sr: int, amp: float = 0.5) -> np.ndarray:
|
||||
t = np.arange(int(sr * seconds)) / sr
|
||||
return (amp * np.sin(2 * np.pi * freq * t)).astype(np.float32)
|
||||
|
||||
|
||||
def test_wav_roundtrip(tmp_path):
|
||||
sr = 16000
|
||||
signal = _tone(440.0, 0.5, sr)
|
||||
path = tmp_path / "tone.wav"
|
||||
write_wav(path, signal, sr)
|
||||
|
||||
loaded, loaded_sr = read_audio(path)
|
||||
assert loaded_sr == sr
|
||||
assert loaded.shape == signal.shape
|
||||
# 16-bit 量化误差应很小
|
||||
assert np.max(np.abs(loaded - signal)) < 1e-3
|
||||
|
||||
|
||||
def test_wav_bytes_roundtrip():
|
||||
sr = 8000
|
||||
signal = _tone(300.0, 0.2, sr)
|
||||
blob = encode_wav_bytes(signal, sr)
|
||||
loaded, loaded_sr = read_wav_bytes(blob)
|
||||
assert loaded_sr == sr
|
||||
assert np.allclose(loaded, signal, atol=1e-3)
|
||||
|
||||
|
||||
def test_resample_preserves_duration():
|
||||
sr = 44100
|
||||
signal = _tone(220.0, 0.4, sr)
|
||||
out = resample(signal, sr, 16000)
|
||||
assert abs(out.size / 16000 - 0.4) < 0.01
|
||||
|
||||
|
||||
def test_resample_identity():
|
||||
signal = _tone(440.0, 0.1, 16000)
|
||||
out = resample(signal, 16000, 16000)
|
||||
assert np.array_equal(out, signal)
|
||||
|
||||
|
||||
def test_bandpass_rejects_out_of_band():
|
||||
sr = 16000
|
||||
low = _tone(20.0, 0.3, sr) # 低于通带
|
||||
mid = _tone(440.0, 0.3, sr) # 通带内
|
||||
high = _tone(6000.0, 0.3, sr) # 高于通带
|
||||
|
||||
low_out = bandpass(low, sr, 60.0, 2000.0)
|
||||
mid_out = bandpass(mid, sr, 60.0, 2000.0)
|
||||
high_out = bandpass(high, sr, 60.0, 2000.0)
|
||||
|
||||
def rms(x: np.ndarray) -> float:
|
||||
return float(np.sqrt(np.mean(x**2)))
|
||||
|
||||
assert rms(mid_out) > 10 * rms(low_out)
|
||||
assert rms(mid_out) > 10 * rms(high_out)
|
||||
|
||||
|
||||
def test_denoise_reduces_high_frequency_noise():
|
||||
rng = np.random.default_rng(0)
|
||||
signal = _tone(440.0, 0.3, 16000, amp=0.5)
|
||||
noisy = signal + rng.normal(0, 0.05, signal.size).astype(np.float32)
|
||||
cleaned = denoise(noisy, 5)
|
||||
assert np.std(cleaned - signal) < np.std(noisy - signal)
|
||||
|
||||
|
||||
def test_trim_silence_removes_padding():
|
||||
sr = 16000
|
||||
core = _tone(440.0, 0.3, sr)
|
||||
padded = np.concatenate([np.zeros(sr // 2, np.float32), core, np.zeros(sr // 2, np.float32)])
|
||||
trimmed = trim_silence(padded, sr)
|
||||
assert trimmed.size < padded.size
|
||||
assert abs(trimmed.size / sr - 0.3) < 0.15
|
||||
|
||||
|
||||
def test_normalize_sets_rms():
|
||||
signal = _tone(440.0, 0.2, 16000, amp=0.01)
|
||||
out = normalize(signal, target_rms=0.1)
|
||||
assert abs(rms_db(out) - 20 * np.log10(0.1)) < 1.0
|
||||
|
||||
|
||||
def test_rms_db_of_silence_is_negative_infinity():
|
||||
assert rms_db(np.zeros(100, dtype=np.float32)) == float("-inf")
|
||||
|
||||
|
||||
def test_frame_signal_shape():
|
||||
x = np.arange(1000, dtype=np.float32)
|
||||
frames = frame_signal(x, 100, 50)
|
||||
assert frames.shape == (19, 100)
|
||||
assert np.allclose(frames[0][:5], x[:5])
|
||||
assert np.allclose(frames[1][:5], x[50:55])
|
||||
|
||||
|
||||
def test_read_audio_rejects_empty():
|
||||
with pytest.raises(Exception):
|
||||
read_wav_bytes(b"")
|
||||
@@ -0,0 +1,90 @@
|
||||
"""DTW 与移调搜索测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.config import DEFAULT
|
||||
from qbh.dtw import _cost_matrix, _dp_matrix, align, shift_candidates, subsequence_dtw
|
||||
from qbh.melody import Melody
|
||||
|
||||
|
||||
def _melody(midis, note_s=0.5, song_id="t") -> Melody:
|
||||
midis = np.asarray(midis, dtype=float)
|
||||
return Melody(midis, np.arange(midis.size) * note_s, np.full(midis.size, note_s * 0.9), song_id)
|
||||
|
||||
|
||||
def _naive_dp(cost: np.ndarray) -> np.ndarray:
|
||||
rows, cols = cost.shape
|
||||
D = np.full((rows, cols), np.inf)
|
||||
D[0, :] = cost[0, :]
|
||||
for i in range(1, rows):
|
||||
for j in range(cols):
|
||||
best = D[i - 1, j]
|
||||
if j > 0:
|
||||
best = min(best, D[i, j - 1], D[i - 1, j - 1])
|
||||
D[i, j] = cost[i, j] + best
|
||||
return D
|
||||
|
||||
|
||||
def test_vectorized_dp_matches_naive():
|
||||
rng = np.random.default_rng(0)
|
||||
cost = rng.random((9, 14)) * 3.0
|
||||
assert np.allclose(_dp_matrix(cost), _naive_dp(cost))
|
||||
|
||||
|
||||
def test_fragment_alignment_finds_correct_span():
|
||||
target = _melody(list(range(60, 75)))
|
||||
query = target.slice(4, 12)
|
||||
result = subsequence_dtw(query, target, shift=0.0, cfg=DEFAULT, need_path=True)
|
||||
assert result.cost == pytest.approx(0.0, abs=1e-6)
|
||||
assert result.target_note_start == 4
|
||||
assert result.target_note_end == 11
|
||||
assert result.sim == pytest.approx(1.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_transposed_query_needs_shift():
|
||||
target = _melody(list(range(60, 75)))
|
||||
query = target.slice(4, 12).transpose(5)
|
||||
|
||||
good = subsequence_dtw(query, target, shift=-5.0, cfg=DEFAULT)
|
||||
bad = subsequence_dtw(query, target, shift=0.0, cfg=DEFAULT)
|
||||
assert good.cost < bad.cost
|
||||
assert good.sim > 0.95
|
||||
|
||||
|
||||
def test_shift_candidates_cover_octave_offsets():
|
||||
target = _melody([60, 62, 64, 67, 69, 67, 64, 62])
|
||||
query = target.transpose(17) # 跨八度的移调
|
||||
candidates = shift_candidates(query, target, DEFAULT)
|
||||
assert -17 in candidates
|
||||
|
||||
|
||||
def test_shift_candidates_cover_plain_transposition():
|
||||
target = _melody([60, 62, 64, 67, 69])
|
||||
query = target.transpose(-5)
|
||||
candidates = shift_candidates(query, target, DEFAULT)
|
||||
assert 5 in candidates
|
||||
|
||||
|
||||
def test_align_picks_best_shift_automatically():
|
||||
target = _melody([60, 62, 64, 67, 69, 67, 64, 62, 60, 62])
|
||||
query = target.slice(1, 7).transpose(4)
|
||||
result = align(query, target, DEFAULT)
|
||||
assert result.shift == pytest.approx(-4.0)
|
||||
assert result.sim > 0.9
|
||||
|
||||
|
||||
def test_duration_cost_penalizes_tempo_mismatch():
|
||||
target = _melody([60, 62, 64, 67])
|
||||
fast = target.scaled(0.25) # 时值全变成 1/4
|
||||
cost = _cost_matrix(fast, target, 0.0, DEFAULT)
|
||||
assert cost.mean() > 0.0
|
||||
|
||||
|
||||
def test_empty_melody_alignment():
|
||||
target = _melody([60, 62, 64])
|
||||
result = subsequence_dtw(Melody.empty(), target, cfg=DEFAULT)
|
||||
assert result.cost == float("inf")
|
||||
assert result.sim == 0.0
|
||||
@@ -0,0 +1,132 @@
|
||||
"""评测模块测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.config import DEFAULT
|
||||
from qbh.evaluate import (
|
||||
DIFFICULTY_PRESETS,
|
||||
add_noise,
|
||||
evaluate,
|
||||
make_query_specs,
|
||||
perturb_melody,
|
||||
synth_query_audio,
|
||||
)
|
||||
from qbh.melody import Melody
|
||||
from qbh.search import SearchEngine
|
||||
|
||||
|
||||
def _melody(song_id="m", n=24) -> Melody:
|
||||
rng = np.random.default_rng(hash(song_id) % 2**31)
|
||||
midis = 60 + np.cumsum(rng.integers(-2, 3, n)).astype(float)
|
||||
midis = np.clip(midis, 55, 80)
|
||||
starts = np.arange(n) * 0.5
|
||||
return Melody(midis, starts, np.full(n, 0.45), song_id, song_id)
|
||||
|
||||
|
||||
def test_make_query_specs_respects_difficulty():
|
||||
melodies = [_melody(f"m{i}") for i in range(3)]
|
||||
easy = make_query_specs(melodies, n_per_song=2, difficulty="easy", seed=1)
|
||||
hard = make_query_specs(melodies, n_per_song=2, difficulty="hard", seed=1)
|
||||
|
||||
assert len(easy) == len(hard) == 6
|
||||
assert easy[0].snr_db > hard[0].snr_db
|
||||
for spec in easy + hard:
|
||||
assert 4 <= spec.n_notes <= 24
|
||||
assert spec.start_idx >= 0
|
||||
|
||||
|
||||
def test_query_specs_are_reproducible():
|
||||
melodies = [_melody("m")]
|
||||
a = make_query_specs(melodies, n_per_song=3, seed=123)
|
||||
b = make_query_specs(melodies, n_per_song=3, seed=123)
|
||||
assert [s.to_dict() for s in a] == [s.to_dict() for s in b]
|
||||
|
||||
|
||||
def test_perturb_melody_applies_transposition_and_tempo():
|
||||
source = _melody()
|
||||
spec = make_query_specs([source], n_per_song=1, seed=5)[0]
|
||||
query = perturb_melody(source, spec, DEFAULT)
|
||||
|
||||
# 音高整体平移(允许抖动带来的偏差)
|
||||
offset = float(np.median(query.midis) - np.median(source.midis))
|
||||
assert abs(offset - spec.shift) < 1.5
|
||||
# 时长被速度缩放
|
||||
ratio = float(np.median(query.durs) / np.median(source.durs))
|
||||
assert abs(ratio - spec.tempo) < 0.3
|
||||
|
||||
|
||||
def test_perturb_melody_changes_note_count():
|
||||
source = _melody(n=40)
|
||||
spec = make_query_specs([source], n_per_song=1, difficulty="hard", seed=9)[0]
|
||||
query = perturb_melody(source, spec, DEFAULT)
|
||||
assert query.n_notes >= 3
|
||||
|
||||
|
||||
def test_add_noise_achieves_rough_snr():
|
||||
rng = np.random.default_rng(0)
|
||||
t = np.arange(16000) / 16000
|
||||
signal = (0.5 * np.sin(2 * np.pi * 440 * t)).astype(np.float32)
|
||||
for target in (20.0, 10.0):
|
||||
noisy = add_noise(signal, target, rng)
|
||||
noise = noisy - signal
|
||||
measured = 10 * np.log10(np.mean(signal**2) / np.mean(noise**2))
|
||||
assert abs(measured - target) < 1.0
|
||||
|
||||
|
||||
def test_synth_query_audio_has_signal():
|
||||
source = _melody()
|
||||
spec = make_query_specs([source], n_per_song=1, seed=3)[0]
|
||||
query = perturb_melody(source, spec, DEFAULT)
|
||||
audio = synth_query_audio(query, spec, DEFAULT)
|
||||
assert audio.size > 0
|
||||
assert float(np.abs(audio).max()) > 0.1
|
||||
|
||||
|
||||
def test_evaluate_returns_sane_metrics(tiny_library):
|
||||
engine = SearchEngine(tiny_library, DEFAULT)
|
||||
specs = make_query_specs(tiny_library.melodies(), n_per_song=2, difficulty="easy", seed=4)
|
||||
report = evaluate(engine, specs, label="test", cfg=DEFAULT)
|
||||
|
||||
assert report.n_queries == len(specs)
|
||||
assert 0.0 <= report.top1 <= 1.0
|
||||
assert report.top3 >= report.top1
|
||||
assert 0.0 <= report.mrr <= 1.0
|
||||
assert report.p95_latency_ms >= report.p50_latency_ms
|
||||
assert len(report.details) == report.n_queries
|
||||
payload = report.to_dict()
|
||||
assert payload["n_songs"] == 3
|
||||
assert "config" in payload
|
||||
|
||||
|
||||
def test_evaluate_empty_specs():
|
||||
class _Empty:
|
||||
class index:
|
||||
n_songs = 0
|
||||
|
||||
class library:
|
||||
@staticmethod
|
||||
def melodies():
|
||||
return []
|
||||
|
||||
report = evaluate(_Empty(), [], label="empty", cfg=DEFAULT)
|
||||
assert report.n_queries == 0
|
||||
assert report.top1 == 0.0
|
||||
|
||||
|
||||
def test_report_save_and_summary(tiny_library, tmp_path):
|
||||
engine = SearchEngine(tiny_library, DEFAULT)
|
||||
specs = make_query_specs(tiny_library.melodies(), n_per_song=1, seed=6)
|
||||
report = evaluate(engine, specs, label="save", cfg=DEFAULT)
|
||||
path = tmp_path / "report.json"
|
||||
report.save(path)
|
||||
assert path.exists()
|
||||
assert "Top-1" in report.summary_line()
|
||||
|
||||
|
||||
def test_difficulty_presets_have_expected_keys():
|
||||
for name, preset in DIFFICULTY_PRESETS.items():
|
||||
for key in ("fragment_low", "fragment_high", "drop", "jitter", "snr_db"):
|
||||
assert key in preset, (name, key)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""倒排索引测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from qbh.config import DEFAULT
|
||||
from qbh.index import NgramIndex, quantize_direction, quantize_magnitude, quantize_rhythm
|
||||
from qbh.melody import Melody
|
||||
|
||||
|
||||
def _melody(midis, song_id="m", 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), song_id)
|
||||
|
||||
|
||||
def test_quantizers():
|
||||
assert list(quantize_magnitude(np.array([0.1, 1.0, 2.0, 4.0, 6.0, 12.0]))) == [0, 1, 2, 3, 4, 5]
|
||||
assert list(quantize_direction(np.array([2.0, 0.0, -2.0]))) == [2, 1, 0]
|
||||
assert list(quantize_rhythm(np.array([0.0, 0.45, -0.9]))) == [0, 1, -2]
|
||||
|
||||
|
||||
def test_build_and_gram_count():
|
||||
index = NgramIndex(cfg=DEFAULT)
|
||||
index.build([_melody([60, 62, 64, 67, 69, 67, 64, 62], "a"),
|
||||
_melody([72, 71, 69, 67, 65], "b")])
|
||||
assert index.n_songs == 2
|
||||
assert index.n_grams() > 0
|
||||
|
||||
|
||||
def test_score_is_transposition_invariant():
|
||||
index = NgramIndex(cfg=DEFAULT)
|
||||
base = _melody([60, 62, 64, 67, 69, 67, 64, 62], "a")
|
||||
index.build([base, _melody([72, 71, 69, 67, 65, 64, 62, 60], "b")])
|
||||
|
||||
score_original = index.score(base)
|
||||
score_shifted = index.score(base.transpose(9))
|
||||
assert score_original.get("a", 0) > 0.8
|
||||
assert abs(score_original.get("a", 0) - score_shifted.get("a", 0)) < 1e-9
|
||||
|
||||
|
||||
def test_candidates_contain_answer():
|
||||
index = NgramIndex(cfg=DEFAULT)
|
||||
target = _melody([60, 62, 64, 67, 69, 71, 72, 71, 69, 67, 64, 62], "target")
|
||||
others = [_melody([60, 60, 67, 67, 69, 69, 67, 67], f"o{i}") for i in range(8)]
|
||||
index.build([target] + others)
|
||||
|
||||
query = target.slice(2, 9).transpose(4)
|
||||
candidates, _ = index.candidates(query)
|
||||
ids = [sid for sid, _ in candidates]
|
||||
assert "target" in ids
|
||||
|
||||
|
||||
def test_empty_melody_scores_nothing():
|
||||
index = NgramIndex(cfg=DEFAULT)
|
||||
index.build([_melody([60, 62, 64], "a")])
|
||||
assert index.score(Melody.empty()) == {}
|
||||
|
||||
|
||||
def test_save_load_roundtrip(tmp_path):
|
||||
index = NgramIndex(cfg=DEFAULT)
|
||||
index.build([_melody([60, 62, 64, 67, 69], "a"), _melody([72, 71, 69, 67], "b")])
|
||||
path = tmp_path / "index.json"
|
||||
index.save(path)
|
||||
|
||||
restored = NgramIndex.load(path, DEFAULT)
|
||||
assert restored.n_songs == index.n_songs
|
||||
assert restored.n_grams() == index.n_grams()
|
||||
query = _melody([60, 62, 64, 67], "q")
|
||||
assert restored.score(query) == index.score(query)
|
||||
@@ -0,0 +1,104 @@
|
||||
"""旋律表示测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.config import DEFAULT
|
||||
from qbh.melody import Melody, fuse_repeated_notes
|
||||
|
||||
|
||||
def test_intervals_are_transposition_invariant():
|
||||
mel = Melody(np.array([60, 62, 64, 67]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||
shifted = mel.transpose(7)
|
||||
assert np.allclose(mel.intervals(), shifted.intervals())
|
||||
|
||||
|
||||
def test_norm_durs_are_tempo_invariant():
|
||||
mel = Melody(np.array([60, 62, 64]), np.array([0.0, 0.5, 1.0]), np.array([0.5, 0.25, 0.25]))
|
||||
scaled = mel.scaled(1.7)
|
||||
assert np.allclose(mel.norm_durs(), scaled.norm_durs())
|
||||
|
||||
|
||||
def test_contour_direction():
|
||||
mel = Melody(np.array([60, 64, 64, 62]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||
assert mel.contour() == "URD"
|
||||
|
||||
|
||||
def test_contour_transposition_invariant():
|
||||
mel = Melody(np.array([60, 64, 64, 62]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||
assert mel.contour() == mel.transpose(-5).contour()
|
||||
|
||||
|
||||
def test_slice_rebases_time():
|
||||
mel = Melody(np.array([60, 62, 64, 65]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||
part = mel.slice(1, 3)
|
||||
assert part.n_notes == 2
|
||||
assert part.starts[0] == pytest.approx(0.0)
|
||||
assert np.allclose(part.midis, [62, 64])
|
||||
|
||||
|
||||
def test_slice_out_of_range_is_empty():
|
||||
mel = Melody(np.array([60, 62]), np.array([0.0, 0.5]), np.array([0.4, 0.4]))
|
||||
assert mel.slice(5, 9).is_empty
|
||||
assert mel.slice(1, 1).is_empty
|
||||
|
||||
|
||||
def test_intervals_clipped():
|
||||
mel = Melody(np.array([40, 100]), np.array([0.0, 1.0]), np.array([1.0, 1.0]))
|
||||
assert mel.intervals(clip=12.0)[0] == 12.0
|
||||
|
||||
|
||||
def test_fuse_repeated_notes_merges_same_pitch():
|
||||
mel = Melody(
|
||||
np.array([60.0, 60.05, 60.02, 64.0]),
|
||||
np.array([0.0, 0.5, 1.0, 1.5]),
|
||||
np.array([0.5, 0.5, 0.5, 0.5]),
|
||||
)
|
||||
fused = fuse_repeated_notes(mel, DEFAULT)
|
||||
assert fused.n_notes == 2
|
||||
assert fused.durs[0] == pytest.approx(1.5, abs=1e-6)
|
||||
|
||||
|
||||
def test_fuse_repeated_notes_keeps_distinct_pitches():
|
||||
mel = Melody(
|
||||
np.array([60.0, 62.0, 64.0]),
|
||||
np.array([0.0, 0.5, 1.0]),
|
||||
np.array([0.5, 0.5, 0.5]),
|
||||
)
|
||||
assert fuse_repeated_notes(mel, DEFAULT).n_notes == 3
|
||||
|
||||
|
||||
def test_fuse_repeated_notes_respects_gap():
|
||||
mel = Melody(
|
||||
np.array([60.0, 60.0]),
|
||||
np.array([0.0, 2.0]), # 间隔 1.5s,远大于阈值
|
||||
np.array([0.5, 0.5]),
|
||||
)
|
||||
assert fuse_repeated_notes(mel, DEFAULT).n_notes == 2
|
||||
|
||||
|
||||
def test_json_roundtrip():
|
||||
mel = Melody(np.array([60.5, 62.25]), np.array([0.0, 0.5]), np.array([0.5, 0.5]), "s", "t")
|
||||
restored = Melody.from_json(mel.to_json())
|
||||
assert np.allclose(restored.midis, mel.midis)
|
||||
assert restored.song_id == "s"
|
||||
|
||||
|
||||
def test_from_events_sorts_by_onset():
|
||||
mel = Melody.from_events([(1.0, 0.5, 64.0), (0.0, 0.5, 60.0), (2.0, 0.5, 67.0)])
|
||||
assert np.allclose(mel.midis, [60, 64, 67])
|
||||
assert np.allclose(mel.starts, [0.0, 1.0, 2.0])
|
||||
|
||||
|
||||
def test_mismatched_lengths_raise():
|
||||
with pytest.raises(ValueError):
|
||||
Melody(np.array([60, 62]), np.array([0.0]), np.array([0.5, 0.5]))
|
||||
|
||||
|
||||
def test_semitone_histogram_counts():
|
||||
mel = Melody(np.array([60.0, 60.4, 62.0]), np.arange(3) * 0.5, np.full(3, 0.4))
|
||||
hist = mel.semitone_histogram()
|
||||
assert hist.sum() == 3
|
||||
assert hist[0] == 2 # 60 和 60.4 都取整到 60
|
||||
@@ -0,0 +1,75 @@
|
||||
"""MIDI 读写测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.melody import Melody
|
||||
from qbh.midiio import read_midi, read_midi_melody, write_midi
|
||||
|
||||
|
||||
def _melody() -> Melody:
|
||||
midis = np.array([60.0, 62.0, 64.0, 67.0, 69.0])
|
||||
starts = np.array([0.0, 0.5, 1.0, 1.5, 2.0])
|
||||
durs = np.array([0.5, 0.5, 0.5, 0.5, 0.9])
|
||||
return Melody(midis, starts, durs, "roundtrip", "回环测试")
|
||||
|
||||
|
||||
def test_write_read_roundtrip(tmp_path):
|
||||
path = tmp_path / "mel.mid"
|
||||
original = _melody()
|
||||
write_midi(path, original, bpm=120.0)
|
||||
|
||||
midi = read_midi(path)
|
||||
assert midi.tracks
|
||||
melody = read_midi_melody(path)
|
||||
|
||||
assert melody.n_notes == original.n_notes
|
||||
assert np.allclose(melody.midis, original.midis)
|
||||
# 时间分辨率受 PPQ 限制,允许 1/480 拍的误差
|
||||
assert np.max(np.abs(melody.starts - original.starts)) < 0.02
|
||||
assert np.max(np.abs(melody.durs - original.durs)) < 0.02
|
||||
|
||||
|
||||
def test_bpm_is_recovered(tmp_path):
|
||||
path = tmp_path / "fast.mid"
|
||||
write_midi(path, _melody(), bpm=150.0)
|
||||
assert read_midi(path).bpm == pytest.approx(150.0, abs=0.5)
|
||||
|
||||
|
||||
def test_rejects_non_midi(tmp_path):
|
||||
path = tmp_path / "not.mid"
|
||||
path.write_bytes(b"this is not midi at all")
|
||||
with pytest.raises(ValueError):
|
||||
read_midi(path)
|
||||
|
||||
|
||||
def test_reads_project_midi_library():
|
||||
"""真实 MIDI 曲库应能全部解析出合理旋律。"""
|
||||
from pathlib import Path
|
||||
|
||||
midi_dir = Path(__file__).resolve().parent.parent / "data" / "midi"
|
||||
files = sorted(midi_dir.glob("*.mid"))
|
||||
if not files:
|
||||
pytest.skip("未找到 data/midi 曲库")
|
||||
|
||||
for path in files:
|
||||
melody = read_midi_melody(path)
|
||||
assert melody.n_notes >= 4, path.name
|
||||
assert melody.duration > 0.5, path.name
|
||||
# 单声部化之后音高应落在合理音区
|
||||
assert 30.0 < melody.median_pitch < 100.0, path.name
|
||||
|
||||
|
||||
def test_monophonize_keeps_highest_on_overlap():
|
||||
from qbh.midiio import MidiNote, _monophonize
|
||||
|
||||
notes = [
|
||||
MidiNote(60, 0.0, 1.0),
|
||||
MidiNote(67, 0.5, 1.0), # 与前者重叠且更高
|
||||
]
|
||||
reduced = _monophonize(notes)
|
||||
pitches = [n.pitch for n in reduced]
|
||||
assert 67 in pitches
|
||||
assert sum(1 for n in reduced if n.pitch == 60) <= 1
|
||||
@@ -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)
|
||||
@@ -0,0 +1,76 @@
|
||||
"""YIN 基频提取测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.pitch import extract_pitch, hz_to_midi, midi_to_hz
|
||||
|
||||
|
||||
def _tone(freq: float, seconds: float, sr: int = 16000, amp: float = 0.5) -> np.ndarray:
|
||||
t = np.arange(int(sr * seconds)) / sr
|
||||
return (amp * np.sin(2 * np.pi * freq * t)).astype(np.float32)
|
||||
|
||||
|
||||
def test_midi_hz_roundtrip():
|
||||
for midi in (40.0, 60.0, 69.0, 72.5):
|
||||
assert abs(hz_to_midi(midi_to_hz(np.array([midi])))[0] - midi) < 1e-9
|
||||
assert abs(midi_to_hz(np.array([69.0]))[0] - 440.0) < 1e-9
|
||||
|
||||
|
||||
@pytest.mark.parametrize("freq", [80.0, 110.0, 220.0, 440.0, 660.0, 880.0])
|
||||
def test_pure_tone_pitch_accuracy(freq):
|
||||
track = extract_pitch(_tone(freq, 0.8), 16000)
|
||||
voiced = track.midi[track.voiced]
|
||||
assert voiced.size > 0
|
||||
expected = 69.0 + 12.0 * np.log2(freq / 440.0)
|
||||
# 允许 0.1 半音误差(含抛物线插值残差)
|
||||
assert abs(float(np.median(voiced)) - expected) < 0.1
|
||||
|
||||
|
||||
def test_silence_is_unvoiced():
|
||||
track = extract_pitch(np.zeros(16000, dtype=np.float32), 16000)
|
||||
assert track.voiced.mean() == 0.0
|
||||
|
||||
|
||||
def test_low_level_noise_is_unvoiced():
|
||||
rng = np.random.default_rng(1)
|
||||
track = extract_pitch(rng.normal(0, 1e-6, 16000).astype(np.float32), 16000)
|
||||
assert track.voiced.mean() == 0.0
|
||||
|
||||
|
||||
def test_harmonic_rich_signal_tracks_fundamental():
|
||||
sr = 16000
|
||||
t = np.arange(sr) / sr
|
||||
signal = np.zeros_like(t)
|
||||
for harmonic, amp in ((1, 1.0), (2, 0.4), (3, 0.2), (4, 0.1)):
|
||||
signal += amp * np.sin(2 * np.pi * 110.0 * harmonic * t)
|
||||
signal = (0.4 * signal / np.abs(signal).max()).astype(np.float32)
|
||||
|
||||
track = extract_pitch(signal, sr)
|
||||
voiced = track.midi[track.voiced]
|
||||
assert abs(float(np.median(voiced)) - 45.0) < 0.15 # A2 = MIDI 45
|
||||
|
||||
|
||||
def test_vibrato_tracked_within_reasonable_band():
|
||||
sr = 16000
|
||||
t = np.arange(sr) / sr
|
||||
f0 = 440.0 * 2 ** ((0.3 * np.sin(2 * np.pi * 5 * t)) / 12.0)
|
||||
phase = 2 * np.pi * np.cumsum(f0) / sr
|
||||
track = extract_pitch((0.5 * np.sin(phase)).astype(np.float32), sr)
|
||||
voiced = track.midi[track.voiced]
|
||||
assert abs(float(np.median(voiced)) - 69.0) < 0.1
|
||||
assert 0.05 < float(np.std(voiced)) < 0.5 # 确实跟踪到了颤音
|
||||
|
||||
|
||||
def test_confidence_high_for_clean_tone():
|
||||
track = extract_pitch(_tone(440.0, 0.5), 16000)
|
||||
assert float(np.median(track.conf[track.voiced])) > 0.9
|
||||
|
||||
|
||||
def test_empty_and_short_input():
|
||||
track = extract_pitch(np.zeros(0, dtype=np.float32), 16000)
|
||||
assert track.n_frames == 0
|
||||
short = extract_pitch(np.zeros(100, dtype=np.float32), 16000)
|
||||
assert short.voiced.size == 0
|
||||
@@ -0,0 +1,86 @@
|
||||
"""检索引擎端到端测试(合成曲库 + 合成哼唱)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.config import DEFAULT
|
||||
from qbh.search import SearchEngine
|
||||
from qbh.synth import render_melody
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def engine(tiny_library):
|
||||
return SearchEngine(tiny_library, DEFAULT)
|
||||
|
||||
|
||||
def test_index_built_from_library(engine, tiny_library):
|
||||
assert engine.index.n_songs == tiny_library.count() == 3
|
||||
|
||||
|
||||
def test_exact_melody_retrieves_itself(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_a")
|
||||
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||
assert result.hits[0].song_id == "m_a"
|
||||
assert result.hits[0].score > 0.9
|
||||
|
||||
|
||||
def test_transposed_melody_still_retrieved(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_b").transpose(7)
|
||||
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||
assert result.hits[0].song_id == "m_b"
|
||||
|
||||
|
||||
def test_fragment_retrieval(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_a").slice(1, 7).transpose(-3)
|
||||
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||
assert result.hits[0].song_id == "m_a"
|
||||
|
||||
|
||||
def test_audio_pipeline_retrieves_rendered_hum(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_a")
|
||||
audio = render_melody(melody.transpose(4), 16000, timbre="hum", seed=21)
|
||||
result, track = engine.search_audio(audio, 16000, top_k=3)
|
||||
assert track.voiced_ratio() > 0.5
|
||||
assert result.hits[0].song_id == "m_a"
|
||||
|
||||
|
||||
def test_result_serialization(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_a")
|
||||
result = engine.search_melody(melody, top_k=2, with_path=True)
|
||||
payload = result.to_dict()
|
||||
assert payload["n_songs"] == 3
|
||||
assert payload["hits"]
|
||||
assert "query" in payload
|
||||
hit = payload["hits"][0]
|
||||
for key in ("song_id", "title", "score", "dtw_sim", "index_sim", "shift", "path"):
|
||||
assert key in hit
|
||||
assert payload["query"]["contour"]
|
||||
|
||||
|
||||
def test_hit_exposes_matched_segment(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_a")
|
||||
result = engine.search_melody(melody, top_k=1, with_path=True)
|
||||
hit = result.hits[0]
|
||||
assert hit.target_end_s >= hit.target_start_s
|
||||
assert hit.target_note_end >= hit.target_note_start
|
||||
|
||||
|
||||
def test_coarse_candidates_include_answer(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_c").transpose(5)
|
||||
candidates = [sid for sid, _ in engine.coarse_candidates(melody)]
|
||||
assert "m_c" in candidates
|
||||
|
||||
|
||||
def test_empty_melody_returns_no_hits(engine):
|
||||
from qbh.melody import Melody
|
||||
|
||||
result = engine.search_melody(Melody.empty(), top_k=3)
|
||||
assert result.hits == []
|
||||
|
||||
|
||||
def test_elapsed_ms_is_reported(engine, tiny_library):
|
||||
melody = tiny_library.get_melody("m_a")
|
||||
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||
assert result.elapsed_ms >= 0.0
|
||||
@@ -0,0 +1,116 @@
|
||||
"""SQLite 持久化层测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.melody import Melody
|
||||
from qbh.store import SongRecord, Store, hash_password, verify_password
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store(tmp_path):
|
||||
s = Store(tmp_path / "test.db")
|
||||
yield s
|
||||
s.close()
|
||||
|
||||
|
||||
def test_song_crud(store):
|
||||
record = SongRecord(id="s1", title="测试曲", origin="测试", tags=("a", "b"),
|
||||
source="test", n_notes=10, duration=5.0, median_pitch=60.0)
|
||||
store.upsert_song(record)
|
||||
assert store.count_songs() == 1
|
||||
|
||||
loaded = store.get_song("s1")
|
||||
assert loaded is not None
|
||||
assert loaded.title == "测试曲"
|
||||
assert loaded.tags == ("a", "b")
|
||||
|
||||
record.title = "改名"
|
||||
store.upsert_song(record)
|
||||
assert store.get_song("s1").title == "改名"
|
||||
|
||||
assert store.delete_song("s1") is True
|
||||
assert store.count_songs() == 0
|
||||
assert store.get_song("s1") is None
|
||||
|
||||
|
||||
def test_melody_storage(store):
|
||||
mel = Melody(np.array([60.0, 62.0]), np.array([0.0, 0.5]), np.array([0.5, 0.5]), "s1", "曲")
|
||||
store.set_melody(mel)
|
||||
loaded = store.get_melody("s1")
|
||||
assert loaded is not None
|
||||
assert np.allclose(loaded.midis, mel.midis)
|
||||
|
||||
store.set_melodies([mel])
|
||||
assert len(store.all_melodies()) == 1
|
||||
|
||||
|
||||
def test_password_hashing():
|
||||
salt, digest = hash_password("secret123")
|
||||
assert verify_password("secret123", salt, digest)
|
||||
assert not verify_password("wrong", salt, digest)
|
||||
# 相同密码、不同盐 → 不同哈希
|
||||
salt2, digest2 = hash_password("secret123")
|
||||
assert digest != digest2
|
||||
|
||||
|
||||
def test_user_lifecycle(store):
|
||||
ok, message = store.create_user("alice", "password1", "a@example.com")
|
||||
assert ok, message
|
||||
|
||||
# 重复注册
|
||||
ok, message = store.create_user("alice", "password2")
|
||||
assert not ok and "已存在" in message
|
||||
|
||||
# 密码太短
|
||||
ok, message = store.create_user("bob", "123")
|
||||
assert not ok and "密码" in message
|
||||
|
||||
user_id = store.verify_user("alice", "password1")
|
||||
assert user_id is not None
|
||||
assert store.verify_user("alice", "wrong") is None
|
||||
assert store.verify_user("nobody", "password1") is None
|
||||
|
||||
info = store.get_user(user_id)
|
||||
assert info["username"] == "alice"
|
||||
|
||||
|
||||
def test_history_lifecycle(store):
|
||||
ok, _ = store.create_user("carol", "password1")
|
||||
assert ok
|
||||
user_id = store.verify_user("carol", "password1")
|
||||
|
||||
store.add_history(
|
||||
user_id=user_id, source="mic", query_notes=12, query_melody="{}",
|
||||
top_song="s1", top_title="曲一", top_score=0.9, elapsed_ms=50.0,
|
||||
results=[{"song_id": "s1", "score": 0.9}],
|
||||
)
|
||||
store.add_history(
|
||||
user_id=None, source="demo", query_notes=8, query_melody="{}",
|
||||
top_song="s2", top_title="曲二", top_score=0.8, elapsed_ms=40.0, results=[],
|
||||
)
|
||||
|
||||
assert len(store.list_history()) == 2
|
||||
mine = store.list_history(user_id=user_id)
|
||||
assert len(mine) == 1
|
||||
assert mine[0]["top_song"] == "s1"
|
||||
assert mine[0]["results"][0]["song_id"] == "s1"
|
||||
|
||||
assert store.clear_history(user_id=user_id) == 1
|
||||
assert len(store.list_history()) == 1
|
||||
|
||||
|
||||
def test_meta_roundtrip(store):
|
||||
store.set_meta("k", {"a": 1})
|
||||
assert store.get_meta("k") == {"a": 1}
|
||||
assert store.get_meta("missing", default=42) == 42
|
||||
|
||||
|
||||
def test_persistence_across_connections(tmp_path):
|
||||
path = tmp_path / "persist.db"
|
||||
with Store(path) as first:
|
||||
first.upsert_song(SongRecord(id="x", title="持久化"))
|
||||
with Store(path) as second:
|
||||
assert second.get_song("x").title == "持久化"
|
||||
Reference in New Issue
Block a user