480 lines
16 KiB
Python
480 lines
16 KiB
Python
"""评测:合成「像人哼唱」的查询,端到端度量检索性能。
|
||
|
||
为什么要自己合成查询:公开的哼唱数据集(如 MIREX-QBH)体积大且需要额外下载,
|
||
所以这里用**显式的扰动模型**来模拟人声哼唱,参数全部可复现(固定种子):
|
||
|
||
1. 取旋律中一段连续片段(易:8–20 个音;难:整首的 40–80%);
|
||
2. 移调(±5 半音,偶尔 ±12);
|
||
3. 速度缩放 0.8–1.3×;
|
||
4. 逐音高抖动 + 缓慢音高漂移;
|
||
5. 丢音 / 把一个音劈成两个 / 插入邻音;
|
||
6. 按哼唱音色渲染(起音滑音、颤音、弱谐波、呼吸噪声);
|
||
7. 按目标信噪比叠加白噪声。
|
||
|
||
指标:Top-1/3/5/10、MRR、平均排名、粗召回率、延迟 p50/p95,外加逐查询明细
|
||
(用于失败分析)与音符提取质量(音符数比、音高误差)。
|
||
|
||
诚实性说明:合成查询 + 合成曲库会让数字偏乐观;因此本项目的基准报告以
|
||
**磁盘上的真实 MIDI 曲库**为主,合成曲库只用于规模化与消融实验。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import math
|
||
import time
|
||
from dataclasses import dataclass, field
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Any, Sequence
|
||
|
||
import numpy as np
|
||
|
||
from .config import DEFAULT, Config
|
||
from .library import Library
|
||
from .melody import Melody
|
||
from .search import SearchEngine
|
||
from .synth import render_melody
|
||
|
||
__all__ = [
|
||
"QuerySpec",
|
||
"QueryOutcome",
|
||
"EvalReport",
|
||
"make_query_specs",
|
||
"perturb_melody",
|
||
"add_noise",
|
||
"evaluate",
|
||
"snr_ablation",
|
||
]
|
||
|
||
# 难度预设:控制片段长度与扰动强度
|
||
DIFFICULTY_PRESETS: dict[str, dict[str, float]] = {
|
||
"easy": dict(fragment_low=0.45, fragment_high=0.8, drop=0.04, insert=0.02, split=0.03,
|
||
jitter=0.28, drift=0.5, snr_db=22.0),
|
||
"normal": dict(fragment_low=0.3, fragment_high=0.6, drop=0.06, insert=0.03, split=0.05,
|
||
jitter=0.35, drift=0.8, snr_db=18.0),
|
||
"hard": dict(fragment_low=0.4, fragment_high=0.8, drop=0.16, insert=0.05, split=0.08,
|
||
jitter=0.5, drift=1.2, snr_db=12.0),
|
||
}
|
||
|
||
|
||
@dataclass
|
||
class QuerySpec:
|
||
"""一条合成查询的构造参数(可完整复现)。"""
|
||
|
||
qid: str
|
||
song_id: str
|
||
title: str
|
||
start_idx: int
|
||
n_notes: int
|
||
shift: float
|
||
tempo: float
|
||
snr_db: float
|
||
difficulty: str
|
||
seed: int
|
||
|
||
def to_dict(self) -> dict[str, Any]:
|
||
return {
|
||
"qid": self.qid,
|
||
"song_id": self.song_id,
|
||
"title": self.title,
|
||
"start_idx": self.start_idx,
|
||
"n_notes": self.n_notes,
|
||
"shift": self.shift,
|
||
"tempo": round(self.tempo, 3),
|
||
"snr_db": self.snr_db,
|
||
"difficulty": self.difficulty,
|
||
"seed": self.seed,
|
||
}
|
||
|
||
@classmethod
|
||
def from_dict(cls, data: dict[str, Any]) -> "QuerySpec":
|
||
return cls(
|
||
qid=data["qid"],
|
||
song_id=data["song_id"],
|
||
title=data.get("title", ""),
|
||
start_idx=int(data["start_idx"]),
|
||
n_notes=int(data["n_notes"]),
|
||
shift=float(data["shift"]),
|
||
tempo=float(data["tempo"]),
|
||
snr_db=float(data.get("snr_db", 18.0)),
|
||
difficulty=data.get("difficulty", "normal"),
|
||
seed=int(data.get("seed", 0)),
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class QueryOutcome:
|
||
qid: str
|
||
answer: str
|
||
answer_title: str
|
||
difficulty: str
|
||
rank: int # 0 表示未进 Top-K
|
||
top1: str
|
||
top1_score: float
|
||
candidate_hit: bool
|
||
elapsed_ms: float
|
||
n_candidates: int
|
||
n_notes_truth: int
|
||
n_notes_extracted: int
|
||
pitch_err: float
|
||
snr_db: float
|
||
|
||
def to_dict(self) -> dict[str, Any]:
|
||
return {
|
||
"qid": self.qid,
|
||
"answer": self.answer,
|
||
"answer_title": self.answer_title,
|
||
"difficulty": self.difficulty,
|
||
"rank": self.rank,
|
||
"top1": self.top1,
|
||
"top1_score": round(self.top1_score, 4),
|
||
"candidate_hit": self.candidate_hit,
|
||
"elapsed_ms": round(self.elapsed_ms, 2),
|
||
"n_candidates": self.n_candidates,
|
||
"n_notes_truth": self.n_notes_truth,
|
||
"n_notes_extracted": self.n_notes_extracted,
|
||
"pitch_err": round(self.pitch_err, 3),
|
||
"snr_db": self.snr_db,
|
||
}
|
||
|
||
|
||
@dataclass
|
||
class EvalReport:
|
||
"""一次评测的汇总结果。"""
|
||
|
||
label: str
|
||
n_queries: int
|
||
n_songs: int
|
||
top1: float
|
||
top3: float
|
||
top5: float
|
||
top10: float
|
||
mrr: float
|
||
mean_rank: float
|
||
candidate_recall: float
|
||
mean_latency_ms: float
|
||
p50_latency_ms: float
|
||
p95_latency_ms: float
|
||
note_count_ratio: float
|
||
pitch_err_median: float
|
||
difficulty: str
|
||
top_k: int
|
||
created_at: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
||
details: list[QueryOutcome] = field(default_factory=list)
|
||
config: dict[str, Any] = field(default_factory=dict)
|
||
extra: dict[str, Any] = field(default_factory=dict)
|
||
|
||
def to_dict(self, *, include_details: bool = True) -> dict[str, Any]:
|
||
out: dict[str, Any] = {
|
||
"label": self.label,
|
||
"n_queries": self.n_queries,
|
||
"n_songs": self.n_songs,
|
||
"top1": round(self.top1, 4),
|
||
"top3": round(self.top3, 4),
|
||
"top5": round(self.top5, 4),
|
||
"top10": round(self.top10, 4),
|
||
"mrr": round(self.mrr, 4),
|
||
"mean_rank": round(self.mean_rank, 3),
|
||
"candidate_recall": round(self.candidate_recall, 4),
|
||
"mean_latency_ms": round(self.mean_latency_ms, 2),
|
||
"p50_latency_ms": round(self.p50_latency_ms, 2),
|
||
"p95_latency_ms": round(self.p95_latency_ms, 2),
|
||
"note_count_ratio": round(self.note_count_ratio, 3),
|
||
"pitch_err_median": round(self.pitch_err_median, 3),
|
||
"difficulty": self.difficulty,
|
||
"top_k": self.top_k,
|
||
"created_at": self.created_at,
|
||
"config": self.config,
|
||
"extra": self.extra,
|
||
}
|
||
if include_details:
|
||
out["details"] = [d.to_dict() for d in self.details]
|
||
return out
|
||
|
||
def save(self, path: str | Path, *, include_details: bool = True) -> None:
|
||
path = Path(path)
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_text(
|
||
json.dumps(self.to_dict(include_details=include_details), ensure_ascii=False, indent=2),
|
||
encoding="utf-8",
|
||
)
|
||
|
||
def summary_line(self) -> str:
|
||
return (
|
||
f"[{self.label}] n={self.n_queries} 曲库={self.n_songs} "
|
||
f"Top-1={self.top1*100:.1f}% Top-3={self.top3*100:.1f}% "
|
||
f"Top-5={self.top5*100:.1f}% MRR={self.mrr:.3f} "
|
||
f"召回率={self.candidate_recall*100:.1f}% "
|
||
f"延迟={self.p50_latency_ms:.0f}/{self.p95_latency_ms:.0f}ms"
|
||
)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 查询合成
|
||
# --------------------------------------------------------------------------- #
|
||
def make_query_specs(
|
||
melodies: Sequence[Melody],
|
||
*,
|
||
n_per_song: int = 3,
|
||
difficulty: str = "normal",
|
||
seed: int = 20260908,
|
||
cfg: Config = DEFAULT,
|
||
transpose_choices: Sequence[int] = (-5, -3, -2, 0, 2, 4, 5, 7),
|
||
octave_probability: float = 0.12,
|
||
tempo_low: float = 0.82,
|
||
tempo_high: float = 1.28,
|
||
snr_db: float | None = None,
|
||
) -> list[QuerySpec]:
|
||
"""为曲库中的每首旋律生成若干条查询参数。"""
|
||
preset = DIFFICULTY_PRESETS.get(difficulty, DIFFICULTY_PRESETS["normal"])
|
||
target_snr = float(preset["snr_db"] if snr_db is None else snr_db)
|
||
rng = np.random.default_rng(seed)
|
||
|
||
specs: list[QuerySpec] = []
|
||
for mel in melodies:
|
||
n = mel.n_notes
|
||
if n < 6:
|
||
continue
|
||
for k in range(n_per_song):
|
||
low = max(4, int(round(preset["fragment_low"] * n)))
|
||
high = max(low + 1, int(round(preset["fragment_high"] * n)))
|
||
length = int(rng.integers(low, min(high, n) + 1))
|
||
length = max(4, min(length, n))
|
||
start = int(rng.integers(0, n - length + 1))
|
||
shift = float(rng.choice(transpose_choices))
|
||
if rng.random() < octave_probability:
|
||
shift += 12.0 * float(rng.choice([-1, 1]))
|
||
specs.append(
|
||
QuerySpec(
|
||
qid=f"q{len(specs):04d}",
|
||
song_id=mel.song_id,
|
||
title=mel.title,
|
||
start_idx=start,
|
||
n_notes=length,
|
||
shift=shift,
|
||
tempo=float(rng.uniform(tempo_low, tempo_high)),
|
||
snr_db=target_snr,
|
||
difficulty=difficulty,
|
||
seed=int(rng.integers(0, 2**31 - 1)),
|
||
)
|
||
)
|
||
return specs
|
||
|
||
|
||
def perturb_melody(
|
||
mel: Melody,
|
||
spec: QuerySpec,
|
||
cfg: Config = DEFAULT,
|
||
) -> Melody:
|
||
"""按查询参数对旋律施加「人哼唱」扰动(不含渲染与加噪)。"""
|
||
preset = DIFFICULTY_PRESETS.get(spec.difficulty, DIFFICULTY_PRESETS["normal"])
|
||
rng = np.random.default_rng(spec.seed)
|
||
|
||
fragment = mel.slice(spec.start_idx, spec.start_idx + spec.n_notes)
|
||
pitches = fragment.midis.copy()
|
||
durs = fragment.durs.copy()
|
||
|
||
# 缓慢音高漂移 + 逐音抖动
|
||
drift = np.clip(np.cumsum(rng.normal(0.0, 0.06, pitches.size)), -preset["drift"], preset["drift"])
|
||
pitches = pitches + rng.normal(0.0, preset["jitter"], pitches.size) + drift
|
||
|
||
# 丢音 / 劈音 / 插音
|
||
kept: list[tuple[float, float]] = []
|
||
for pitch, dur in zip(pitches, durs):
|
||
if rng.random() < preset["drop"]:
|
||
continue
|
||
if rng.random() < preset["split"] and dur > 0.2:
|
||
half = dur / 2.0
|
||
kept.append((pitch, half))
|
||
kept.append((pitch + rng.normal(0.0, 0.15), half))
|
||
else:
|
||
kept.append((pitch, dur))
|
||
if rng.random() < preset["insert"]:
|
||
kept.append((pitch + float(rng.choice([-2, -1, 1, 2])), dur * 0.5))
|
||
|
||
if len(kept) < 3:
|
||
kept = [(float(p), float(d)) for p, d in zip(pitches[:3], durs[:3])]
|
||
|
||
# 用原始音长比例重建时间轴(保留节奏形状,音间留 2% 空隙)
|
||
starts: list[float] = []
|
||
cursor = 0.0
|
||
for _, dur in kept:
|
||
starts.append(cursor)
|
||
cursor += dur * 1.02
|
||
|
||
out = Melody(
|
||
np.array([p for p, _ in kept], dtype=np.float64),
|
||
np.array(starts, dtype=np.float64),
|
||
np.array([d for _, d in kept], dtype=np.float64),
|
||
song_id=mel.song_id,
|
||
title=mel.title,
|
||
)
|
||
return out.transpose(spec.shift).scaled(spec.tempo)
|
||
|
||
|
||
def add_noise(x: np.ndarray, snr_db: float, rng: np.random.Generator) -> np.ndarray:
|
||
"""按目标信噪比叠加白噪声。"""
|
||
if not np.isfinite(snr_db):
|
||
return x
|
||
signal_power = float(np.mean(np.square(x, dtype=np.float64)))
|
||
if signal_power <= 0.0:
|
||
return x
|
||
noise_power = signal_power / (10.0 ** (snr_db / 10.0))
|
||
noise = rng.normal(0.0, math.sqrt(noise_power), x.size)
|
||
return np.clip(x + noise, -1.0, 1.0).astype(np.float32)
|
||
|
||
|
||
def synth_query_audio(
|
||
mel: Melody, spec: QuerySpec, cfg: Config = DEFAULT
|
||
) -> np.ndarray:
|
||
"""把查询旋律渲染成带噪的「哼唱」音频。"""
|
||
rng = np.random.default_rng(spec.seed + 7919)
|
||
wave = render_melody(mel, cfg.sample_rate, timbre="hum", seed=spec.seed % (2**31 - 1))
|
||
return add_noise(wave, spec.snr_db, rng)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 评测
|
||
# --------------------------------------------------------------------------- #
|
||
def _rank_of(hits, answer: str) -> int:
|
||
for idx, hit in enumerate(hits, start=1):
|
||
if hit.song_id == answer:
|
||
return idx
|
||
return 0
|
||
|
||
|
||
def evaluate(
|
||
engine: SearchEngine,
|
||
specs: Sequence[QuerySpec],
|
||
*,
|
||
label: str = "eval",
|
||
top_k: int = 10,
|
||
cfg: Config = DEFAULT,
|
||
library: Library | None = None,
|
||
verbose: bool = False,
|
||
) -> EvalReport:
|
||
"""跑完整流水线(合成音频 → 提取 → 检索)并汇总指标。"""
|
||
melodies = {m.song_id: m for m in engine.library.melodies()}
|
||
outcomes: list[QueryOutcome] = []
|
||
ranks: list[int] = []
|
||
latencies: list[float] = []
|
||
candidate_hits = 0
|
||
note_ratios: list[float] = []
|
||
pitch_errs: list[float] = []
|
||
|
||
for spec in specs:
|
||
source = melodies.get(spec.song_id)
|
||
if source is None:
|
||
continue
|
||
truth = perturb_melody(source, spec, cfg)
|
||
audio = synth_query_audio(truth, spec, cfg)
|
||
|
||
# 粗召回是否覆盖答案(用于诊断两级检索的瓶颈)
|
||
result, track = engine.search_audio(audio, cfg.sample_rate, top_k=top_k, cfg=cfg)
|
||
cand_ids = {sid for sid, _ in engine.coarse_candidates(result.query)}
|
||
candidate_hit = spec.song_id in cand_ids
|
||
candidate_hits += int(candidate_hit)
|
||
|
||
rank = _rank_of(result.hits, spec.song_id)
|
||
ranks.append(rank if rank > 0 else 0)
|
||
latencies.append(result.elapsed_ms)
|
||
|
||
extracted = result.query.n_notes
|
||
note_ratios.append(extracted / max(truth.n_notes, 1))
|
||
# 提取音高误差:按顺序比较前 min 个音(近似)
|
||
m = min(extracted, truth.n_notes)
|
||
if m > 1:
|
||
pitch_errs.append(float(np.median(np.abs(truth.midis[:m] - result.query.midis[:m]))))
|
||
|
||
top = result.hits[0] if result.hits else None
|
||
outcomes.append(
|
||
QueryOutcome(
|
||
qid=spec.qid,
|
||
answer=spec.song_id,
|
||
answer_title=spec.title,
|
||
difficulty=spec.difficulty,
|
||
rank=rank,
|
||
top1=top.song_id if top else "",
|
||
top1_score=top.score if top else 0.0,
|
||
candidate_hit=candidate_hit,
|
||
elapsed_ms=result.elapsed_ms,
|
||
n_candidates=result.n_candidates,
|
||
n_notes_truth=truth.n_notes,
|
||
n_notes_extracted=extracted,
|
||
pitch_err=pitch_errs[-1] if pitch_errs else float("nan"),
|
||
snr_db=spec.snr_db,
|
||
)
|
||
)
|
||
if verbose and rank != 1:
|
||
print(
|
||
f" {spec.qid} {spec.song_id} -> {outcomes[-1].top1} "
|
||
f"rank={rank} score={outcomes[-1].top1_score:.3f}"
|
||
)
|
||
|
||
n = len(outcomes)
|
||
if n == 0:
|
||
return EvalReport(
|
||
label=label, n_queries=0, n_songs=engine.index.n_songs, top1=0.0, top3=0.0,
|
||
top5=0.0, top10=0.0, mrr=0.0, mean_rank=0.0, candidate_recall=0.0,
|
||
mean_latency_ms=0.0, p50_latency_ms=0.0, p95_latency_ms=0.0,
|
||
note_count_ratio=0.0, pitch_err_median=0.0, difficulty="n/a", top_k=top_k,
|
||
config=cfg.to_dict(),
|
||
)
|
||
|
||
def _acc(limit: int) -> float:
|
||
return sum(1 for r in ranks if 0 < r <= limit) / n
|
||
|
||
reciprocal = sum((1.0 / r) for r in ranks if r > 0) / n
|
||
mean_rank = float(np.mean([r if r > 0 else top_k + 1 for r in ranks]))
|
||
lat = np.asarray(latencies, dtype=np.float64)
|
||
|
||
return EvalReport(
|
||
label=label,
|
||
n_queries=n,
|
||
n_songs=engine.index.n_songs,
|
||
top1=_acc(1),
|
||
top3=_acc(3),
|
||
top5=_acc(5),
|
||
top10=_acc(10),
|
||
mrr=reciprocal,
|
||
mean_rank=mean_rank,
|
||
candidate_recall=candidate_hits / n,
|
||
mean_latency_ms=float(lat.mean()),
|
||
p50_latency_ms=float(np.percentile(lat, 50)),
|
||
p95_latency_ms=float(np.percentile(lat, 95)),
|
||
note_count_ratio=float(np.mean(note_ratios)),
|
||
pitch_err_median=float(np.median(pitch_errs)) if pitch_errs else float("nan"),
|
||
difficulty=specs[0].difficulty if specs else "n/a",
|
||
top_k=top_k,
|
||
details=outcomes,
|
||
config=cfg.to_dict(),
|
||
)
|
||
|
||
|
||
def snr_ablation(
|
||
engine: SearchEngine,
|
||
melodies: Sequence[Melody],
|
||
*,
|
||
levels: Sequence[float] = (22.0, 18.0, 15.0, 12.5, 10.0, 7.5, 5.0),
|
||
n_per_song: int = 2,
|
||
seed: int = 20260908,
|
||
cfg: Config = DEFAULT,
|
||
label_prefix: str = "snr",
|
||
) -> list[EvalReport]:
|
||
"""在若干信噪比下重复评测,得到鲁棒性曲线。"""
|
||
reports: list[EvalReport] = []
|
||
for snr in levels:
|
||
specs = make_query_specs(
|
||
melodies,
|
||
n_per_song=n_per_song,
|
||
difficulty="normal",
|
||
seed=seed,
|
||
cfg=cfg,
|
||
snr_db=snr,
|
||
)
|
||
reports.append(
|
||
evaluate(engine, specs, label=f"{label_prefix}-{snr:g}dB", cfg=cfg)
|
||
)
|
||
return reports
|