Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
+235
@@ -0,0 +1,235 @@
|
||||
"""子序列动态时间规整(subsequence DTW)与移调搜索。
|
||||
|
||||
两个关键设计:
|
||||
|
||||
**开放起止的子序列对齐**。人常常只哼副歌或某个片段,因此查询不必对齐整首
|
||||
曲子:起始代价置零(``D[0, :] = 0``),终点取最后一行的最小值。这样查询可以
|
||||
落在曲库旋律的任意连续片段上。
|
||||
|
||||
**自由带 + 移调搜索**。YIN 在颤音与滑音处有 ±0.5 半音左右的量化误差,
|
||||
若直接线性惩罚会让正确曲目被误伤,故对音高代价先减掉一个自由带再截断。
|
||||
查询与曲库的调性差异用「音高直方图匹配」先粗筛 8 个候选移调,再各扩 ±1 精算,
|
||||
比在 ±12 半音上逐个穷举快得多。
|
||||
|
||||
行递推用前缀和技巧向量化(``B[j] = min(A[j] − S[j−1], B[j−1])`` 是累积最小),
|
||||
避免 Python 层的双重循环。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .melody import Melody
|
||||
|
||||
__all__ = ["Alignment", "align", "subsequence_dtw", "shift_candidates"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Alignment:
|
||||
"""一次查询—目标对齐的结果。"""
|
||||
|
||||
song_id: str
|
||||
shift: float
|
||||
cost: float # 平均单元代价
|
||||
sim: float # 相似度 0..1
|
||||
target_note_start: int = 0
|
||||
target_note_end: int = 0
|
||||
target_start_s: float = 0.0
|
||||
target_end_s: float = 0.0
|
||||
path: list[tuple[int, int]] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def target_note_span(self) -> int:
|
||||
return max(0, self.target_note_end - self.target_note_start)
|
||||
|
||||
|
||||
def _norm_durs(mel: Melody) -> np.ndarray:
|
||||
d = mel.norm_durs()
|
||||
return np.maximum(d, 1e-3)
|
||||
|
||||
|
||||
def _cost_matrix(
|
||||
query: Melody, target: Melody, shift: float, cfg: Config
|
||||
) -> np.ndarray:
|
||||
"""构造 (Q, T) 的代价矩阵。"""
|
||||
q_pitch = query.midis + shift
|
||||
t_pitch = target.midis
|
||||
q_dur = _norm_durs(query)
|
||||
t_dur = _norm_durs(target)
|
||||
|
||||
pitch_cost = np.abs(q_pitch[:, None] - t_pitch[None, :]) - cfg.dtw_pitch_free_band
|
||||
np.clip(pitch_cost, 0.0, cfg.dtw_pitch_cap, out=pitch_cost)
|
||||
|
||||
dur_cost = np.abs(np.log(q_dur[:, None] / t_dur[None, :]))
|
||||
np.clip(dur_cost, 0.0, cfg.dtw_dur_cap, out=dur_cost)
|
||||
|
||||
return cfg.dtw_pitch_weight * pitch_cost + cfg.dtw_dur_weight * dur_cost
|
||||
|
||||
|
||||
def _dp_matrix(cost: np.ndarray) -> np.ndarray:
|
||||
"""开放起点的 DTW 累积代价矩阵,行内递推向量化。"""
|
||||
n_rows, n_cols = cost.shape
|
||||
D = np.empty((n_rows, n_cols), dtype=np.float64)
|
||||
D[0, :] = cost[0, :] # 起点开放:查询可对齐目标的任意位置
|
||||
|
||||
for i in range(1, n_rows):
|
||||
prev = D[i - 1]
|
||||
# A[j] = min(prev[j], prev[j-1]),其中 prev[-1] 视作 +inf
|
||||
shifted = np.empty_like(prev)
|
||||
shifted[0] = prev[0]
|
||||
shifted[1:] = prev[:-1]
|
||||
A = np.minimum(prev, shifted)
|
||||
|
||||
row_cost = cost[i]
|
||||
S = np.cumsum(row_cost)
|
||||
M = A - np.concatenate(([0.0], S[:-1]))
|
||||
B = np.minimum.accumulate(M)
|
||||
D[i] = B + S
|
||||
return D
|
||||
|
||||
|
||||
def _backtrack(D: np.ndarray, end_col: int) -> list[tuple[int, int]]:
|
||||
"""从 (最后一行, end_col) 回溯对齐路径。"""
|
||||
i = D.shape[0] - 1
|
||||
j = int(end_col)
|
||||
path: list[tuple[int, int]] = [(i, j)]
|
||||
while i > 0:
|
||||
if j == 0:
|
||||
i -= 1
|
||||
else:
|
||||
candidates = (D[i - 1, j - 1], D[i - 1, j], D[i, j - 1])
|
||||
best = int(np.argmin(candidates))
|
||||
if best == 0:
|
||||
i, j = i - 1, j - 1
|
||||
elif best == 1:
|
||||
i -= 1
|
||||
else:
|
||||
j -= 1
|
||||
path.append((i, j))
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
|
||||
def subsequence_dtw(
|
||||
query: Melody,
|
||||
target: Melody,
|
||||
*,
|
||||
shift: float = 0.0,
|
||||
cfg: Config = DEFAULT,
|
||||
need_path: bool = False,
|
||||
) -> Alignment:
|
||||
"""在固定移调量下做一次子序列 DTW。"""
|
||||
if query.n_notes == 0 or target.n_notes == 0:
|
||||
return Alignment(target.song_id, shift, float("inf"), 0.0)
|
||||
|
||||
cost = _cost_matrix(query, target, shift, cfg)
|
||||
D = _dp_matrix(cost)
|
||||
|
||||
end_col = int(np.argmin(D[-1, :]))
|
||||
total = float(D[-1, end_col])
|
||||
avg = total / max(query.n_notes, 1)
|
||||
sim = float(np.exp(-cfg.dtw_score_lambda * avg))
|
||||
|
||||
path: list[tuple[int, int]] = []
|
||||
if need_path:
|
||||
path = _backtrack(D, end_col)
|
||||
|
||||
if path:
|
||||
start_row, start_col = path[0]
|
||||
else:
|
||||
# 未取路径时,用累积矩阵反推起点:沿最优前驱回退
|
||||
start_row, start_col = 0, end_col
|
||||
i, j = D.shape[0] - 1, end_col
|
||||
while i > 0:
|
||||
if j == 0:
|
||||
i -= 1
|
||||
else:
|
||||
candidates = (D[i - 1, j - 1], D[i - 1, j], D[i, j - 1])
|
||||
best = int(np.argmin(candidates))
|
||||
i, j = (i - 1, j - 1) if best == 0 else ((i - 1, j) if best == 1 else (i, j - 1))
|
||||
start_row, start_col = i, j
|
||||
|
||||
col_start = int(start_col)
|
||||
col_end = int(end_col)
|
||||
return Alignment(
|
||||
song_id=target.song_id,
|
||||
shift=float(shift),
|
||||
cost=avg,
|
||||
sim=sim,
|
||||
target_note_start=col_start,
|
||||
target_note_end=col_end,
|
||||
target_start_s=float(target.starts[col_start]) if target.n_notes else 0.0,
|
||||
target_end_s=float(target.offsets[col_end]) if target.n_notes else 0.0,
|
||||
path=path,
|
||||
)
|
||||
|
||||
|
||||
def shift_candidates(
|
||||
query: Melody, target: Melody, cfg: Config = DEFAULT
|
||||
) -> list[int]:
|
||||
"""挑选候选移调量(整数半音)。
|
||||
|
||||
主估计是**中值音高差**:整条旋律被整体移调后,两边的中值音高差就等于
|
||||
移调量,这个估计对片段查询同样成立,而且天然覆盖跨八度的移调(±17 半音
|
||||
这种偏移如果只靠固定 ±12 的直方图搜索就会永远匹配不上)。
|
||||
|
||||
直方图重叠度作为补充,用于查询中个别音被 YIN 折叠了八度的情况。
|
||||
"""
|
||||
if query.n_notes == 0 or target.n_notes == 0:
|
||||
return [0]
|
||||
|
||||
q_med = float(np.median(query.midis))
|
||||
t_med = float(np.median(target.midis))
|
||||
base = int(round(t_med - q_med))
|
||||
|
||||
q_counts: dict[int, int] = defaultdict(int)
|
||||
t_counts: dict[int, int] = defaultdict(int)
|
||||
for v in np.rint(query.midis).astype(np.int64):
|
||||
q_counts[int(v)] += 1
|
||||
for v in np.rint(target.midis).astype(np.int64):
|
||||
t_counts[int(v)] += 1
|
||||
|
||||
rng = max(cfg.transpose_range, cfg.transpose_span + 1)
|
||||
scored: list[tuple[float, int]] = []
|
||||
for shift in range(-rng, rng + 1):
|
||||
overlap = sum(count * t_counts.get(pitch + shift, 0) for pitch, count in q_counts.items())
|
||||
scored.append((overlap, shift))
|
||||
scored.sort(key=lambda item: (-item[0], abs(item[1])))
|
||||
|
||||
candidates: set[int] = set()
|
||||
# 中值差邻域:吸收逐音抖动与半音取整误差
|
||||
for delta in range(-cfg.transpose_span, cfg.transpose_span + 1):
|
||||
candidates.add(base + delta)
|
||||
# 直方图 top 候选各扩 ±1
|
||||
for _, shift in scored[: cfg.transpose_candidates]:
|
||||
for delta in (-1, 0, 1):
|
||||
candidates.add(shift + delta)
|
||||
|
||||
order = {shift: rank for rank, (_, shift) in enumerate(scored)}
|
||||
return sorted(candidates, key=lambda s: (order.get(s, 10_000), abs(s)))
|
||||
|
||||
|
||||
def align(
|
||||
query: Melody,
|
||||
target: Melody,
|
||||
cfg: Config = DEFAULT,
|
||||
*,
|
||||
need_path: bool = False,
|
||||
shifts: list[int] | None = None,
|
||||
) -> Alignment:
|
||||
"""在候选移调量上搜索,返回代价最小的对齐。"""
|
||||
if shifts is None:
|
||||
shifts = shift_candidates(query, target, cfg)
|
||||
|
||||
best: Alignment | None = None
|
||||
for shift in shifts:
|
||||
result = subsequence_dtw(query, target, shift=shift, cfg=cfg, need_path=need_path)
|
||||
if best is None or result.cost < best.cost:
|
||||
best = result
|
||||
if best is None:
|
||||
return Alignment(target.song_id, 0.0, float("inf"), 0.0)
|
||||
return best
|
||||
Reference in New Issue
Block a user