Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
+257
@@ -0,0 +1,257 @@
|
||||
"""旋律表示:音符序列及其派生特征。
|
||||
|
||||
统一用「连续 MIDI 音高 + 起音时刻 + 时长」三个等长数组表示一条旋律。
|
||||
所有派生特征都设计成对**移调**或**速度**不敏感,这是哼唱检索的关键:
|
||||
|
||||
* ``intervals()`` 相邻音高差 → 移调不变
|
||||
* ``norm_durs()`` 时值除以自身中值 → 速度不变
|
||||
* ``contour()`` 上行/下行/保持的符号串 → 同时移调与速度不变
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable, Sequence
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
|
||||
__all__ = ["Melody", "fuse_repeated_notes"]
|
||||
|
||||
_EPS = 1e-9
|
||||
|
||||
|
||||
@dataclass
|
||||
class Melody:
|
||||
"""一条旋律的音符序列。"""
|
||||
|
||||
midis: np.ndarray
|
||||
starts: np.ndarray
|
||||
durs: np.ndarray
|
||||
song_id: str = ""
|
||||
title: str = ""
|
||||
meta: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.midis = np.asarray(self.midis, dtype=np.float64).reshape(-1)
|
||||
self.starts = np.asarray(self.starts, dtype=np.float64).reshape(-1)
|
||||
self.durs = np.asarray(self.durs, dtype=np.float64).reshape(-1)
|
||||
n = self.midis.size
|
||||
if self.starts.size != n or self.durs.size != n:
|
||||
raise ValueError(
|
||||
f"midis/starts/durs 长度必须一致:{self.midis.size}/{self.starts.size}/{self.durs.size}"
|
||||
)
|
||||
|
||||
# ---------------- 基本属性 ---------------- #
|
||||
def __len__(self) -> int:
|
||||
return int(self.midis.size)
|
||||
|
||||
@property
|
||||
def n_notes(self) -> int:
|
||||
return int(self.midis.size)
|
||||
|
||||
@property
|
||||
def is_empty(self) -> bool:
|
||||
return self.midis.size == 0
|
||||
|
||||
@property
|
||||
def offsets(self) -> np.ndarray:
|
||||
return self.starts + self.durs
|
||||
|
||||
@property
|
||||
def duration(self) -> float:
|
||||
return float(self.offsets.max()) if self.midis.size else 0.0
|
||||
|
||||
@property
|
||||
def median_pitch(self) -> float:
|
||||
return float(np.median(self.midis)) if self.midis.size else 0.0
|
||||
|
||||
# ---------------- 派生特征 ---------------- #
|
||||
def intervals(self, clip: float | None = None) -> np.ndarray:
|
||||
"""相邻音高差(半音),可截断以抑制离群跳变。"""
|
||||
if self.midis.size < 2:
|
||||
return np.zeros(0, dtype=np.float64)
|
||||
iv = np.diff(self.midis)
|
||||
if clip is not None:
|
||||
iv = np.clip(iv, -clip, clip)
|
||||
return iv
|
||||
|
||||
def norm_durs(self) -> np.ndarray:
|
||||
"""时值除以中值 → 速度归一化。"""
|
||||
if self.midis.size == 0:
|
||||
return np.zeros(0, dtype=np.float64)
|
||||
med = float(np.median(self.durs))
|
||||
if med <= _EPS:
|
||||
return np.ones_like(self.durs)
|
||||
return self.durs / med
|
||||
|
||||
def log_dur_ratios(self, clip: float = 2.5) -> np.ndarray:
|
||||
"""相邻时值比的对数,用于节奏码本。"""
|
||||
if self.durs.size < 2:
|
||||
return np.zeros(0, dtype=np.float64)
|
||||
ratio = np.log(np.maximum(self.durs[1:], _EPS) / np.maximum(self.durs[:-1], _EPS))
|
||||
return np.clip(ratio, -clip, clip)
|
||||
|
||||
def contour(self, jump: float = 0.75) -> str:
|
||||
"""音高走向串:``U`` 上行 / ``D`` 下行 / ``R`` 保持。长度 = 音符数 − 1。"""
|
||||
chars: list[str] = []
|
||||
for iv in self.intervals():
|
||||
if iv > jump:
|
||||
chars.append("U")
|
||||
elif iv < -jump:
|
||||
chars.append("D")
|
||||
else:
|
||||
chars.append("R")
|
||||
return "".join(chars)
|
||||
|
||||
def semitone_histogram(self) -> np.ndarray:
|
||||
"""音高(取整到半音)的直方图,用于估计移调量。"""
|
||||
if self.midis.size == 0:
|
||||
return np.zeros(1, dtype=np.float64)
|
||||
rounded = np.rint(self.midis).astype(np.int64)
|
||||
lo, hi = int(rounded.min()), int(rounded.max())
|
||||
hist = np.bincount(rounded - lo, minlength=hi - lo + 1).astype(np.float64)
|
||||
return hist
|
||||
|
||||
# ---------------- 变换 ---------------- #
|
||||
def transpose(self, semitones: float) -> "Melody":
|
||||
return Melody(
|
||||
self.midis + semitones, self.starts, self.durs, self.song_id, self.title, dict(self.meta)
|
||||
)
|
||||
|
||||
def scaled(self, factor: float) -> "Melody":
|
||||
"""时间轴缩放(速度变换)。"""
|
||||
return Melody(
|
||||
self.midis,
|
||||
self.starts * factor,
|
||||
self.durs * factor,
|
||||
self.song_id,
|
||||
self.title,
|
||||
dict(self.meta),
|
||||
)
|
||||
|
||||
def slice(self, start: int, stop: int) -> "Melody":
|
||||
"""按音符下标取连续片段(相对第一条音符重新计时)。"""
|
||||
start = max(0, int(start))
|
||||
stop = min(self.n_notes, int(stop))
|
||||
if stop <= start:
|
||||
return Melody.empty(self.song_id, self.title)
|
||||
sub = Melody(
|
||||
self.midis[start:stop],
|
||||
self.starts[start:stop],
|
||||
self.durs[start:stop],
|
||||
self.song_id,
|
||||
self.title,
|
||||
dict(self.meta),
|
||||
)
|
||||
sub.starts = sub.starts - sub.starts.min()
|
||||
return sub
|
||||
|
||||
def sorted_by_onset(self) -> "Melody":
|
||||
order = np.argsort(self.starts, kind="stable")
|
||||
return Melody(
|
||||
self.midis[order], self.starts[order], self.durs[order], self.song_id, self.title, dict(self.meta)
|
||||
)
|
||||
|
||||
# ---------------- 序列化 ---------------- #
|
||||
@classmethod
|
||||
def empty(cls, song_id: str = "", title: str = "") -> "Melody":
|
||||
z = np.zeros(0, dtype=np.float64)
|
||||
return cls(z, z.copy(), z.copy(), song_id, title)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"song_id": self.song_id,
|
||||
"title": self.title,
|
||||
"midis": [round(float(v), 4) for v in self.midis],
|
||||
"starts": [round(float(v), 4) for v in self.starts],
|
||||
"durs": [round(float(v), 4) for v in self.durs],
|
||||
"meta": self.meta,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> "Melody":
|
||||
return cls(
|
||||
data.get("midis", []),
|
||||
data.get("starts", []),
|
||||
data.get("durs", []),
|
||||
data.get("song_id", ""),
|
||||
data.get("title", ""),
|
||||
dict(data.get("meta", {})),
|
||||
)
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(self.to_dict(), ensure_ascii=False)
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, text: str) -> "Melody":
|
||||
return cls.from_dict(json.loads(text))
|
||||
|
||||
@classmethod
|
||||
def from_events(
|
||||
cls,
|
||||
events: Iterable[Sequence[float]],
|
||||
song_id: str = "",
|
||||
title: str = "",
|
||||
cfg: Config = DEFAULT,
|
||||
) -> "Melody":
|
||||
"""从 ``(onset_s, dur_s, midi)`` 事件序列构造。"""
|
||||
rows = [e for e in events if len(e) >= 3]
|
||||
if not rows:
|
||||
return cls.empty(song_id, title)
|
||||
arr = np.asarray(rows, dtype=np.float64)
|
||||
mel = cls(arr[:, 2], arr[:, 0], arr[:, 1], song_id, title)
|
||||
return mel.sorted_by_onset()
|
||||
|
||||
def summary(self) -> str:
|
||||
return (
|
||||
f"<Melody {self.song_id or '?'} n={self.n_notes} "
|
||||
f"dur={self.duration:.2f}s pitch={self.median_pitch:.1f}>"
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 重复音融合
|
||||
# --------------------------------------------------------------------------- #
|
||||
def fuse_repeated_notes(
|
||||
mel: Melody, cfg: Config = DEFAULT, *, enabled: bool = True
|
||||
) -> Melody:
|
||||
"""把相邻的同音高音符合并成一个。
|
||||
|
||||
动机:声学切分无法把一个持续音切成两半,而乐谱里反复音是分开写的。
|
||||
若只在查询端切分、不在曲库端合并,两者音符数就对不齐。因此在**两侧对称**
|
||||
地做重复音融合,让表示保持一致(合并后时长累加,节奏信息得以保留)。
|
||||
"""
|
||||
if not enabled or mel.n_notes < 2:
|
||||
return mel
|
||||
|
||||
midis: list[float] = [float(mel.midis[0])]
|
||||
starts: list[float] = [float(mel.starts[0])]
|
||||
durs: list[float] = [float(mel.durs[0])]
|
||||
|
||||
for i in range(1, mel.n_notes):
|
||||
pitch = float(mel.midis[i])
|
||||
onset = float(mel.starts[i])
|
||||
dur = float(mel.durs[i])
|
||||
prev_pitch = midis[-1]
|
||||
prev_end = starts[-1] + durs[-1]
|
||||
gap = onset - prev_end
|
||||
# 同音高且间隔足够小 → 视为同一个音的延续
|
||||
if abs(pitch - prev_pitch) < cfg.repeat_merge_semitones and gap < max(
|
||||
0.06, durs[-1] * 0.9
|
||||
):
|
||||
new_end = max(prev_end, onset + dur)
|
||||
durs[-1] = new_end - starts[-1]
|
||||
# 音高取时长加权平均,避免把持续音拉偏
|
||||
total = durs[-1]
|
||||
midis[-1] = (prev_pitch * (total - dur) + pitch * dur) / max(total, _EPS)
|
||||
else:
|
||||
midis.append(pitch)
|
||||
starts.append(onset)
|
||||
durs.append(dur)
|
||||
|
||||
if len(midis) == mel.n_notes:
|
||||
return mel
|
||||
return Melody(np.array(midis), np.array(starts), np.array(durs), mel.song_id, mel.title, dict(mel.meta))
|
||||
Reference in New Issue
Block a user