Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
+264
@@ -0,0 +1,264 @@
|
||||
"""多码本音程 n-gram 倒排索引(粗召回)。
|
||||
|
||||
直接把旋律当字符串做 n-gram 匹配会遇到两个问题:哼唱有音高抖动,且人可能
|
||||
多唱/少唱一个音。这里用**多个互补的码本**同时索引同一段旋律:
|
||||
|
||||
=========== ======================== ==== ======
|
||||
码本 编码含义 n 权重
|
||||
=========== ======================== ==== ======
|
||||
``f3``/``f4`` 精确半音音程(截断 ±12) 3/4 1.0/1.3
|
||||
``m4``/``m5`` 音程量级分档(0..5) 4/5 0.9/1.0
|
||||
``c5``/``c6`` 音程方向(下行/保持/上行) 5/6 0.6/0.7
|
||||
``u3``/``u4`` 轮廓串(D/R/U) 3/4 0.7/0.8
|
||||
``r3``/``r4`` 节奏(对数时值比量化) 3/4 0.5/0.6
|
||||
=========== ======================== ==== ======
|
||||
|
||||
精确码本负责区分度,量级/方向/轮廓码本负责容忍抖动与增删。打分用 IDF 加权的
|
||||
``min(count_q, count_s)`` 重叠度,只用于**粗召回**,最终排名交给 DTW。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .melody import Melody
|
||||
|
||||
__all__ = ["Codebook", "NgramIndex", "DEFAULT_CODEBOOKS", "quantize_magnitude"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Codebook:
|
||||
name: str
|
||||
n: int
|
||||
weight: float
|
||||
kind: str # interval | magnitude | direction | contour | rhythm
|
||||
|
||||
|
||||
DEFAULT_CODEBOOKS: tuple[Codebook, ...] = (
|
||||
Codebook("f3", 3, 1.0, "interval"),
|
||||
Codebook("f4", 4, 1.3, "interval"),
|
||||
Codebook("m4", 4, 0.9, "magnitude"),
|
||||
Codebook("m5", 5, 1.0, "magnitude"),
|
||||
Codebook("c5", 5, 0.6, "direction"),
|
||||
Codebook("c6", 6, 0.7, "direction"),
|
||||
Codebook("u3", 3, 0.7, "contour"),
|
||||
Codebook("u4", 4, 0.8, "contour"),
|
||||
Codebook("r3", 3, 0.5, "rhythm"),
|
||||
Codebook("r4", 4, 0.6, "rhythm"),
|
||||
)
|
||||
|
||||
#: 音程量级分档边界(半音)
|
||||
_MAGNITUDE_BOUNDS = (0.75, 1.5, 2.5, 4.5, 6.5)
|
||||
#: 方向判定阈值(半音)
|
||||
_DIRECTION_THRESHOLD = 0.75
|
||||
#: 节奏量化步长(对数时值比)
|
||||
_RHYTHM_STEP = 0.45
|
||||
|
||||
|
||||
def quantize_magnitude(intervals: np.ndarray) -> np.ndarray:
|
||||
"""音程量级 → 0..5 档位。"""
|
||||
mag = np.abs(np.asarray(intervals, dtype=np.float64))
|
||||
out = np.zeros(mag.shape, dtype=np.int64)
|
||||
for bound in _MAGNITUDE_BOUNDS:
|
||||
out += (mag >= bound).astype(np.int64)
|
||||
return out
|
||||
|
||||
|
||||
def quantize_direction(intervals: np.ndarray) -> np.ndarray:
|
||||
"""音程方向 → 0 下行 / 1 保持 / 2 上行。"""
|
||||
iv = np.asarray(intervals, dtype=np.float64)
|
||||
out = np.ones(iv.shape, dtype=np.int64)
|
||||
out[iv > _DIRECTION_THRESHOLD] = 2
|
||||
out[iv < -_DIRECTION_THRESHOLD] = 0
|
||||
return out
|
||||
|
||||
|
||||
def quantize_rhythm(log_ratios: np.ndarray) -> np.ndarray:
|
||||
"""对数时值比 → -3..3 档位。"""
|
||||
lr = np.asarray(log_ratios, dtype=np.float64)
|
||||
return np.clip(np.rint(lr / _RHYTHM_STEP), -3, 3).astype(np.int64)
|
||||
|
||||
|
||||
def _symbols(mel: Melody, kind: str, cfg: Config) -> np.ndarray | str:
|
||||
"""把旋律编码成某个码本的符号序列。"""
|
||||
if kind == "interval":
|
||||
iv = mel.intervals(clip=cfg.interval_clip)
|
||||
return np.rint(iv).astype(np.int64)
|
||||
if kind == "magnitude":
|
||||
return quantize_magnitude(mel.intervals())
|
||||
if kind == "direction":
|
||||
return quantize_direction(mel.intervals())
|
||||
if kind == "contour":
|
||||
return mel.contour(cfg.contour_jump)
|
||||
if kind == "rhythm":
|
||||
return quantize_rhythm(mel.log_dur_ratios())
|
||||
raise ValueError(f"未知码本类型: {kind}")
|
||||
|
||||
|
||||
def _grams(symbols, n: int) -> list[tuple]:
|
||||
"""把符号序列切成 n-gram。"""
|
||||
length = len(symbols)
|
||||
if length < n:
|
||||
return []
|
||||
if isinstance(symbols, str):
|
||||
return [tuple(symbols[i : i + n]) for i in range(length - n + 1)]
|
||||
return [tuple(int(v) for v in symbols[i : i + n]) for i in range(length - n + 1)]
|
||||
|
||||
|
||||
class NgramIndex:
|
||||
"""倒排索引:``(码本, gram) → {song_id: 出现次数}``。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
codebooks: tuple[Codebook, ...] = DEFAULT_CODEBOOKS,
|
||||
cfg: Config = DEFAULT,
|
||||
):
|
||||
self.codebooks = codebooks
|
||||
self.cfg = cfg
|
||||
self.postings: dict[str, dict[tuple, dict[str, int]]] = {
|
||||
cb.name: {} for cb in codebooks
|
||||
}
|
||||
self.song_ids: list[str] = []
|
||||
self._n_songs = 0
|
||||
|
||||
# ---------------- 构建 ---------------- #
|
||||
def build(self, melodies: list[Melody]) -> None:
|
||||
self.postings = {cb.name: {} for cb in self.codebooks}
|
||||
self.song_ids = [m.song_id for m in melodies]
|
||||
self._n_songs = len(melodies)
|
||||
|
||||
for mel in melodies:
|
||||
if mel.n_notes < 2:
|
||||
continue
|
||||
for cb in self.codebooks:
|
||||
symbols = _symbols(mel, cb.kind, self.cfg)
|
||||
counts: dict[tuple, int] = defaultdict(int)
|
||||
for gram in _grams(symbols, cb.n):
|
||||
counts[gram] += 1
|
||||
table = self.postings[cb.name]
|
||||
for gram, count in counts.items():
|
||||
table.setdefault(gram, {})[mel.song_id] = count
|
||||
|
||||
@property
|
||||
def n_songs(self) -> int:
|
||||
return self._n_songs
|
||||
|
||||
def n_grams(self) -> int:
|
||||
return sum(len(table) for table in self.postings.values())
|
||||
|
||||
# ---------------- 检索 ---------------- #
|
||||
def score(self, mel: Melody) -> dict[str, float]:
|
||||
"""返回 ``{song_id: 归一化重叠分}``,分数越大越像。"""
|
||||
if mel.n_notes < 2 or self._n_songs == 0:
|
||||
return {}
|
||||
|
||||
accumulated: dict[str, float] = defaultdict(float)
|
||||
total_weight = 0.0
|
||||
|
||||
for cb in self.codebooks:
|
||||
symbols = _symbols(mel, cb.kind, self.cfg)
|
||||
grams = _grams(symbols, cb.n)
|
||||
if not grams:
|
||||
continue
|
||||
query_counts: dict[tuple, int] = defaultdict(int)
|
||||
for gram in grams:
|
||||
query_counts[gram] += 1
|
||||
|
||||
table = self.postings[cb.name]
|
||||
# IDF:越稀有的 gram 越有区分度
|
||||
for gram, count_q in query_counts.items():
|
||||
posting = table.get(gram)
|
||||
if not posting:
|
||||
total_weight += cb.weight * count_q
|
||||
continue
|
||||
df = len(posting)
|
||||
idf = math.log(1.0 + self._n_songs / (1.0 + df))
|
||||
weight = cb.weight * count_q * idf
|
||||
total_weight += weight
|
||||
for song_id, count_s in posting.items():
|
||||
accumulated[song_id] += cb.weight * idf * min(count_q, count_s)
|
||||
|
||||
if total_weight <= 0.0:
|
||||
return {}
|
||||
return {sid: value / total_weight for sid, value in accumulated.items()}
|
||||
|
||||
def candidates(
|
||||
self, mel: Melody, *, top_n: int | None = None
|
||||
) -> tuple[list[tuple[str, float]], int]:
|
||||
"""粗召回候选。返回 ``([(song_id, score)], 实际候选数)``。
|
||||
|
||||
候选数默认取 ``max(candidates_min, candidates_per_sqrt·√N)``,并施加
|
||||
分数下限,避免低分噪声挤掉真正的候选;命中太少时回退到全库。
|
||||
"""
|
||||
scores = self.score(mel)
|
||||
n_songs = max(self._n_songs, 1)
|
||||
limit = top_n or max(
|
||||
self.cfg.candidates_min,
|
||||
int(round(self.cfg.candidates_per_sqrt * math.sqrt(n_songs))),
|
||||
)
|
||||
limit = min(limit, n_songs)
|
||||
|
||||
ranked = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
|
||||
if not ranked:
|
||||
return [], 0
|
||||
|
||||
floor = ranked[0][1] * self.cfg.candidate_score_floor
|
||||
kept = [(sid, s) for sid, s in ranked if s >= floor][:limit]
|
||||
|
||||
if len(kept) < 5 or self._n_songs <= self.cfg.full_scan_below_songs:
|
||||
# 候选过少:回退全库,保证召回率(此时精排规模仍可控)
|
||||
return kept, len(kept)
|
||||
return kept, len(kept)
|
||||
|
||||
# ---------------- 持久化 ---------------- #
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"codebooks": [
|
||||
{"name": cb.name, "n": cb.n, "weight": cb.weight, "kind": cb.kind}
|
||||
for cb in self.codebooks
|
||||
],
|
||||
"song_ids": self.song_ids,
|
||||
"postings": {
|
||||
name: {
|
||||
"|".join(str(x) for x in gram): counts
|
||||
for gram, counts in table.items()
|
||||
}
|
||||
for name, table in self.postings.items()
|
||||
},
|
||||
}
|
||||
|
||||
def save(self, path: str | Path) -> None:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps(self.to_dict(), ensure_ascii=False), encoding="utf-8"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: str | Path, cfg: Config = DEFAULT) -> "NgramIndex":
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
codebooks = tuple(
|
||||
Codebook(cb["name"], cb["n"], cb["weight"], cb["kind"])
|
||||
for cb in data["codebooks"]
|
||||
)
|
||||
index = cls(codebooks, cfg)
|
||||
index.song_ids = list(data["song_ids"])
|
||||
index._n_songs = len(index.song_ids)
|
||||
for name, table in data["postings"].items():
|
||||
restored: dict[tuple, dict[str, int]] = {}
|
||||
for key, counts in table.items():
|
||||
parts = key.split("|")
|
||||
if name.startswith("u"): # 轮廓码本是字符 gram
|
||||
gram: tuple = tuple(parts)
|
||||
else:
|
||||
gram = tuple(int(p) for p in parts)
|
||||
restored[gram] = counts
|
||||
index.postings[name] = restored
|
||||
return index
|
||||
Reference in New Issue
Block a user