Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
"""qbh —— 基于旋律的音乐哼唱检索(Query by Humming)核心库。
|
||||
|
||||
流水线::
|
||||
|
||||
音频 → 预处理 → YIN 基频提取 → 音符切分 → 旋律表示
|
||||
→ 多码本音程 n-gram 倒排索引(粗召回)
|
||||
→ 子序列 DTW + 移调搜索(精排)
|
||||
→ 分数融合 → Top-K 结果
|
||||
|
||||
模块划分见 docs/设计文档.md。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
|
||||
__all__ = ["Config", "DEFAULT", "__version__"]
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
"""音频输入、预处理与 WAV 编解码。
|
||||
|
||||
设计取舍:PCM WAV 用标准库 ``wave`` 读取,保证零第三方依赖也能跑通主链路;
|
||||
若环境里装了 ``soundfile``,则额外支持 MP3 / FLAC / OGG 等格式。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import math
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
|
||||
__all__ = [
|
||||
"read_audio",
|
||||
"read_wav_bytes",
|
||||
"write_wav",
|
||||
"encode_wav_bytes",
|
||||
"resample",
|
||||
"bandpass",
|
||||
"denoise",
|
||||
"normalize",
|
||||
"trim_silence",
|
||||
"preprocess",
|
||||
"rms_db",
|
||||
"frame_signal",
|
||||
]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 读取
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _pcm_to_float(raw: bytes, sampwidth: int, n_channels: int) -> np.ndarray:
|
||||
"""把交错 PCM 字节流转成 [-1, 1] 的 float32 单声道波形。"""
|
||||
if sampwidth == 1:
|
||||
# 8-bit WAV 是无符号偏移码
|
||||
data = np.frombuffer(raw, dtype=np.uint8).astype(np.float32)
|
||||
data = (data - 128.0) / 128.0
|
||||
elif sampwidth == 2:
|
||||
data = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
|
||||
elif sampwidth == 3:
|
||||
b = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3).astype(np.int32)
|
||||
# 小端 24-bit 有符号:补齐到 32-bit 再右移 8 位
|
||||
val = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
|
||||
val = np.where(val >= (1 << 23), val - (1 << 24), val)
|
||||
data = val.astype(np.float32) / 8388608.0
|
||||
elif sampwidth == 4:
|
||||
data = np.frombuffer(raw, dtype="<i4").astype(np.float32) / 2147483648.0
|
||||
else:
|
||||
raise ValueError(f"不支持的 WAV 位深: {sampwidth * 8} bit")
|
||||
|
||||
if n_channels > 1:
|
||||
data = data.reshape(-1, n_channels).mean(axis=1)
|
||||
return np.ascontiguousarray(data, dtype=np.float32)
|
||||
|
||||
|
||||
def read_wav_bytes(blob: bytes) -> tuple[np.ndarray, int]:
|
||||
"""解析内存中的 WAV 字节流,返回 (单声道 float32 波形, 采样率)。"""
|
||||
with wave.open(io.BytesIO(blob), "rb") as wf:
|
||||
sr = wf.getframerate()
|
||||
n_channels = wf.getnchannels()
|
||||
sampwidth = wf.getsampwidth()
|
||||
raw = wf.readframes(wf.getnframes())
|
||||
if not raw:
|
||||
raise ValueError("WAV 数据为空")
|
||||
return _pcm_to_float(raw, sampwidth, n_channels), sr
|
||||
|
||||
|
||||
def _read_via_soundfile(path: Path) -> tuple[np.ndarray, int]:
|
||||
import soundfile as sf # 可选依赖
|
||||
|
||||
data, sr = sf.read(str(path), dtype="float32", always_2d=False)
|
||||
if data.ndim > 1:
|
||||
data = data.mean(axis=1)
|
||||
return np.ascontiguousarray(data, dtype=np.float32), int(sr)
|
||||
|
||||
|
||||
def read_audio(source: str | Path | bytes) -> tuple[np.ndarray, int]:
|
||||
"""读取音频文件或字节流,返回 (单声道 float32 波形, 采样率)。
|
||||
|
||||
优先用标准库解析 WAV;失败且装了 soundfile 时,再尝试其它容器格式。
|
||||
"""
|
||||
if isinstance(source, bytes):
|
||||
try:
|
||||
return read_wav_bytes(source)
|
||||
except Exception:
|
||||
if not _has_soundfile():
|
||||
raise
|
||||
data, sr = _read_via_soundfile_bytes(source)
|
||||
return data, sr
|
||||
|
||||
path = Path(source)
|
||||
try:
|
||||
return read_wav_bytes(path.read_bytes())
|
||||
except Exception:
|
||||
if not _has_soundfile():
|
||||
raise
|
||||
return _read_via_soundfile(path)
|
||||
|
||||
|
||||
def _has_soundfile() -> bool:
|
||||
try:
|
||||
import soundfile # noqa: F401
|
||||
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _read_via_soundfile_bytes(blob: bytes) -> tuple[np.ndarray, int]:
|
||||
import soundfile as sf
|
||||
|
||||
data, sr = sf.read(io.BytesIO(blob), dtype="float32", always_2d=False)
|
||||
if data.ndim > 1:
|
||||
data = data.mean(axis=1)
|
||||
return np.ascontiguousarray(data, dtype=np.float32), int(sr)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 写出
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _float_to_pcm16(x: np.ndarray) -> bytes:
|
||||
clipped = np.clip(x, -1.0, 1.0)
|
||||
return (clipped * 32767.0).astype("<i2").tobytes()
|
||||
|
||||
|
||||
def encode_wav_bytes(x: np.ndarray, sr: int) -> bytes:
|
||||
"""把波形编码为 16-bit PCM WAV 字节流(用于 HTTP 响应 / 前端回放)。"""
|
||||
buf = io.BytesIO()
|
||||
with wave.open(buf, "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(int(sr))
|
||||
wf.writeframes(_float_to_pcm16(x))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def write_wav(path: str | Path, x: np.ndarray, sr: int) -> None:
|
||||
"""把波形写成 16-bit PCM WAV 文件。"""
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(encode_wav_bytes(x, sr))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 预处理
|
||||
# --------------------------------------------------------------------------- #
|
||||
def resample(x: np.ndarray, sr: int, target_sr: int) -> np.ndarray:
|
||||
"""多相滤波重采样(有理数比例),比线性插值保真。"""
|
||||
if sr == target_sr or x.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
g = math.gcd(int(sr), int(target_sr))
|
||||
up, down = target_sr // g, sr // g
|
||||
return signal.resample_poly(x, up, down).astype(np.float32)
|
||||
|
||||
|
||||
def bandpass(
|
||||
x: np.ndarray, sr: int, low_hz: float, high_hz: float, order: int = 4
|
||||
) -> np.ndarray:
|
||||
"""零相位 Butterworth 带通滤波。
|
||||
|
||||
哼唱的有效能量集中在 60–2000 Hz;低于 60 Hz 多为桌面震动/直流漂移,
|
||||
高于 2000 Hz 多为齿音与房间噪声。截止频率贴近 Nyquist 时自动退化为低通。
|
||||
"""
|
||||
if x.size < 32:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
nyq = sr / 2.0
|
||||
high = min(high_hz, nyq * 0.95)
|
||||
low = max(low_hz, 1e-3)
|
||||
if low >= high:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
sos = signal.butter(order, [low, high], btype="bandpass", fs=sr, output="sos")
|
||||
return signal.sosfiltfilt(sos, x).astype(np.float32)
|
||||
|
||||
|
||||
def denoise(x: np.ndarray, window: int = 3) -> np.ndarray:
|
||||
"""滑动均值去噪。窗口很小,只削高频毛刺,不破坏基频轮廓。"""
|
||||
if window <= 1 or x.size < window:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
kernel = np.ones(int(window), dtype=np.float32) / float(window)
|
||||
return np.convolve(x, kernel, mode="same").astype(np.float32)
|
||||
|
||||
|
||||
def rms_db(x: np.ndarray) -> float:
|
||||
"""整体 RMS 的分贝值;空信号或全零信号返回 -inf。"""
|
||||
if x.size == 0:
|
||||
return float("-inf")
|
||||
rms = float(np.sqrt(np.mean(np.square(x, dtype=np.float64))))
|
||||
if rms <= 0.0:
|
||||
return float("-inf")
|
||||
return 20.0 * math.log10(rms)
|
||||
|
||||
|
||||
def normalize(x: np.ndarray, target_rms: float = 0.06) -> np.ndarray:
|
||||
"""按 RMS 归一化并限幅,使音量不同的录音具有可比性。"""
|
||||
if x.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
rms = float(np.sqrt(np.mean(np.square(x, dtype=np.float64))))
|
||||
if rms < 1e-8:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
y = x * (target_rms / rms)
|
||||
return np.clip(y, -1.0, 1.0).astype(np.float32)
|
||||
|
||||
|
||||
def trim_silence(
|
||||
x: np.ndarray,
|
||||
sr: int,
|
||||
threshold_db: float = -45.0,
|
||||
padding_ms: float = 50.0,
|
||||
) -> np.ndarray:
|
||||
"""裁掉首尾静音(相对峰值门限),保留少量留白避免削掉起音。"""
|
||||
if x.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
win = max(1, int(0.02 * sr)) # 20 ms 能量窗
|
||||
n = x.size // win
|
||||
if n < 2:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
energy = np.square(x[: n * win], dtype=np.float64).reshape(n, win).mean(axis=1)
|
||||
peak = float(energy.max())
|
||||
if peak <= 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
floor = peak * (10.0 ** (threshold_db / 10.0))
|
||||
active = np.flatnonzero(energy >= floor)
|
||||
if active.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
pad = int(padding_ms / 1000.0 * sr)
|
||||
start = max(0, active[0] * win - pad)
|
||||
stop = min(x.size, (active[-1] + 1) * win + pad)
|
||||
return np.ascontiguousarray(x[start:stop], dtype=np.float32)
|
||||
|
||||
|
||||
def preprocess(
|
||||
x: np.ndarray,
|
||||
sr: int,
|
||||
cfg: Config = DEFAULT,
|
||||
*,
|
||||
do_bandpass: bool = True,
|
||||
do_denoise: bool = True,
|
||||
do_trim: bool = True,
|
||||
) -> np.ndarray:
|
||||
"""完整预处理链:重采样 → 去噪 → 带通 → 静音裁剪 → 归一化。
|
||||
|
||||
开关参数用于噪声鲁棒性实验中的“预处理开/关”对照。
|
||||
"""
|
||||
y = resample(x, sr, cfg.sample_rate)
|
||||
if do_denoise:
|
||||
y = denoise(y, cfg.denoise_window)
|
||||
if do_bandpass:
|
||||
y = bandpass(y, cfg.sample_rate, cfg.band_low_hz, cfg.band_high_hz, cfg.band_order)
|
||||
if do_trim:
|
||||
y = trim_silence(y, cfg.sample_rate, cfg.trim_threshold_db, cfg.trim_padding_ms)
|
||||
return normalize(y, cfg.target_rms)
|
||||
|
||||
|
||||
def frame_signal(x: np.ndarray, frame_len: int, hop: int) -> np.ndarray:
|
||||
"""分帧,返回形状 (n_frames, frame_len) 的视图(不足一帧则丢弃)。"""
|
||||
if x.size < frame_len:
|
||||
return np.empty((0, frame_len), dtype=np.float32)
|
||||
n_frames = 1 + (x.size - frame_len) // hop
|
||||
idx = np.arange(frame_len)[None, :] + hop * np.arange(n_frames)[:, None]
|
||||
return np.ascontiguousarray(x[idx])
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
"""大规模基准:合成曲库在 300 / 600 / 1000 首规模下的召回率与检索延迟。
|
||||
|
||||
关注两件事:
|
||||
|
||||
1. **粗召回率**是否随曲库增大而下降(倒排索引能否把答案保留在候选集里);
|
||||
2. **延迟**的扩展性——两级检索的耗时是否近似随 ``候选数 × DTW 规模`` 增长,
|
||||
而不是随曲库线性增长。
|
||||
|
||||
合成曲库与合成查询同源,因此准确率只作**相对参考**;真实基线请以
|
||||
``data/midi`` 的 27 首真实旋律为准(见 docs/评测报告.md)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import statistics
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .evaluate import make_query_specs, perturb_melody, synth_query_audio
|
||||
from .library import Library
|
||||
from .melody import Melody
|
||||
from .search import SearchEngine
|
||||
from .store import Store
|
||||
|
||||
__all__ = ["generate_melody", "run_scale_benchmark"]
|
||||
|
||||
_SCALES: dict[str, list[int]] = {
|
||||
"major": [0, 2, 4, 5, 7, 9, 11],
|
||||
"minor": [0, 2, 3, 5, 7, 8, 10],
|
||||
"pentatonic": [0, 2, 4, 7, 9],
|
||||
}
|
||||
|
||||
_RHYTHMS: tuple[tuple[float, ...], ...] = (
|
||||
(1.0, 1.0, 1.0, 1.0),
|
||||
(1.5, 0.5, 1.0, 1.0),
|
||||
(0.5, 0.5, 1.0, 2.0),
|
||||
(2.0, 1.0, 1.0),
|
||||
(1.0, 0.5, 0.5, 2.0),
|
||||
(0.75, 0.25, 1.0, 2.0),
|
||||
)
|
||||
|
||||
|
||||
def generate_melody(
|
||||
rng: np.random.Generator,
|
||||
song_id: str,
|
||||
*,
|
||||
n_notes: int = 32,
|
||||
root: int = 60,
|
||||
scale: str = "major",
|
||||
bpm: float = 100.0,
|
||||
) -> Melody:
|
||||
"""生成一条有动机重复与变化的结构化旋律。"""
|
||||
steps = _SCALES[scale]
|
||||
motif_len = int(rng.integers(3, 7))
|
||||
motif = [int(rng.integers(0, len(steps))) for _ in range(motif_len)]
|
||||
|
||||
degrees: list[int] = []
|
||||
while len(degrees) < n_notes:
|
||||
transposition = int(rng.integers(-2, 3))
|
||||
for degree in motif:
|
||||
if len(degrees) >= n_notes:
|
||||
break
|
||||
value = degree + transposition
|
||||
if rng.random() < 0.15: # 局部变化
|
||||
value += int(rng.integers(-1, 2))
|
||||
degrees.append(value)
|
||||
|
||||
midis: list[float] = []
|
||||
for degree in degrees:
|
||||
octave, index = divmod(degree, len(steps))
|
||||
midi = root + 12 * octave + steps[index]
|
||||
while midi < 45:
|
||||
midi += 12
|
||||
while midi > 84:
|
||||
midi -= 12
|
||||
midis.append(float(midi))
|
||||
|
||||
beat = 60.0 / bpm
|
||||
pattern = _RHYTHMS[int(rng.integers(0, len(_RHYTHMS)))]
|
||||
starts: list[float] = []
|
||||
durs: list[float] = []
|
||||
cursor = 0.0
|
||||
for i in range(len(midis)):
|
||||
beats = pattern[i % len(pattern)]
|
||||
starts.append(cursor)
|
||||
durs.append(beats * beat)
|
||||
cursor += beats * beat
|
||||
|
||||
return Melody(np.array(midis), np.array(starts), np.array(durs), song_id, song_id)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScaleResult:
|
||||
n_songs: int
|
||||
n_queries: int
|
||||
n_grams: int
|
||||
build_seconds: float
|
||||
index_seconds: float
|
||||
candidate_recall: float
|
||||
top1: float
|
||||
top5: float
|
||||
mrr: float
|
||||
mean_candidates: float
|
||||
p50_ms: float
|
||||
p95_ms: float
|
||||
mean_ms: float
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"n_songs": self.n_songs,
|
||||
"n_queries": self.n_queries,
|
||||
"n_grams": self.n_grams,
|
||||
"build_seconds": round(self.build_seconds, 2),
|
||||
"index_seconds": round(self.index_seconds, 3),
|
||||
"candidate_recall": round(self.candidate_recall, 4),
|
||||
"top1": round(self.top1, 4),
|
||||
"top5": round(self.top5, 4),
|
||||
"mrr": round(self.mrr, 4),
|
||||
"mean_candidates": round(self.mean_candidates, 1),
|
||||
"p50_ms": round(self.p50_ms, 2),
|
||||
"p95_ms": round(self.p95_ms, 2),
|
||||
"mean_ms": round(self.mean_ms, 2),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class BenchReport:
|
||||
sizes: list[int]
|
||||
results: list[ScaleResult] = field(default_factory=list)
|
||||
difficulty: str = "normal"
|
||||
seed: int = 20260908
|
||||
config: dict = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"sizes": self.sizes,
|
||||
"difficulty": self.difficulty,
|
||||
"seed": self.seed,
|
||||
"config": self.config,
|
||||
"results": [r.to_dict() for r in self.results],
|
||||
}
|
||||
|
||||
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, indent=2), encoding="utf-8")
|
||||
|
||||
def markdown_table(self) -> str:
|
||||
head = (
|
||||
"| 曲库规模 | n-gram 数 | 候选召回率 | Top-1 | Top-5 | MRR | "
|
||||
"平均候选数 | 延迟 p50 | 延迟 p95 | 索引构建 |\n"
|
||||
"|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|\n"
|
||||
)
|
||||
rows = [
|
||||
f"| {r.n_songs} | {r.n_grams} | {r.candidate_recall*100:.1f}% | "
|
||||
f"{r.top1*100:.1f}% | {r.top5*100:.1f}% | {r.mrr:.3f} | "
|
||||
f"{r.mean_candidates:.0f} | {r.p50_ms:.0f} ms | {r.p95_ms:.0f} ms | "
|
||||
f"{r.index_seconds*1000:.0f} ms |"
|
||||
for r in self.results
|
||||
]
|
||||
return head + "\n".join(rows)
|
||||
|
||||
|
||||
def run_scale_benchmark(
|
||||
sizes: tuple[int, ...] = (300, 600, 1000),
|
||||
*,
|
||||
n_queries_per_size: int = 60,
|
||||
difficulty: str = "normal",
|
||||
seed: int = 20260908,
|
||||
cfg: Config = DEFAULT,
|
||||
verbose: bool = True,
|
||||
) -> BenchReport:
|
||||
"""在多个曲库规模上跑基准测试。"""
|
||||
report = BenchReport(sizes=list(sizes), difficulty=difficulty, seed=seed, config=cfg.to_dict())
|
||||
rng = np.random.default_rng(seed)
|
||||
|
||||
for size in sizes:
|
||||
work_dir = Path(tempfile.mkdtemp(prefix=f"qbh_bench_{size}_"))
|
||||
try:
|
||||
started = time.perf_counter()
|
||||
store = Store(work_dir / "bench.db")
|
||||
library = Library(
|
||||
store, cfg, midi_dir=work_dir / "midi", audio_dir=work_dir / "audio"
|
||||
)
|
||||
scales = ("major", "minor", "pentatonic")
|
||||
for i in range(size):
|
||||
melody = generate_melody(
|
||||
rng,
|
||||
f"s{i:05d}",
|
||||
n_notes=int(rng.integers(20, 48)),
|
||||
root=int(rng.integers(55, 68)),
|
||||
scale=scales[int(rng.integers(0, len(scales)))],
|
||||
bpm=float(rng.uniform(70, 150)),
|
||||
)
|
||||
library.add_melody(melody, song_id=melody.song_id, title=melody.title,
|
||||
source="synthetic", render_audio=False)
|
||||
build_seconds = time.perf_counter() - started
|
||||
|
||||
started = time.perf_counter()
|
||||
engine = SearchEngine(library, cfg)
|
||||
index_seconds = time.perf_counter() - started
|
||||
|
||||
melodies = library.melodies()
|
||||
specs = make_query_specs(
|
||||
melodies, n_per_song=1, difficulty=difficulty, seed=seed + size
|
||||
)[:n_queries_per_size]
|
||||
|
||||
ranks: list[int] = []
|
||||
latencies: list[float] = []
|
||||
candidate_hits = 0
|
||||
n_candidates: list[int] = []
|
||||
|
||||
for spec in specs:
|
||||
source = next(m for m in melodies if m.song_id == spec.song_id)
|
||||
truth = perturb_melody(source, spec, cfg)
|
||||
audio = synth_query_audio(truth, spec, cfg)
|
||||
result, _ = engine.search_audio(audio, cfg.sample_rate, top_k=10, cfg=cfg)
|
||||
|
||||
cand_ids = {sid for sid, _ in engine.coarse_candidates(result.query)}
|
||||
candidate_hits += int(spec.song_id in cand_ids)
|
||||
n_candidates.append(result.n_candidates)
|
||||
latencies.append(result.elapsed_ms)
|
||||
|
||||
rank = next(
|
||||
(i + 1 for i, h in enumerate(result.hits) if h.song_id == spec.song_id), 0
|
||||
)
|
||||
ranks.append(rank)
|
||||
|
||||
n = max(len(specs), 1)
|
||||
lat = np.asarray(latencies, dtype=np.float64)
|
||||
result = ScaleResult(
|
||||
n_songs=size,
|
||||
n_queries=len(specs),
|
||||
n_grams=engine.index.n_grams(),
|
||||
build_seconds=build_seconds,
|
||||
index_seconds=index_seconds,
|
||||
candidate_recall=candidate_hits / n,
|
||||
top1=sum(1 for r in ranks if r == 1) / n,
|
||||
top5=sum(1 for r in ranks if 0 < r <= 5) / n,
|
||||
mrr=sum((1.0 / r) for r in ranks if r > 0) / n,
|
||||
mean_candidates=float(statistics.fmean(n_candidates)) if n_candidates else 0.0,
|
||||
p50_ms=float(np.percentile(lat, 50)) if lat.size else 0.0,
|
||||
p95_ms=float(np.percentile(lat, 95)) if lat.size else 0.0,
|
||||
mean_ms=float(lat.mean()) if lat.size else 0.0,
|
||||
)
|
||||
report.results.append(result)
|
||||
if verbose:
|
||||
print(
|
||||
f" 曲库 {size:>4} 首 · n-gram {result.n_grams:>6} · "
|
||||
f"召回率 {result.candidate_recall*100:5.1f}% · Top-1 {result.top1*100:5.1f}% · "
|
||||
f"候选 {result.mean_candidates:5.1f} · 延迟 p50 {result.p50_ms:6.1f}ms "
|
||||
f"p95 {result.p95_ms:6.1f}ms"
|
||||
)
|
||||
store.close()
|
||||
finally:
|
||||
shutil.rmtree(work_dir, ignore_errors=True)
|
||||
|
||||
return report
|
||||
@@ -0,0 +1,86 @@
|
||||
"""集中管理全部算法阈值。
|
||||
|
||||
所有可调参数都收在这里,便于复现实验、做消融与参数扫描。
|
||||
`Config` 是冻结 dataclass,用 `with_()` 派生变体,避免全局可变状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, fields, replace
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Config:
|
||||
# ---------- 采样与预处理 ----------
|
||||
sample_rate: int = 16_000
|
||||
band_low_hz: float = 60.0
|
||||
band_high_hz: float = 2_000.0
|
||||
band_order: int = 4
|
||||
denoise_window: int = 3
|
||||
target_rms: float = 0.06
|
||||
trim_threshold_db: float = -45.0
|
||||
trim_padding_ms: float = 50.0
|
||||
|
||||
# ---------- 分帧 ----------
|
||||
frame_ms: float = 48.0
|
||||
hop_ms: float = 10.0
|
||||
|
||||
# ---------- YIN 基频提取 ----------
|
||||
fmin_hz: float = 70.0
|
||||
fmax_hz: float = 1_000.0
|
||||
yin_threshold: float = 0.12
|
||||
yin_max_cmndf: float = 0.55
|
||||
voicing_conf: float = 0.5
|
||||
voicing_db_below_peak: float = -45.0
|
||||
median_filter_frames: int = 7
|
||||
octave_fold_low: float = 9.0
|
||||
octave_fold_high: float = 15.0
|
||||
|
||||
# ---------- 音符切分 ----------
|
||||
split_semitones: float = 0.8
|
||||
min_note_ms: float = 70.0
|
||||
bridge_gap_ms: float = 60.0
|
||||
merge_semitones: float = 0.5
|
||||
repeat_merge_semitones: float = 0.35
|
||||
max_notes: int = 600
|
||||
|
||||
# ---------- 音程 / 轮廓编码 ----------
|
||||
interval_clip: float = 12.0
|
||||
contour_jump: float = 0.75
|
||||
|
||||
# ---------- 粗召回索引 ----------
|
||||
candidates_min: int = 40
|
||||
candidates_per_sqrt: float = 7.0
|
||||
candidate_score_floor: float = 0.10
|
||||
full_scan_below_songs: int = 60
|
||||
contour_variants_max: int = 40
|
||||
|
||||
# ---------- 精排 DTW ----------
|
||||
dtw_pitch_free_band: float = 0.3
|
||||
dtw_pitch_cap: float = 10.0
|
||||
dtw_dur_cap: float = 2.5
|
||||
dtw_pitch_weight: float = 1.0
|
||||
dtw_dur_weight: float = 0.7
|
||||
transpose_range: int = 24
|
||||
transpose_span: int = 4
|
||||
transpose_candidates: int = 8
|
||||
dtw_score_lambda: float = 0.6
|
||||
dtw_max_cells: int = 4_000_000
|
||||
|
||||
# ---------- 分数融合 ----------
|
||||
w_dtw: float = 0.80
|
||||
w_index: float = 0.20
|
||||
|
||||
# ---------- 检索 ----------
|
||||
top_k: int = 10
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转为普通字典,便于写入评测报告 / 前端展示。"""
|
||||
return {f.name: getattr(self, f.name) for f in fields(self)}
|
||||
|
||||
def with_(self, **kwargs) -> "Config":
|
||||
"""派生一个只改动指定字段的新配置。"""
|
||||
return replace(self, **kwargs)
|
||||
|
||||
|
||||
DEFAULT = Config()
|
||||
+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
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
"""评测:合成「像人哼唱」的查询,端到端度量检索性能。
|
||||
|
||||
为什么要自己合成查询:公开的哼唱数据集(如 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
|
||||
+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
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
"""曲库管理:把内置曲谱、MIDI 文件与导入的音频统一成可检索的曲库。
|
||||
|
||||
曲库构建流程::
|
||||
|
||||
内置曲谱 ─┐
|
||||
MIDI 文件 ─┼─→ 旋律特征 ─→ SQLite(melodies) ─→ 倒排索引
|
||||
外部导入 ─┘ └─→ 合成示范音频 ─→ data/audio/*.wav
|
||||
|
||||
同名曲目会去重:以真实 MIDI 为准,避免内置曲谱与 MIDI 版本互为近邻干扰检索。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .melody import Melody, fuse_repeated_notes
|
||||
from .midiio import read_midi_melody
|
||||
from .scores import BUILTIN_SCORES
|
||||
from .store import SongRecord, Store
|
||||
from .synth import render_melody
|
||||
|
||||
__all__ = ["Library", "BuildReport", "MIDI_TITLES"]
|
||||
|
||||
#: 27 首真实 MIDI 的中文标题(其余由文件名兜底)
|
||||
MIDI_TITLES: dict[str, str] = {
|
||||
"auld_lang_syne": "友谊地久天长",
|
||||
"fen_shua_jiang": "粉刷匠",
|
||||
"frere_jacques": "两只老虎",
|
||||
"fur_elise": "致爱丽丝",
|
||||
"greensleeves": "绿袖子",
|
||||
"haenschen_klein": "小小少年",
|
||||
"happy_birthday": "生日快乐",
|
||||
"jingle_bells": "铃儿响叮当",
|
||||
"london_bridge": "伦敦桥",
|
||||
"mary_had_little_lamb": "玛丽有只小羊羔",
|
||||
"molihua": "茉莉花",
|
||||
"ode_to_joy": "欢乐颂",
|
||||
"row_your_boat": "划船歌",
|
||||
"silent_night": "平安夜",
|
||||
"song_bie": "送别",
|
||||
"swan_lake": "天鹅湖",
|
||||
"turkish_march": "土耳其进行曲",
|
||||
"twinkle_twinkle": "小星星",
|
||||
"vivaldi_spring": "春(第一乐章)",
|
||||
"when_the_saints": "圣者行进",
|
||||
"william_tell_gallop": "威廉·退尔序曲",
|
||||
"penta_01": "五声音阶旋律 #1",
|
||||
"penta_02": "五声音阶旋律 #2",
|
||||
"penta_03": "五声音阶旋律 #3",
|
||||
"penta_04": "五声音阶旋律 #4",
|
||||
"penta_05": "五声音阶旋律 #5",
|
||||
"penta_06": "五声音阶旋律 #6",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class BuildReport:
|
||||
"""曲库构建结果摘要。"""
|
||||
|
||||
n_builtin: int = 0
|
||||
n_midi: int = 0
|
||||
n_skipped_duplicates: int = 0
|
||||
n_total: int = 0
|
||||
n_audio: int = 0
|
||||
seconds: float = 0.0
|
||||
built_at: str = ""
|
||||
errors: list[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"n_builtin": self.n_builtin,
|
||||
"n_midi": self.n_midi,
|
||||
"n_skipped_duplicates": self.n_skipped_duplicates,
|
||||
"n_total": self.n_total,
|
||||
"n_audio": self.n_audio,
|
||||
"seconds": round(self.seconds, 2),
|
||||
"built_at": self.built_at,
|
||||
"errors": self.errors,
|
||||
}
|
||||
|
||||
|
||||
class Library:
|
||||
"""曲库:负责构建、查询与示范音频管理。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: Store,
|
||||
cfg: Config = DEFAULT,
|
||||
*,
|
||||
midi_dir: str | Path = "data/midi",
|
||||
audio_dir: str | Path = "data/audio",
|
||||
):
|
||||
self.store = store
|
||||
self.cfg = cfg
|
||||
self.midi_dir = Path(midi_dir)
|
||||
self.audio_dir = Path(audio_dir)
|
||||
self.audio_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._melody_cache: list[Melody] | None = None
|
||||
|
||||
# ---------------- 构建 ---------------- #
|
||||
def build(
|
||||
self,
|
||||
*,
|
||||
include_builtin: bool = True,
|
||||
include_midi: bool = True,
|
||||
render_audio: bool = True,
|
||||
dedup: bool = True,
|
||||
force: bool = False,
|
||||
) -> BuildReport:
|
||||
"""重建曲库。``force=False`` 时若已有曲库则直接复用。"""
|
||||
started = datetime.now()
|
||||
report = BuildReport(built_at=started.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
|
||||
if not force and self.store.count_songs() > 0:
|
||||
report.n_total = self.store.count_songs()
|
||||
report.n_audio = len(list(self.audio_dir.glob("*.wav")))
|
||||
report.seconds = (datetime.now() - started).total_seconds()
|
||||
return report
|
||||
|
||||
if force:
|
||||
self.store.clear_library()
|
||||
|
||||
midi_melodies: list[Melody] = []
|
||||
if include_midi and self.midi_dir.exists():
|
||||
for path in sorted(self.midi_dir.glob("*.mid")):
|
||||
stem = path.stem
|
||||
title = MIDI_TITLES.get(stem, stem)
|
||||
try:
|
||||
mel = read_midi_melody(path, song_id=f"midi_{stem}", title=title)
|
||||
except Exception as exc: # 单文件损坏不应中断整库构建
|
||||
report.errors.append(f"{path.name}: {exc}")
|
||||
continue
|
||||
if mel.n_notes < 4:
|
||||
report.errors.append(f"{path.name}: 音符过少({mel.n_notes})")
|
||||
continue
|
||||
mel.meta["source"] = "midi"
|
||||
mel.meta["origin"] = "磁盘 MIDI 曲库"
|
||||
mel.meta["tags"] = ["真实MIDI"]
|
||||
midi_melodies.append(mel)
|
||||
|
||||
midi_stems = {m.song_id.removeprefix("midi_") for m in midi_melodies}
|
||||
|
||||
builtin_melodies: list[Melody] = []
|
||||
if include_builtin:
|
||||
for score in BUILTIN_SCORES:
|
||||
if dedup and score.id in midi_stems:
|
||||
report.n_skipped_duplicates += 1
|
||||
continue
|
||||
builtin_melodies.append(score.melody())
|
||||
|
||||
report.n_midi = len(midi_melodies)
|
||||
report.n_builtin = len(builtin_melodies)
|
||||
|
||||
# 曲库侧也要做重复音融合:查询端(声学切分)无法把一个持续音切成两半,
|
||||
# 若曲库保留乐谱里的重复音,两侧音符数就会系统性错位。
|
||||
all_melodies = [
|
||||
fuse_repeated_notes(mel, self.cfg)
|
||||
for mel in midi_melodies + builtin_melodies
|
||||
]
|
||||
|
||||
records: list[SongRecord] = []
|
||||
for mel in all_melodies:
|
||||
records.append(
|
||||
SongRecord(
|
||||
id=mel.song_id,
|
||||
title=mel.title,
|
||||
origin=str(mel.meta.get("origin", "")),
|
||||
tags=tuple(mel.meta.get("tags", [])),
|
||||
source=str(mel.meta.get("source", "")),
|
||||
midi_file=(
|
||||
f"midi/{mel.song_id.removeprefix('midi_')}.mid"
|
||||
if mel.song_id.startswith("midi_")
|
||||
else ""
|
||||
),
|
||||
audio_file=f"audio/{mel.song_id}.wav" if render_audio else "",
|
||||
n_notes=mel.n_notes,
|
||||
duration=round(mel.duration, 3),
|
||||
median_pitch=round(mel.median_pitch, 2),
|
||||
)
|
||||
)
|
||||
|
||||
for record in records:
|
||||
self.store.upsert_song(record)
|
||||
self.store.set_melodies(all_melodies)
|
||||
self.store.set_meta("library_built_at", report.built_at)
|
||||
self.store.set_meta("library_config", self.cfg.to_dict())
|
||||
|
||||
if render_audio:
|
||||
for mel in all_melodies:
|
||||
try:
|
||||
self._render_audio(mel)
|
||||
report.n_audio += 1
|
||||
except Exception as exc:
|
||||
report.errors.append(f"audio {mel.song_id}: {exc}")
|
||||
|
||||
self._melody_cache = None
|
||||
report.n_total = len(records)
|
||||
report.seconds = (datetime.now() - started).total_seconds()
|
||||
return report
|
||||
|
||||
# ---------------- 示范音频 ---------------- #
|
||||
def _render_audio(self, mel: Melody, *, force: bool = False) -> Path:
|
||||
path = self.audio_dir / f"{mel.song_id}.wav"
|
||||
if path.exists() and not force:
|
||||
return path
|
||||
from .audio import write_wav
|
||||
|
||||
wave = render_melody(mel, self.cfg.sample_rate, timbre="song", seed=hash(mel.song_id) % 2**31)
|
||||
write_wav(path, wave, self.cfg.sample_rate)
|
||||
return path
|
||||
|
||||
def audio_path(self, song_id: str) -> Path | None:
|
||||
path = self.audio_dir / f"{song_id}.wav"
|
||||
if path.exists():
|
||||
return path
|
||||
mel = self.store.get_melody(song_id)
|
||||
if mel is None:
|
||||
return None
|
||||
try:
|
||||
return self._render_audio(mel)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# ---------------- 查询 ---------------- #
|
||||
def songs(self) -> list[SongRecord]:
|
||||
return self.store.list_songs()
|
||||
|
||||
def get_song(self, song_id: str) -> SongRecord | None:
|
||||
return self.store.get_song(song_id)
|
||||
|
||||
def count(self) -> int:
|
||||
return self.store.count_songs()
|
||||
|
||||
def melodies(self, *, refresh: bool = False) -> list[Melody]:
|
||||
if self._melody_cache is None or refresh:
|
||||
self._melody_cache = self.store.all_melodies()
|
||||
return self._melody_cache
|
||||
|
||||
def get_melody(self, song_id: str) -> Melody | None:
|
||||
return self.store.get_melody(song_id)
|
||||
|
||||
def title_of(self, song_id: str) -> str:
|
||||
record = self.store.get_song(song_id)
|
||||
return record.title if record else song_id
|
||||
|
||||
# ---------------- 增删 ---------------- #
|
||||
def add_melody(
|
||||
self,
|
||||
mel: Melody,
|
||||
*,
|
||||
song_id: str,
|
||||
title: str = "",
|
||||
origin: str = "",
|
||||
tags: tuple[str, ...] = (),
|
||||
source: str = "import",
|
||||
render_audio: bool = True,
|
||||
) -> SongRecord:
|
||||
"""向曲库添加/覆盖一条旋律。"""
|
||||
mel = fuse_repeated_notes(mel, self.cfg)
|
||||
mel.song_id = song_id
|
||||
mel.title = title or song_id
|
||||
mel.meta.update({"origin": origin, "tags": list(tags), "source": source})
|
||||
record = SongRecord(
|
||||
id=song_id,
|
||||
title=mel.title,
|
||||
origin=origin,
|
||||
tags=tuple(tags),
|
||||
source=source,
|
||||
audio_file=f"audio/{song_id}.wav" if render_audio else "",
|
||||
n_notes=mel.n_notes,
|
||||
duration=round(mel.duration, 3),
|
||||
median_pitch=round(mel.median_pitch, 2),
|
||||
)
|
||||
self.store.upsert_song(record)
|
||||
self.store.set_melody(mel)
|
||||
if render_audio:
|
||||
try:
|
||||
self._render_audio(mel, force=True)
|
||||
except Exception:
|
||||
pass
|
||||
self._melody_cache = None
|
||||
return record
|
||||
|
||||
def add_midi_file(
|
||||
self, path: str | Path, *, song_id: str | None = None, title: str = ""
|
||||
) -> SongRecord:
|
||||
"""导入一个 MIDI 文件作为曲目。"""
|
||||
path = Path(path)
|
||||
sid = song_id or f"midi_{path.stem}"
|
||||
mel = read_midi_melody(path, song_id=sid, title=title or MIDI_TITLES.get(path.stem, path.stem))
|
||||
if mel.n_notes < 4:
|
||||
raise ValueError(f"MIDI 中有效音符过少({mel.n_notes})")
|
||||
return self.add_melody(
|
||||
mel,
|
||||
song_id=sid,
|
||||
title=mel.title,
|
||||
origin="导入 MIDI",
|
||||
tags=("导入",),
|
||||
source="midi",
|
||||
)
|
||||
|
||||
def delete(self, song_id: str) -> bool:
|
||||
audio = self.audio_dir / f"{song_id}.wav"
|
||||
if audio.exists():
|
||||
try:
|
||||
audio.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
self._melody_cache = None
|
||||
return self.store.delete_song(song_id)
|
||||
|
||||
# ---------------- 导出 ---------------- #
|
||||
def dump_index_payload(self) -> dict:
|
||||
return {
|
||||
"n_songs": self.count(),
|
||||
"built_at": self.store.get_meta("library_built_at"),
|
||||
"songs": [
|
||||
{
|
||||
"id": r.id,
|
||||
"title": r.title,
|
||||
"origin": r.origin,
|
||||
"tags": list(r.tags),
|
||||
"source": r.source,
|
||||
"n_notes": r.n_notes,
|
||||
"duration": r.duration,
|
||||
}
|
||||
for r in self.songs()
|
||||
],
|
||||
}
|
||||
|
||||
def save_index_payload(self, path: str | Path) -> None:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps(self.dump_index_payload(), ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
+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))
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
"""最小化的 MIDI 读写(不依赖 mido / pretty_midi)。
|
||||
|
||||
只实现本项目需要的部分:标准 MIDI 文件的头块、轨道块、变速(running status)、
|
||||
note-on / note-off、以及 tempo / 轨道名元事件。够用来导入旋律 MIDI,
|
||||
也能把内置曲库导出成 MIDI 便于外部核对。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .melody import Melody
|
||||
|
||||
__all__ = ["MidiNote", "MidiTrack", "MidiFile", "read_midi", "write_midi", "melody_from_midi"]
|
||||
|
||||
_DEFAULT_TEMPO_US = 500_000 # 120 BPM
|
||||
|
||||
|
||||
@dataclass
|
||||
class MidiNote:
|
||||
pitch: int
|
||||
start: float # 秒
|
||||
dur: float # 秒
|
||||
velocity: int = 80
|
||||
|
||||
@property
|
||||
def end(self) -> float:
|
||||
return self.start + self.dur
|
||||
|
||||
|
||||
@dataclass
|
||||
class MidiTrack:
|
||||
name: str = ""
|
||||
program: int = 0
|
||||
channel: int = 0
|
||||
notes: list[MidiNote] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def median_pitch(self) -> float:
|
||||
return float(np.median([n.pitch for n in self.notes])) if self.notes else 0.0
|
||||
|
||||
@property
|
||||
def polyphony(self) -> float:
|
||||
"""同时发声音符的平均数量,1.0 表示严格单音。"""
|
||||
if not self.notes:
|
||||
return 0.0
|
||||
events: list[tuple[float, int]] = []
|
||||
for n in self.notes:
|
||||
events.append((n.start, 1))
|
||||
events.append((n.end, -1))
|
||||
events.sort(key=lambda e: (e[0], e[1]))
|
||||
active = 0
|
||||
peak = 0
|
||||
for _, delta in events:
|
||||
active += delta
|
||||
peak = max(peak, active)
|
||||
return float(peak)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MidiFile:
|
||||
ppq: int
|
||||
tracks: list[MidiTrack]
|
||||
tempo_us: int = _DEFAULT_TEMPO_US
|
||||
|
||||
@property
|
||||
def bpm(self) -> float:
|
||||
return 60_000_000.0 / self.tempo_us
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 解析
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _read_varlen(data: bytes, pos: int) -> tuple[int, int]:
|
||||
value = 0
|
||||
while True:
|
||||
if pos >= len(data):
|
||||
raise ValueError("MIDI 数据在变长整数处意外结束")
|
||||
byte = data[pos]
|
||||
pos += 1
|
||||
value = (value << 7) | (byte & 0x7F)
|
||||
if not byte & 0x80:
|
||||
return value, pos
|
||||
|
||||
|
||||
def _parse_track(data: bytes, tempo_us: int, ppq: int) -> tuple[MidiTrack, int]:
|
||||
"""解析一条轨道,同时返回该轨道中最后一次生效的 tempo。"""
|
||||
track = MidiTrack()
|
||||
pos = 0
|
||||
tick = 0
|
||||
status = 0
|
||||
active: dict[tuple[int, int], MidiNote] = {}
|
||||
sec_per_tick = tempo_us / 1_000_000.0 / ppq
|
||||
|
||||
while pos < len(data):
|
||||
delta, pos = _read_varlen(data, pos)
|
||||
tick += delta
|
||||
if pos >= len(data):
|
||||
break
|
||||
byte = data[pos]
|
||||
|
||||
if byte & 0x80:
|
||||
status = byte
|
||||
pos += 1
|
||||
# else: running status,沿用上一个 status
|
||||
|
||||
if status == 0xFF: # meta
|
||||
if pos >= len(data):
|
||||
break
|
||||
meta_type = data[pos]
|
||||
pos += 1
|
||||
length, pos = _read_varlen(data, pos)
|
||||
payload = data[pos : pos + length]
|
||||
pos += length
|
||||
if meta_type == 0x51 and length == 3:
|
||||
tempo_us = int.from_bytes(payload, "big")
|
||||
sec_per_tick = tempo_us / 1_000_000.0 / ppq
|
||||
elif meta_type == 0x03:
|
||||
track.name = payload.decode("utf-8", errors="replace").strip()
|
||||
elif status in (0xF0, 0xF7): # sysex
|
||||
length, pos = _read_varlen(data, pos)
|
||||
pos += length
|
||||
else:
|
||||
kind = status & 0xF0
|
||||
if kind in (0x80, 0x90, 0xA0, 0xB0, 0xE0):
|
||||
if pos + 1 >= len(data):
|
||||
break
|
||||
d1, d2 = data[pos], data[pos + 1]
|
||||
pos += 2
|
||||
if kind == 0xC0:
|
||||
pass
|
||||
if kind == 0x90 and d2 > 0:
|
||||
track.channel = status & 0x0F
|
||||
active[(track.channel, d1)] = MidiNote(
|
||||
pitch=d1, start=tick * sec_per_tick, dur=0.0, velocity=d2
|
||||
)
|
||||
elif kind == 0x80 or (kind == 0x90 and d2 == 0):
|
||||
key = (status & 0x0F, d1)
|
||||
note = active.pop(key, None)
|
||||
if note is not None:
|
||||
note.dur = max(tick * sec_per_tick - note.start, 1e-3)
|
||||
track.notes.append(note)
|
||||
elif kind in (0xC0, 0xD0):
|
||||
if pos < len(data):
|
||||
if kind == 0xC0:
|
||||
track.program = data[pos]
|
||||
pos += 1
|
||||
|
||||
# 未闭合的 note-on:以最后一拍收尾
|
||||
for note in active.values():
|
||||
note.dur = max(tick * sec_per_tick - note.start, 1e-3)
|
||||
track.notes.append(note)
|
||||
|
||||
track.notes.sort(key=lambda n: (n.start, n.pitch))
|
||||
return track, tempo_us
|
||||
|
||||
|
||||
def read_midi(path: str | Path | bytes) -> MidiFile:
|
||||
"""读取标准 MIDI 文件。"""
|
||||
data = path if isinstance(path, bytes) else Path(path).read_bytes()
|
||||
if data[:4] != b"MThd":
|
||||
raise ValueError("不是合法的 MIDI 文件(缺少 MThd 头)")
|
||||
header_len = struct.unpack(">I", data[4:8])[0]
|
||||
fmt, n_tracks, division = struct.unpack(">HHH", data[8 : 8 + 6])
|
||||
pos = 8 + header_len
|
||||
|
||||
if division & 0x8000:
|
||||
raise ValueError("不支持 SMPTE 时间格式的 MIDI")
|
||||
ppq = division
|
||||
|
||||
tracks: list[MidiTrack] = []
|
||||
tempo_us = _DEFAULT_TEMPO_US
|
||||
for _ in range(n_tracks):
|
||||
if data[pos : pos + 4] != b"MTrk":
|
||||
break
|
||||
length = struct.unpack(">I", data[pos + 4 : pos + 8])[0]
|
||||
chunk = data[pos + 8 : pos + 8 + length]
|
||||
pos += 8 + length
|
||||
track, tempo_us = _parse_track(chunk, tempo_us, ppq)
|
||||
if track.notes:
|
||||
tracks.append(track)
|
||||
if not tracks:
|
||||
raise ValueError("MIDI 文件中没有音符")
|
||||
return MidiFile(ppq=ppq, tracks=tracks, tempo_us=tempo_us)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 旋律抽取
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _monophonize(notes: list[MidiNote]) -> list[MidiNote]:
|
||||
"""把可能复调的音符压成单音:重叠时保留较高音,并截断被覆盖的音。"""
|
||||
ordered = sorted(notes, key=lambda n: (n.start, -n.pitch))
|
||||
out: list[MidiNote] = []
|
||||
for note in ordered:
|
||||
if out and note.start < out[-1].end - 1e-6:
|
||||
if note.pitch > out[-1].pitch:
|
||||
out[-1].dur = max(1e-3, note.start - out[-1].start)
|
||||
out.append(MidiNote(note.pitch, note.start, note.dur, note.velocity))
|
||||
# 低音被覆盖则丢弃
|
||||
else:
|
||||
out.append(MidiNote(note.pitch, note.start, note.dur, note.velocity))
|
||||
return [n for n in out if n.dur >= 0.03]
|
||||
|
||||
|
||||
def pick_melody_track(midi: MidiFile) -> MidiTrack:
|
||||
"""在复音/多轨 MIDI 中挑出最像主旋律的轨道。
|
||||
|
||||
评分偏好:单音(polyphony 低)、音符数适中、音高偏高的轨道。
|
||||
"""
|
||||
if len(midi.tracks) == 1:
|
||||
return midi.tracks[0]
|
||||
|
||||
best, best_score = midi.tracks[0], float("-inf")
|
||||
for track in midi.tracks:
|
||||
n = len(track.notes)
|
||||
if n < 4:
|
||||
continue
|
||||
poly = track.polyphony
|
||||
score = (
|
||||
np.log1p(n)
|
||||
+ 0.02 * track.median_pitch
|
||||
- 1.5 * max(0.0, poly - 1.0)
|
||||
)
|
||||
if score > best_score:
|
||||
best, best_score = track, score
|
||||
return best
|
||||
|
||||
|
||||
def melody_from_midi(
|
||||
midi: MidiFile, song_id: str = "", title: str = ""
|
||||
) -> Melody:
|
||||
"""从 MIDI 中抽取单声部旋律。"""
|
||||
track = pick_melody_track(midi)
|
||||
notes = _monophonize(track.notes)
|
||||
if not notes:
|
||||
return Melody.empty(song_id, title)
|
||||
notes.sort(key=lambda n: n.start)
|
||||
base = notes[0].start
|
||||
mel = Melody(
|
||||
np.array([n.pitch for n in notes], dtype=np.float64),
|
||||
np.array([n.start - base for n in notes], dtype=np.float64),
|
||||
np.array([n.dur for n in notes], dtype=np.float64),
|
||||
song_id,
|
||||
title,
|
||||
{"midi_track": track.name, "bpm": round(midi.bpm, 2), "program": track.program},
|
||||
)
|
||||
return mel
|
||||
|
||||
|
||||
def read_midi_melody(path: str | Path, song_id: str = "", title: str = "") -> Melody:
|
||||
"""一步读取 MIDI 文件并抽取旋律。"""
|
||||
return melody_from_midi(read_midi(path), song_id or Path(path).stem, title)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 写出
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _write_varlen(value: int) -> bytes:
|
||||
if value < 0:
|
||||
raise ValueError("变长整数不能为负")
|
||||
out = bytearray([value & 0x7F])
|
||||
value >>= 7
|
||||
while value:
|
||||
out.append((value & 0x7F) | 0x80)
|
||||
value >>= 7
|
||||
out.reverse()
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def write_midi(
|
||||
path: str | Path,
|
||||
mel: Melody,
|
||||
*,
|
||||
ppq: int = 480,
|
||||
bpm: float = 100.0,
|
||||
program: int = 0,
|
||||
) -> None:
|
||||
"""把旋律写成单轨 MIDI(用于外部核对/导出)。"""
|
||||
tempo_us = int(round(60_000_000.0 / max(bpm, 1e-6)))
|
||||
sec_per_tick = tempo_us / 1_000_000.0 / ppq
|
||||
|
||||
events: list[tuple[int, bytes]] = []
|
||||
events.append((0, b"\xff\x51\x03" + tempo_us.to_bytes(3, "big")))
|
||||
events.append((0, bytes([0xC0 | 0x0F, program & 0x7F])))
|
||||
|
||||
for pitch, onset, dur in zip(mel.midis, mel.starts, mel.durs):
|
||||
start_tick = int(round(onset / sec_per_tick))
|
||||
end_tick = max(start_tick + 1, int(round((onset + dur) / sec_per_tick)))
|
||||
value = int(round(pitch))
|
||||
value = max(0, min(127, value))
|
||||
events.append((start_tick, bytes([0x90, value, 80])))
|
||||
events.append((end_tick, bytes([0x80, value, 0])))
|
||||
|
||||
events.sort(key=lambda e: e[0])
|
||||
|
||||
body = bytearray()
|
||||
last_tick = 0
|
||||
for tick, payload in events:
|
||||
body += _write_varlen(tick - last_tick)
|
||||
body += payload
|
||||
last_tick = tick
|
||||
body += _write_varlen(0) + b"\xff\x2f\x00"
|
||||
|
||||
chunk = b"MTrk" + struct.pack(">I", len(body)) + bytes(body)
|
||||
header = b"MThd" + struct.pack(">IHHH", 6, 0, 1, ppq)
|
||||
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(header + chunk)
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"""音符切分:把逐帧基频轨迹变成音符序列。
|
||||
|
||||
声学上「一个音符」表现为一段稳定的基频平台。切分流程:
|
||||
|
||||
1. 对 MIDI 音高轨迹做中值滤波,去掉颤音/抖动造成的毛刺;
|
||||
2. 按「音高突变」或「有声中断」把有声帧分成若干段;
|
||||
3. 合并音高接近且时间相邻的段(吸收换音时的短暂抖动);
|
||||
4. 对称地融合重复音(见 :func:`qbh.melody.fuse_repeated_notes`);
|
||||
5. 丢弃过短音符(多为切分噪声)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .melody import Melody, fuse_repeated_notes
|
||||
from .pitch import PitchTrack
|
||||
|
||||
__all__ = ["segment_notes", "smooth_midi", "group_runs"]
|
||||
|
||||
|
||||
def smooth_midi(midi: np.ndarray, window: int) -> np.ndarray:
|
||||
"""对含 NaN 的音高序列做中值滤波(NaN 不参与中值,输出保持 NaN)。"""
|
||||
if window <= 1 or midi.size == 0:
|
||||
return midi.copy()
|
||||
half = window // 2
|
||||
out = midi.copy()
|
||||
for i in range(midi.size):
|
||||
if not np.isfinite(midi[i]):
|
||||
continue
|
||||
lo = max(0, i - half)
|
||||
hi = min(midi.size, i + half + 1)
|
||||
seg = midi[lo:hi]
|
||||
seg = seg[np.isfinite(seg)]
|
||||
if seg.size:
|
||||
out[i] = np.median(seg)
|
||||
return out
|
||||
|
||||
|
||||
def group_runs(
|
||||
voiced_idx: np.ndarray,
|
||||
midi: np.ndarray,
|
||||
max_gap_frames: int,
|
||||
split_semitones: float,
|
||||
reference_window: int = 12,
|
||||
) -> list[tuple[int, int]]:
|
||||
"""把有声帧下标分组成音高平台。
|
||||
|
||||
返回 ``[(起点下标, 终点下标), ...]``,下标指向 ``voiced_idx`` 的位置(闭区间)。
|
||||
分段条件是「与当前平台参考音高相差超过阈值」或「中断超过 max_gap_frames 帧」。
|
||||
"""
|
||||
if voiced_idx.size == 0:
|
||||
return []
|
||||
|
||||
runs: list[tuple[int, int]] = []
|
||||
seg_start = 0
|
||||
recent: list[float] = [float(midi[0])]
|
||||
|
||||
for i in range(1, voiced_idx.size):
|
||||
gap = int(voiced_idx[i] - voiced_idx[i - 1])
|
||||
reference = float(np.median(recent[-reference_window:]))
|
||||
if gap > max_gap_frames or abs(float(midi[i]) - reference) > split_semitones:
|
||||
runs.append((seg_start, i - 1))
|
||||
seg_start = i
|
||||
recent = [float(midi[i])]
|
||||
else:
|
||||
recent.append(float(midi[i]))
|
||||
|
||||
runs.append((seg_start, voiced_idx.size - 1))
|
||||
return runs
|
||||
|
||||
|
||||
def _merge_close_segments(
|
||||
notes: list[tuple[float, float, float]],
|
||||
bridge_gap_s: float,
|
||||
merge_semitones: float,
|
||||
) -> list[tuple[float, float, float]]:
|
||||
"""合并音高接近且间隔很小的相邻音符(吸收换音抖动)。"""
|
||||
if not notes:
|
||||
return notes
|
||||
merged: list[tuple[float, float, float]] = [notes[0]]
|
||||
for pitch, onset, dur in notes[1:]:
|
||||
prev_pitch, prev_onset, prev_dur = merged[-1]
|
||||
prev_end = prev_onset + prev_dur
|
||||
gap = onset - prev_end
|
||||
if gap <= bridge_gap_s and abs(pitch - prev_pitch) < merge_semitones:
|
||||
new_end = max(prev_end, onset + dur)
|
||||
total = new_end - prev_onset
|
||||
weight_prev = prev_dur / max(total, 1e-9)
|
||||
merged[-1] = (
|
||||
prev_pitch * weight_prev + pitch * (1.0 - weight_prev),
|
||||
prev_onset,
|
||||
total,
|
||||
)
|
||||
else:
|
||||
merged.append((pitch, onset, dur))
|
||||
return merged
|
||||
|
||||
|
||||
def segment_notes(track: PitchTrack, cfg: Config = DEFAULT) -> Melody:
|
||||
"""把基频轨迹切分成音符序列。"""
|
||||
voiced_idx = np.flatnonzero(track.voiced)
|
||||
if voiced_idx.size == 0:
|
||||
return Melody.empty()
|
||||
|
||||
midi = track.midi[voiced_idx]
|
||||
midi = smooth_midi(midi, cfg.median_filter_frames)
|
||||
|
||||
hop = track.hop_s
|
||||
max_gap_frames = max(1, int(round(cfg.bridge_gap_ms / 1000.0 / hop)))
|
||||
runs = group_runs(
|
||||
voiced_idx, midi, max_gap_frames, cfg.split_semitones, cfg.median_filter_frames
|
||||
)
|
||||
|
||||
notes: list[tuple[float, float, float]] = []
|
||||
for start, stop in runs:
|
||||
seg = midi[start : stop + 1]
|
||||
seg = seg[np.isfinite(seg)]
|
||||
if seg.size == 0:
|
||||
continue
|
||||
pitch = float(np.median(seg))
|
||||
# 帧中心 → 音符起止:向外各扩半帧,补上被帧中心吞掉的时间
|
||||
onset = float(track.times[voiced_idx[start]] - hop / 2.0)
|
||||
offset = float(track.times[voiced_idx[stop]] + hop / 2.0)
|
||||
dur = max(offset - onset, hop)
|
||||
notes.append((pitch, max(onset, 0.0), dur))
|
||||
|
||||
notes = _merge_close_segments(
|
||||
notes, cfg.bridge_gap_ms / 1000.0, cfg.merge_semitones
|
||||
)
|
||||
notes = [n for n in notes if n[2] * 1000.0 >= cfg.min_note_ms]
|
||||
if not notes:
|
||||
return Melody.empty()
|
||||
|
||||
notes.sort(key=lambda n: n[0])
|
||||
notes.sort(key=lambda n: n[1])
|
||||
|
||||
mel = Melody(
|
||||
np.array([n[0] for n in notes]),
|
||||
np.array([n[1] for n in notes]),
|
||||
np.array([n[2] for n in notes]),
|
||||
)
|
||||
mel.starts = mel.starts - mel.starts.min()
|
||||
mel = fuse_repeated_notes(mel, cfg)
|
||||
|
||||
if mel.n_notes > cfg.max_notes:
|
||||
mel = mel.slice(0, cfg.max_notes)
|
||||
return mel
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
"""YIN 基频(F0)提取 —— 向量化实现。
|
||||
|
||||
YIN 的差函数原始定义需要 O(N·τ) 的双重求和。这里用恒等式
|
||||
|
||||
d(τ) = e1 + e2(τ) − 2·A(τ)
|
||||
|
||||
把逐帧计算改写成「前缀和 + FFT 互相关」,整段音频一次性批量算完:
|
||||
``e1`` 是帧内固定能量,``e2(τ)`` 用平方前缀和求得,``A(τ)`` 用 FFT 卷积求得。
|
||||
这样避免了 Python 层的双层循环,一段 10 秒哼唱通常在几十毫秒内完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
from scipy.fft import irfft, next_fast_len, rfft
|
||||
|
||||
from .audio import frame_signal
|
||||
from .config import DEFAULT, Config
|
||||
|
||||
__all__ = ["PitchTrack", "extract_pitch", "hz_to_midi", "midi_to_hz"]
|
||||
|
||||
_A4_HZ = 440.0
|
||||
_A4_MIDI = 69.0
|
||||
|
||||
|
||||
def hz_to_midi(f0: np.ndarray) -> np.ndarray:
|
||||
"""频率(Hz) → 连续 MIDI 音高;非正频率记为 NaN。"""
|
||||
f0 = np.asarray(f0, dtype=np.float64)
|
||||
out = np.full(f0.shape, np.nan, dtype=np.float64)
|
||||
ok = f0 > 0
|
||||
out[ok] = _A4_MIDI + 12.0 * np.log2(f0[ok] / _A4_HZ)
|
||||
return out
|
||||
|
||||
|
||||
def midi_to_hz(midi: np.ndarray) -> np.ndarray:
|
||||
"""连续 MIDI 音高 → 频率(Hz)。"""
|
||||
midi = np.asarray(midi, dtype=np.float64)
|
||||
return _A4_HZ * np.power(2.0, (midi - _A4_MIDI) / 12.0)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PitchTrack:
|
||||
"""逐帧基频轨迹。"""
|
||||
|
||||
times: np.ndarray # 帧中心时刻(秒)
|
||||
f0: np.ndarray # 基频 Hz,未发声为 0
|
||||
midi: np.ndarray # 连续 MIDI 音高,未发声为 NaN
|
||||
conf: np.ndarray # 置信度 0..1
|
||||
rms: np.ndarray # 逐帧 RMS
|
||||
voiced: np.ndarray # 有声标记
|
||||
sr: int
|
||||
hop_s: float
|
||||
frame_s: float
|
||||
|
||||
@property
|
||||
def n_frames(self) -> int:
|
||||
return int(self.times.size)
|
||||
|
||||
@property
|
||||
def duration(self) -> float:
|
||||
return float(self.times[-1] + self.hop_s) if self.times.size else 0.0
|
||||
|
||||
def voiced_ratio(self) -> float:
|
||||
return float(self.voiced.mean()) if self.voiced.size else 0.0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 差函数 / CMNDF
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _difference_functions(frames: np.ndarray, tau_max: int, window: int) -> np.ndarray:
|
||||
"""批量计算 d(τ),τ ∈ [0, tau_max]。返回 (n_frames, tau_max+1)。"""
|
||||
frames = np.asarray(frames, dtype=np.float64)
|
||||
n_frames, frame_len = frames.shape
|
||||
taus = np.arange(tau_max + 1)
|
||||
|
||||
# e1:积分窗内的固定能量
|
||||
sq = frames * frames
|
||||
cumsum = np.concatenate(
|
||||
[np.zeros((n_frames, 1)), np.cumsum(sq, axis=1)], axis=1
|
||||
)
|
||||
e1 = cumsum[:, window]
|
||||
|
||||
# e2(τ):滑动窗能量
|
||||
e2 = cumsum[:, taus + window] - cumsum[:, taus]
|
||||
|
||||
# A(τ):积分窗与整帧的互相关,用 FFT 一次算完
|
||||
reversed_head = np.ascontiguousarray(frames[:, :window][:, ::-1])
|
||||
fft_len = next_fast_len(frame_len + window - 1)
|
||||
fa = rfft(reversed_head, fft_len, axis=1)
|
||||
fb = rfft(frames, fft_len, axis=1)
|
||||
conv = irfft(fb * fa, fft_len, axis=1)
|
||||
acf = conv[:, taus + window - 1]
|
||||
|
||||
diff = e1[:, None] + e2 - 2.0 * acf
|
||||
return np.maximum(diff, 0.0)
|
||||
|
||||
|
||||
def _cmndf(diff: np.ndarray) -> np.ndarray:
|
||||
"""累积均值归一化差函数 d'(τ);d'(0) 约定为 1。"""
|
||||
cumsum = np.cumsum(diff, axis=1)
|
||||
taus = np.arange(1, diff.shape[1], dtype=np.float64)
|
||||
running = cumsum[:, 1:] / taus
|
||||
out = np.ones_like(diff)
|
||||
np.divide(diff[:, 1:], np.maximum(running, 1e-12), out=out[:, 1:])
|
||||
return out
|
||||
|
||||
|
||||
def _pick_tau(
|
||||
cmndf: np.ndarray, tau_min: int, tau_max: int, threshold: float
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""选基音周期。
|
||||
|
||||
低基频(如 110 Hz)的 CMNDF 谷很宽,"首次低于阈值" 的位置离真正的谷底
|
||||
可能差十几个采样点,因此在 ±3 邻域内细化会系统性高估基频。这里改为
|
||||
**先定位所有局部极小,再取其中最早的一个低于阈值者**;若没有低于阈值的
|
||||
谷,才退化为范围内全局最小(后续由置信度门限筛除)。
|
||||
|
||||
返回 (tau 浮点值, 谷底 CMNDF 值)。
|
||||
"""
|
||||
n_frames, n_tau = cmndf.shape
|
||||
|
||||
# 局部极小:两侧邻点都不小于自身
|
||||
is_min = np.zeros_like(cmndf, dtype=bool)
|
||||
is_min[:, 1:-1] = (cmndf[:, 1:-1] <= cmndf[:, :-2]) & (
|
||||
cmndf[:, 1:-1] <= cmndf[:, 2:]
|
||||
)
|
||||
in_range = np.zeros(n_tau, dtype=bool)
|
||||
in_range[tau_min : tau_max + 1] = True
|
||||
candidates = is_min & in_range[None, :]
|
||||
|
||||
below = candidates & (cmndf < threshold)
|
||||
has_candidate = below.any(axis=1)
|
||||
# 取 tau 最小的合格谷底
|
||||
first_below = below.argmax(axis=1)
|
||||
|
||||
# 无合格谷底:在范围内取全局最小
|
||||
masked = np.where(in_range[None, :], cmndf, np.inf)
|
||||
fallback = masked.argmin(axis=1)
|
||||
|
||||
rows = np.arange(n_frames)
|
||||
best = np.where(has_candidate, first_below, fallback)
|
||||
|
||||
# 抛物线插值,得到亚采样精度的周期与谷底值
|
||||
d0 = cmndf[rows, best]
|
||||
d_left = cmndf[rows, np.maximum(best - 1, tau_min)]
|
||||
d_right = cmndf[rows, np.minimum(best + 1, tau_max)]
|
||||
denom = d_left - 2.0 * d0 + d_right
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
shift = np.where(np.abs(denom) > 1e-12, 0.5 * (d_left - d_right) / denom, 0.0)
|
||||
shift = np.nan_to_num(shift, nan=0.0, posinf=0.0, neginf=0.0)
|
||||
shift = np.clip(shift, -1.0, 1.0)
|
||||
interior = (best > tau_min) & (best < tau_max)
|
||||
tau = best.astype(np.float64) + np.where(interior, shift, 0.0)
|
||||
valley = d0 - 0.5 * denom * shift * shift
|
||||
return tau, np.maximum(valley, 0.0)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 后处理
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _nan_median_filter(values: np.ndarray, window: int) -> np.ndarray:
|
||||
"""忽略 NaN 的中值滤波(用于构造局部参考音高)。"""
|
||||
if window <= 1:
|
||||
return values.copy()
|
||||
half = window // 2
|
||||
out = np.full_like(values, np.nan)
|
||||
for i in range(values.size):
|
||||
lo = max(0, i - half)
|
||||
hi = min(values.size, i + half + 1)
|
||||
seg = values[lo:hi]
|
||||
seg = seg[np.isfinite(seg)]
|
||||
if seg.size:
|
||||
out[i] = np.median(seg)
|
||||
return out
|
||||
|
||||
|
||||
def _fold_octaves(
|
||||
midi: np.ndarray, reference: np.ndarray, low: float, high: float
|
||||
) -> np.ndarray:
|
||||
"""把偏离局部参考达 low..high 半音的帧折叠一个八度。
|
||||
|
||||
YIN 最常见的错误是倍频/半频误判(±12 半音)。这里只在偏差落在一个八度附近时
|
||||
才纠正,避免把真实的大跳音程(如 9 度)改坏。
|
||||
"""
|
||||
diff = midi - reference
|
||||
magnitude = np.abs(diff)
|
||||
fold = -np.round(diff / 12.0) * 12.0
|
||||
mask = np.isfinite(diff) & (magnitude >= low) & (magnitude <= high)
|
||||
return np.where(mask, midi + fold, midi)
|
||||
|
||||
|
||||
def _correct_octaves(
|
||||
midi: np.ndarray, voiced: np.ndarray, cfg: Config
|
||||
) -> np.ndarray:
|
||||
out = midi.copy()
|
||||
for _ in range(2): # 两轮迭代,处理连续八度跳变
|
||||
reference = _nan_median_filter(out, cfg.median_filter_frames)
|
||||
corrected = _fold_octaves(out, reference, cfg.octave_fold_low, cfg.octave_fold_high)
|
||||
corrected = np.where(voiced, corrected, np.nan)
|
||||
if np.allclose(np.nan_to_num(corrected, nan=0.0), np.nan_to_num(out, nan=0.0)):
|
||||
break
|
||||
out = corrected
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 主入口
|
||||
# --------------------------------------------------------------------------- #
|
||||
def extract_pitch(x: np.ndarray, sr: int, cfg: Config = DEFAULT) -> PitchTrack:
|
||||
"""对单声道波形提取逐帧基频。"""
|
||||
x = np.asarray(x, dtype=np.float32).reshape(-1)
|
||||
frame_len = max(64, int(round(cfg.frame_ms / 1000.0 * sr)))
|
||||
hop = max(1, int(round(cfg.hop_ms / 1000.0 * sr)))
|
||||
|
||||
tau_min = max(2, int(np.floor(sr / cfg.fmax_hz)))
|
||||
tau_max = int(np.ceil(sr / cfg.fmin_hz))
|
||||
# 固定积分窗长度,保证 e1 与 τ 无关(YIN 原文做法)
|
||||
tau_max = min(tau_max, frame_len // 2 - 1)
|
||||
window = frame_len - tau_max
|
||||
if window < tau_max or window < 8:
|
||||
raise ValueError(
|
||||
f"帧长过短:frame_len={frame_len}, tau_max={tau_max}, window={window}"
|
||||
)
|
||||
|
||||
frames = frame_signal(x, frame_len, hop)
|
||||
n_frames = frames.shape[0]
|
||||
times = (np.arange(n_frames) * hop + frame_len / 2.0) / sr
|
||||
|
||||
if n_frames == 0:
|
||||
empty = np.zeros(0)
|
||||
return PitchTrack(
|
||||
times=empty,
|
||||
f0=empty,
|
||||
midi=empty,
|
||||
conf=empty,
|
||||
rms=empty,
|
||||
voiced=np.zeros(0, dtype=bool),
|
||||
sr=sr,
|
||||
hop_s=hop / sr,
|
||||
frame_s=frame_len / sr,
|
||||
)
|
||||
|
||||
diff = _difference_functions(frames, tau_max, window)
|
||||
cmndf = _cmndf(diff)
|
||||
tau, cmndf_at_tau = _pick_tau(cmndf, tau_min, tau_max, cfg.yin_threshold)
|
||||
|
||||
f0 = sr / np.maximum(tau, 1e-9)
|
||||
conf = np.clip(1.0 - cmndf_at_tau, 0.0, 1.0)
|
||||
rms = np.sqrt(np.mean(np.square(frames, dtype=np.float64), axis=1))
|
||||
|
||||
# 双重有声判定:置信度 + 相对峰值能量
|
||||
peak_rms = float(rms.max()) if rms.size else 0.0
|
||||
# 绝对静音门限:全零/极低电平信号上 YIN 的 CMNDF 恒为 0,会被误判为满置信度
|
||||
silence = peak_rms < 1e-5
|
||||
energy_floor = peak_rms * (10.0 ** (cfg.voicing_db_below_peak / 20.0))
|
||||
voiced = (
|
||||
(conf >= cfg.voicing_conf)
|
||||
& (cmndf_at_tau <= cfg.yin_max_cmndf)
|
||||
& (rms > energy_floor)
|
||||
)
|
||||
if silence:
|
||||
voiced[:] = False
|
||||
|
||||
midi = hz_to_midi(f0)
|
||||
midi = np.where(voiced, midi, np.nan)
|
||||
midi = _correct_octaves(midi, voiced, cfg)
|
||||
|
||||
return PitchTrack(
|
||||
times=times,
|
||||
f0=np.where(voiced, f0, 0.0),
|
||||
midi=midi,
|
||||
conf=conf,
|
||||
rms=rms,
|
||||
voiced=voiced,
|
||||
sr=sr,
|
||||
hop_s=hop / sr,
|
||||
frame_s=frame_len / sr,
|
||||
)
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
"""内置曲库:用简谱式记谱 DSL 手工录入的旋律。
|
||||
|
||||
记谱格式:``音名:拍数``,用空格分隔,``-`` 表示休止,``|`` 为小节线(忽略)。
|
||||
音名支持升降号,例如 ``C4``、``F#4``、``Bb3``;``C4`` 对应 MIDI 60。
|
||||
|
||||
选择这批曲目的原则:公版或传统民歌,旋律辨识度高,且覆盖中西、大小调、
|
||||
五声音阶等不同风格——这样检索难度分布更真实,不会因为曲目同质而虚高。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .melody import Melody
|
||||
|
||||
__all__ = ["Score", "BUILTIN_SCORES", "parse_notation", "builtin_melodies"]
|
||||
|
||||
_NOTE_BASE = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
|
||||
|
||||
|
||||
def note_name_to_midi(name: str) -> int:
|
||||
"""``"C4"`` → 60,``"F#4"`` → 66,``"Bb3"`` → 58。"""
|
||||
letter = name[0].upper()
|
||||
if letter not in _NOTE_BASE:
|
||||
raise ValueError(f"无法识别的音名: {name!r}")
|
||||
rest = name[1:]
|
||||
accidental = 0
|
||||
if rest.startswith("#"):
|
||||
accidental, rest = 1, rest[1:]
|
||||
elif rest.startswith("b"):
|
||||
accidental, rest = -1, rest[1:]
|
||||
octave = int(rest)
|
||||
return 12 * (octave + 1) + _NOTE_BASE[letter] + accidental
|
||||
|
||||
|
||||
def parse_notation(text: str, bpm: float = 100.0) -> Melody:
|
||||
"""把记谱串解析成 :class:`Melody`。"""
|
||||
beat_s = 60.0 / bpm
|
||||
events: list[tuple[float, float, float]] = []
|
||||
cursor = 0.0
|
||||
for token in text.split():
|
||||
if token == "|":
|
||||
continue
|
||||
name, _, beats_text = token.partition(":")
|
||||
beats = float(beats_text) if beats_text else 1.0
|
||||
dur = beats * beat_s
|
||||
if name != "-":
|
||||
events.append((cursor, dur, float(note_name_to_midi(name))))
|
||||
cursor += dur
|
||||
if not events:
|
||||
raise ValueError("记谱串为空")
|
||||
return Melody.from_events(events)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Score:
|
||||
"""一首内置曲目的元数据与记谱。"""
|
||||
|
||||
id: str
|
||||
title: str
|
||||
origin: str
|
||||
tags: tuple[str, ...]
|
||||
notation: str
|
||||
bpm: float = 100.0
|
||||
|
||||
def melody(self) -> Melody:
|
||||
mel = parse_notation(self.notation, self.bpm)
|
||||
mel.song_id = self.id
|
||||
mel.title = self.title
|
||||
mel.meta.update({"origin": self.origin, "tags": list(self.tags), "source": "builtin"})
|
||||
return mel
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 曲目表
|
||||
# --------------------------------------------------------------------------- #
|
||||
_BUILTIN: tuple[Score, ...] = (
|
||||
# ---------------- 儿歌 / 传统 ----------------
|
||||
Score(
|
||||
"twinkle_twinkle", "小星星", "法国民谣", ("儿歌", "大调"),
|
||||
"C4:1 C4:1 G4:1 G4:1 A4:1 A4:1 G4:2 "
|
||||
"F4:1 F4:1 E4:1 E4:1 D4:1 D4:1 C4:2 "
|
||||
"G4:1 G4:1 F4:1 F4:1 E4:1 E4:1 D4:2 "
|
||||
"G4:1 G4:1 F4:1 F4:1 E4:1 E4:1 D4:2 "
|
||||
"C4:1 C4:1 G4:1 G4:1 A4:1 A4:1 G4:2 "
|
||||
"F4:1 F4:1 E4:1 E4:1 D4:1 D4:1 C4:2",
|
||||
104.0,
|
||||
),
|
||||
Score(
|
||||
"happy_birthday", "生日快乐", "美国传统", ("儿歌", "大调"),
|
||||
"G4:0.75 G4:0.25 A4:1 G4:1 C5:1 B4:2 "
|
||||
"G4:0.75 G4:0.25 A4:1 G4:1 D5:1 C5:2 "
|
||||
"G4:0.75 G4:0.25 G5:1 E5:1 C5:1 B4:1 A4:2 "
|
||||
"F5:0.75 F5:0.25 E5:1 C5:1 D5:1 C5:2",
|
||||
108.0,
|
||||
),
|
||||
Score(
|
||||
"jingle_bells", "铃儿响叮当", "美国传统", ("儿歌", "节日", "大调"),
|
||||
"E4:1 E4:1 E4:2 E4:1 E4:1 E4:2 "
|
||||
"E4:1 G4:1 C4:1 D4:1 E4:4 "
|
||||
"F4:1 F4:1 F4:1 F4:1 F4:1 E4:1 E4:1 E4:1 "
|
||||
"E4:1 D4:1 D4:1 E4:1 D4:2 G4:2",
|
||||
120.0,
|
||||
),
|
||||
Score(
|
||||
"frere_jacques", "两只老虎", "法国民谣", ("儿歌", "大调"),
|
||||
"C4:1 D4:1 E4:1 C4:1 C4:1 D4:1 E4:1 C4:1 "
|
||||
"E4:1 F4:1 G4:2 E4:1 F4:1 G4:2 "
|
||||
"G4:0.5 A4:0.5 G4:0.5 F4:0.5 E4:1 C4:1 "
|
||||
"G4:0.5 A4:0.5 G4:0.5 F4:0.5 E4:1 C4:1 "
|
||||
"C4:1 G3:1 C4:2 C4:1 G3:1 C4:2",
|
||||
112.0,
|
||||
),
|
||||
Score(
|
||||
"mary_had_little_lamb", "玛丽有只小羊羔", "美国传统", ("儿歌", "大调"),
|
||||
"E4:1 D4:1 C4:1 D4:1 E4:1 E4:1 E4:2 "
|
||||
"D4:1 D4:1 D4:2 E4:1 G4:1 G4:2 "
|
||||
"E4:1 D4:1 C4:1 D4:1 E4:1 E4:1 E4:1 E4:1 "
|
||||
"D4:1 D4:1 E4:1 D4:1 C4:2 -:1",
|
||||
100.0,
|
||||
),
|
||||
Score(
|
||||
"row_your_boat", "划船歌", "美国传统", ("儿歌", "大调", "轮唱"),
|
||||
"C4:1 C4:1 C4:0.75 D4:0.25 E4:1 "
|
||||
"E4:1 D4:1 E4:1 F4:1 G4:2 "
|
||||
"C5:1 C5:1 C5:0.75 G4:0.25 G4:1 "
|
||||
"G4:1 E4:1 E4:1 D4:1 D4:1 C4:2",
|
||||
96.0,
|
||||
),
|
||||
Score(
|
||||
"london_bridge", "伦敦桥", "英国传统", ("儿歌", "大调"),
|
||||
"G4:0.5 A4:0.5 G4:0.5 F4:0.5 E4:0.5 F4:0.5 G4:2 "
|
||||
"D4:0.5 E4:0.5 F4:2 E4:0.5 F4:0.5 G4:2 "
|
||||
"G4:0.5 A4:0.5 G4:0.5 F4:0.5 E4:0.5 F4:0.5 G4:2 "
|
||||
"D4:2 G4:2 E4:2 C4:2",
|
||||
108.0,
|
||||
),
|
||||
Score(
|
||||
"when_the_saints", "圣者行进", "美国传统", ("传统", "大调"),
|
||||
"C4:1 E4:1 F4:1 G4:2 C4:1 E4:1 F4:1 G4:2 "
|
||||
"C4:1 E4:1 F4:1 G4:1 E4:1 C4:1 E4:1 D4:2 "
|
||||
"E4:1 E4:1 D4:1 C4:1 C4:1 E4:1 G4:2 "
|
||||
"E4:1 E4:1 D4:1 C4:1 C4:1 E4:1 G4:2",
|
||||
110.0,
|
||||
),
|
||||
Score(
|
||||
"auld_lang_syne", "友谊地久天长", "苏格兰民歌", ("传统", "节日", "大调"),
|
||||
"C4:1 -:0.5 F4:1.5 E4:1 F4:1.5 A4:1 G4:1 "
|
||||
"F4:1.5 F4:0.5 A4:1 C5:1.5 D5:1 "
|
||||
"C5:1 A4:1 F4:1.5 F4:0.5 G4:1 A4:1 G4:1 F4:1 -:0.5",
|
||||
88.0,
|
||||
),
|
||||
Score(
|
||||
"silent_night", "平安夜", "奥地利传统", ("节日", "大调"),
|
||||
"G4:1.5 A4:0.5 G4:1 E4:3 "
|
||||
"G4:1.5 A4:0.5 G4:1 E4:3 "
|
||||
"D5:2 D5:1 B4:3 "
|
||||
"C5:2 C5:1 G4:3 "
|
||||
"A4:2 A4:1 C5:1.5 B4:0.5 A4:1 G4:1.5 A4:0.5 G4:1 E4:3 "
|
||||
"D5:2 D5:1 F5:1.5 D5:0.5 B4:1 C5:1.5 E5:0.5 C5:3",
|
||||
76.0,
|
||||
),
|
||||
Score(
|
||||
"amazing_grace", "奇异恩典", "美国传统", ("传统", "大调"),
|
||||
"G4:1 C5:2 E5:0.5 D5:0.5 C5:1 E5:2 D5:0.5 C5:0.5 "
|
||||
"A4:1 C5:2 A4:0.5 G4:0.5 G4:3 "
|
||||
"G4:1 C5:2 E5:0.5 D5:0.5 C5:1 E5:2 G5:1 "
|
||||
"E5:1.5 D5:0.5 C5:1 A4:1 G4:1 A4:1 C5:1 D5:2 C5:1",
|
||||
84.0,
|
||||
),
|
||||
Score(
|
||||
"itsy_bitsy_spider", "小蜘蛛", "美国儿歌", ("儿歌", "小调"),
|
||||
"C4:0.5 C4:0.5 C4:0.5 D4:0.5 E4:1 E4:1 "
|
||||
"E4:0.5 D4:0.5 C4:0.5 D4:0.5 E4:1 C4:1 "
|
||||
"E4:0.5 E4:0.5 F4:0.5 G4:0.5 G4:1 F4:1 "
|
||||
"E4:0.5 F4:0.5 G4:0.5 E4:0.5 E4:1 C4:1",
|
||||
120.0,
|
||||
),
|
||||
Score(
|
||||
"old_macdonald", "老麦克唐纳", "美国传统", ("儿歌", "大调"),
|
||||
"G4:1 G4:1 G4:1 D4:1 E4:1 E4:1 D4:2 "
|
||||
"B4:1 B4:1 A4:1 A4:1 G4:2 "
|
||||
"D4:1 G4:1 G4:1 G4:1 D4:1 E4:1 E4:1 D4:2 "
|
||||
"B4:1 B4:1 A4:1 A4:1 G4:2",
|
||||
104.0,
|
||||
),
|
||||
Score(
|
||||
"yankee_doodle", "扬基歌", "美国传统", ("传统", "大调"),
|
||||
"C4:1 C4:1 D4:1 E4:1 C4:1 E4:1 D4:1 G4:1 "
|
||||
"C4:1 C4:1 D4:1 E4:1 C4:2 B4:2 "
|
||||
"C4:1 C4:1 D4:1 E4:1 F4:1 E4:1 D4:1 C4:1 "
|
||||
"B4:1 G4:1 A4:1 B4:1 C4:2 C4:2",
|
||||
116.0,
|
||||
),
|
||||
Score(
|
||||
"brahms_lullaby", "摇篮曲", "勃拉姆斯", ("古典", "大调"),
|
||||
"E4:0.5 E4:0.5 G4:1 E4:0.5 E4:0.5 G4:1 "
|
||||
"E4:0.5 G4:0.5 C5:1.5 B4:0.5 A4:1 A4:1 G4:2 "
|
||||
"D4:0.5 E4:0.5 F4:1 D4:0.5 E4:0.5 F4:1 "
|
||||
"D4:0.5 F4:0.5 B4:1.5 A4:0.5 G4:1 B4:1 C5:2",
|
||||
72.0,
|
||||
),
|
||||
Score(
|
||||
"scarborough_fair", "斯卡布罗集市", "英国传统", ("民歌", "小调"),
|
||||
"A4:1 A4:1 A4:1 E4:2 E4:1 B4:1 C5:1 B4:2 A4:1 "
|
||||
"A4:1 A4:1 G4:1 A4:2 B4:1 A4:1 G4:1 E4:2 "
|
||||
"A4:1 A4:1 A4:1 E4:2 E4:1 B4:1 C5:1 B4:2 A4:1 "
|
||||
"A4:1 G4:1 A4:1 B4:2 A4:1 G4:1 E4:1 D4:2",
|
||||
92.0,
|
||||
),
|
||||
# ---------------- 中国民歌 ----------------
|
||||
Score(
|
||||
"molihua", "茉莉花", "江苏民歌", ("民歌", "五声", "中国"),
|
||||
"E4:0.5 E4:0.5 G4:1 A4:1 C5:0.5 C5:0.5 A4:1 G4:1 "
|
||||
"A4:0.5 G4:0.5 A4:1 C5:1 G4:1 A4:0.5 G4:0.5 E4:1 D4:1 E4:2 "
|
||||
"G4:0.5 G4:0.5 G4:1 E4:1 D4:0.5 E4:0.5 G4:1 A4:1 "
|
||||
"C5:0.5 A4:0.5 G4:1 A4:1 G4:1 E4:0.5 D4:0.5 E4:2",
|
||||
88.0,
|
||||
),
|
||||
Score(
|
||||
"song_bie", "送别", "李叔同 词", ("民歌", "中国", "大调"),
|
||||
"A4:1 A4:1 B4:1 C5:1 C5:2 B4:1 A4:1 "
|
||||
"G4:1 G4:1 A4:1 B4:1 A4:2 G4:1 F4:1 "
|
||||
"E4:1 E4:1 G4:1 A4:1 G4:2 E4:1 D4:1 "
|
||||
"C4:1 D4:1 E4:1 G4:1 A4:2 G4:2",
|
||||
76.0,
|
||||
),
|
||||
Score(
|
||||
"kangding_qingge", "康定情歌", "四川民歌", ("民歌", "五声", "中国"),
|
||||
"G4:0.5 A4:0.5 C5:1 A4:1 G4:1 A4:0.5 C5:0.5 D5:1 C5:1 A4:2 "
|
||||
"G4:0.5 A4:0.5 C5:1 A4:1 G4:1 E4:0.5 G4:0.5 A4:1 G4:1 E4:2 "
|
||||
"C5:0.5 D5:0.5 E5:1 D5:1 C5:1 A4:0.5 C5:0.5 D5:1 C5:1 A4:2",
|
||||
92.0,
|
||||
),
|
||||
Score(
|
||||
"shi_shang_zhi_you_mama_hao", "世上只有妈妈好", "中国电影插曲", ("儿歌", "中国", "大调"),
|
||||
"C4:1 C4:1 D4:1 E4:1 G4:2 E4:1 G4:1 "
|
||||
"A4:1 G4:1 E4:1 D4:1 C4:2 -:1 "
|
||||
"C4:1 C4:1 D4:1 E4:1 G4:2 E4:1 G4:1 "
|
||||
"A4:1 G4:1 E4:1 D4:1 C4:2 -:1",
|
||||
80.0,
|
||||
),
|
||||
Score(
|
||||
"yi_fen_qian", "一分钱", "潘振声", ("儿歌", "中国", "大调"),
|
||||
"G4:0.5 G4:0.5 E4:1 G4:0.5 G4:0.5 E4:1 "
|
||||
"G4:0.5 A4:0.5 G4:0.5 E4:0.5 D4:1 E4:1 "
|
||||
"C4:0.5 D4:0.5 E4:0.5 G4:0.5 A4:1 G4:1 "
|
||||
"E4:0.5 D4:0.5 C4:0.5 D4:0.5 E4:2",
|
||||
116.0,
|
||||
),
|
||||
Score(
|
||||
"zhao_peng_you", "找朋友", "中国儿歌", ("儿歌", "中国", "大调"),
|
||||
"C4:1 C4:1 D4:1 E4:1 G4:2 E4:2 "
|
||||
"G4:1 G4:1 A4:1 G4:1 E4:1 D4:1 C4:2 "
|
||||
"C4:1 D4:1 E4:1 G4:1 A4:2 G4:2 "
|
||||
"E4:1 D4:1 C4:1 D4:1 C4:4",
|
||||
108.0,
|
||||
),
|
||||
Score(
|
||||
"shu_ya_zi", "数鸭子", "中国儿歌", ("儿歌", "中国", "大调"),
|
||||
"G4:0.5 G4:0.5 A4:1 G4:0.5 E4:0.5 G4:1 "
|
||||
"A4:0.5 G4:0.5 E4:1 D4:1 E4:2 "
|
||||
"G4:0.5 G4:0.5 A4:1 C5:0.5 A4:0.5 G4:1 "
|
||||
"E4:0.5 D4:0.5 E4:1 C4:1 D4:2",
|
||||
112.0,
|
||||
),
|
||||
Score(
|
||||
"mai_bao_ge", "卖报歌", "聂耳", ("儿歌", "中国", "大调"),
|
||||
"G4:0.5 G4:0.5 A4:0.5 G4:0.5 E4:1 G4:0.5 A4:0.5 "
|
||||
"C5:1 A4:0.5 G4:0.5 E4:1 D4:1 "
|
||||
"G4:0.5 G4:0.5 A4:0.5 G4:0.5 E4:1 G4:0.5 A4:0.5 "
|
||||
"C5:1 A4:1 G4:2",
|
||||
120.0,
|
||||
),
|
||||
# ---------------- 古典 ----------------
|
||||
Score(
|
||||
"ode_to_joy", "欢乐颂", "贝多芬", ("古典", "大调"),
|
||||
"E4:1 E4:1 F4:1 G4:1 G4:1 F4:1 E4:1 D4:1 "
|
||||
"C4:1 C4:1 D4:1 E4:1 E4:1.5 D4:0.5 D4:2 "
|
||||
"E4:1 E4:1 F4:1 G4:1 G4:1 F4:1 E4:1 D4:1 "
|
||||
"C4:1 C4:1 D4:1 E4:1 D4:1.5 C4:0.5 C4:2",
|
||||
100.0,
|
||||
),
|
||||
Score(
|
||||
"fur_elise", "致爱丽丝", "贝多芬", ("古典", "小调"),
|
||||
"E5:0.5 D#5:0.5 E5:0.5 D#5:0.5 E5:0.5 B4:0.5 D5:0.5 C5:0.5 "
|
||||
"A4:1.5 C4:0.5 E4:0.5 A4:0.5 B4:1.5 E4:0.5 G#4:0.5 B4:0.5 "
|
||||
"C5:1.5 E4:0.5 E5:0.5 D#5:0.5 E5:0.5 D#5:0.5 E5:0.5 B4:0.5 "
|
||||
"D5:0.5 C5:0.5 A4:1.5 C4:0.5 E4:0.5 A4:0.5 B4:1.5 E4:0.5 G#4:0.5 B4:0.5 C5:2",
|
||||
120.0,
|
||||
),
|
||||
Score(
|
||||
"greensleeves", "绿袖子", "英国传统", ("民歌", "小调"),
|
||||
"A4:1 C5:2 D5:1 E5:1.5 F5:0.5 E5:1 D5:2 B4:1 G4:1.5 A4:0.5 B4:1 C5:2 A4:1 A4:1.5 G#4:0.5 A4:1 B4:2 G4:1 "
|
||||
"A4:1 C5:2 D5:1 E5:1.5 F5:0.5 E5:1 D5:2 B4:1 G4:1.5 A4:0.5 B4:1 C5:2 A4:2",
|
||||
100.0,
|
||||
),
|
||||
Score(
|
||||
"swan_lake", "天鹅湖", "柴可夫斯基", ("古典", "小调"),
|
||||
"B4:2 E5:1 F#5:0.5 G#5:0.5 F#5:1 E5:1 "
|
||||
"D5:1 F#5:1 B4:2 -:1 "
|
||||
"B4:2 E5:1 F#5:0.5 G#5:0.5 F#5:1 E5:1 "
|
||||
"D5:1 F#5:1 B4:2 -:1",
|
||||
88.0,
|
||||
),
|
||||
Score(
|
||||
"turkish_march", "土耳其进行曲", "莫扎特", ("古典", "小调"),
|
||||
"B4:0.5 A4:0.5 G#4:0.5 A4:0.5 C5:0.5 B4:0.5 A4:0.5 G#4:0.5 "
|
||||
"A4:0.5 C5:0.5 B4:0.5 A4:0.5 G#4:0.5 A4:0.5 B4:0.5 C5:0.5 "
|
||||
"D5:0.5 C5:0.5 B4:0.5 C5:0.5 E5:0.5 D5:0.5 C5:0.5 B4:0.5 "
|
||||
"C5:0.5 E5:0.5 D5:0.5 C5:0.5 B4:0.5 C5:0.5 D5:0.5 E5:0.5",
|
||||
132.0,
|
||||
),
|
||||
Score(
|
||||
"vivaldi_spring", "春(第一乐章)", "维瓦尔第", ("古典", "大调"),
|
||||
"E5:1 E5:1 E5:1 G#5:1 G#5:1 G#5:1 "
|
||||
"F#5:1 E5:1 D#5:1 E5:1 F#5:1 E5:1 D#5:1 C#5:1 "
|
||||
"B4:1 C#5:1 D#5:1 E5:1 F#5:1 G#5:1 A5:1 B5:1 "
|
||||
"A5:2 G#5:2 E5:2 -:1",
|
||||
120.0,
|
||||
),
|
||||
Score(
|
||||
"canon_in_d", "卡农", "帕赫贝尔", ("古典", "大调"),
|
||||
"F#5:2 E5:2 D5:2 C#5:2 B4:2 A4:2 B4:2 C#5:2 "
|
||||
"D5:2 C#5:2 B4:2 A4:2 G4:2 F#4:2 G4:2 A4:2 "
|
||||
"B4:2 A4:2 G4:2 F#4:2 E4:2 D4:2 E4:2 F#4:2 "
|
||||
"G4:2 F#4:2 E4:2 D4:2 C#4:2 B3:2 C#4:2 D4:2",
|
||||
96.0,
|
||||
),
|
||||
Score(
|
||||
"beethoven_5th", "命运交响曲", "贝多芬", ("古典", "小调"),
|
||||
"G4:1 G4:1 G4:1 D#4:3 -:0.5 G4:1 G4:1 G4:1 D#4:3 -:0.5 "
|
||||
"G4:1 G4:1 G4:1 D#4:3 -:0.5 G4:1 G4:1 G4:1 D#4:3 -:0.5",
|
||||
108.0,
|
||||
),
|
||||
Score(
|
||||
"mozart_eine_kleine", "小夜曲", "莫扎特", ("古典", "大调"),
|
||||
"G4:1 D4:1 G4:1 D4:1 G4:1 D4:1 G4:0.5 B4:0.5 D5:1 "
|
||||
"C5:0.5 B4:0.5 C5:0.5 D5:0.5 C5:1 B4:1 G4:1 "
|
||||
"F#4:1 A4:1 D4:1 F#4:1 A4:1 C5:1 B4:0.5 A4:0.5 G4:1",
|
||||
132.0,
|
||||
),
|
||||
Score(
|
||||
"blue_danube", "蓝色多瑙河", "约翰·施特劳斯", ("古典", "大调"),
|
||||
"G4:0.5 G4:0.5 G4:1 B4:1 C5:1 D5:1 C5:1 B4:1 "
|
||||
"A4:1 G4:1 G4:1 B4:1 A4:1 G4:2 "
|
||||
"G4:0.5 G4:0.5 G4:1 B4:1 C5:1 D5:1 E5:1 D5:1 "
|
||||
"C5:1 B4:1 A4:1 G4:1 B4:2 G4:2",
|
||||
168.0,
|
||||
),
|
||||
)
|
||||
|
||||
BUILTIN_SCORES: tuple[Score, ...] = _BUILTIN
|
||||
|
||||
|
||||
def builtin_melodies(cfg: Config = DEFAULT) -> list[Melody]:
|
||||
"""返回全部内置曲目的 :class:`Melody` 列表。"""
|
||||
return [score.melody() for score in BUILTIN_SCORES]
|
||||
|
||||
|
||||
def get_score(song_id: str) -> Score | None:
|
||||
for score in BUILTIN_SCORES:
|
||||
if score.id == song_id:
|
||||
return score
|
||||
return None
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
"""检索引擎:两级检索 + 分数融合。
|
||||
|
||||
**第一级(粗召回)** 用 :mod:`qbh.index` 的多码本倒排索引,把候选从整库缩到
|
||||
几十首。**第二级(精排)** 对候选逐个做子序列 DTW + 移调搜索。最终分数是两者
|
||||
的加权和:
|
||||
|
||||
score = w_dtw · exp(−λ·平均代价) + w_index · 归一化重叠分
|
||||
|
||||
之所以不只用 DTW:索引分能区分「音程走向一致但细节不同」的近邻曲目;
|
||||
之所以不只用索引分:索引只看局部 n-gram 统计,无法判断整体旋律是否连续对齐。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .audio import preprocess, read_audio
|
||||
from .config import DEFAULT, Config
|
||||
from .dtw import align
|
||||
from .index import NgramIndex
|
||||
from .library import Library
|
||||
from .melody import Melody, fuse_repeated_notes
|
||||
from .notes import segment_notes
|
||||
from .pitch import extract_pitch
|
||||
|
||||
__all__ = ["Hit", "SearchResult", "SearchEngine"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Hit:
|
||||
"""一条检索结果。"""
|
||||
|
||||
song_id: str
|
||||
title: str
|
||||
score: float
|
||||
dtw_sim: float
|
||||
index_sim: float
|
||||
shift: float
|
||||
target_start_s: float
|
||||
target_end_s: float
|
||||
target_note_start: int
|
||||
target_note_end: int
|
||||
origin: str = ""
|
||||
tags: tuple[str, ...] = ()
|
||||
has_audio: bool = False
|
||||
path: list[tuple[int, int]] = field(default_factory=list)
|
||||
|
||||
def to_dict(self, *, include_path: bool = True) -> dict[str, Any]:
|
||||
out = {
|
||||
"song_id": self.song_id,
|
||||
"title": self.title,
|
||||
"score": round(self.score, 4),
|
||||
"dtw_sim": round(self.dtw_sim, 4),
|
||||
"index_sim": round(self.index_sim, 4),
|
||||
"shift": round(self.shift, 2),
|
||||
"target_start_s": round(self.target_start_s, 3),
|
||||
"target_end_s": round(self.target_end_s, 3),
|
||||
"target_note_start": self.target_note_start,
|
||||
"target_note_end": self.target_note_end,
|
||||
"origin": self.origin,
|
||||
"tags": list(self.tags),
|
||||
"has_audio": self.has_audio,
|
||||
}
|
||||
if include_path:
|
||||
out["path"] = [[int(i), int(j)] for i, j in self.path]
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class SearchResult:
|
||||
"""一次检索的完整结果。"""
|
||||
|
||||
query: Melody
|
||||
hits: list[Hit]
|
||||
elapsed_ms: float
|
||||
n_candidates: int
|
||||
n_songs: int
|
||||
coarse_recall: bool = False # 是否退化为全库扫描
|
||||
|
||||
def top(self) -> Hit | None:
|
||||
return self.hits[0] if self.hits else None
|
||||
|
||||
def to_dict(self, *, include_path: bool = True, include_query: bool = True) -> dict[str, Any]:
|
||||
out: dict[str, Any] = {
|
||||
"elapsed_ms": round(self.elapsed_ms, 2),
|
||||
"n_candidates": self.n_candidates,
|
||||
"n_songs": self.n_songs,
|
||||
"coarse_recall": self.coarse_recall,
|
||||
"hits": [h.to_dict(include_path=include_path) for h in self.hits],
|
||||
}
|
||||
if include_query:
|
||||
out["query"] = {
|
||||
"n_notes": self.query.n_notes,
|
||||
"duration": round(self.query.duration, 3),
|
||||
"midis": [round(float(v), 2) for v in self.query.midis],
|
||||
"starts": [round(float(v), 3) for v in self.query.starts],
|
||||
"durs": [round(float(v), 3) for v in self.query.durs],
|
||||
"contour": self.query.contour(),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
class SearchEngine:
|
||||
"""把曲库、倒排索引与 DTW 精排组装成可复用的检索引擎。"""
|
||||
|
||||
def __init__(self, library: Library, cfg: Config = DEFAULT):
|
||||
self.library = library
|
||||
self.cfg = cfg
|
||||
self.index = NgramIndex(cfg=cfg)
|
||||
self.rebuild_index()
|
||||
|
||||
# ---------------- 索引 ---------------- #
|
||||
def rebuild_index(self) -> int:
|
||||
melodies = self.library.melodies(refresh=True)
|
||||
self.index.build(melodies)
|
||||
return self.index.n_songs
|
||||
|
||||
def _melody_map(self) -> dict[str, Melody]:
|
||||
return {m.song_id: m for m in self.library.melodies()}
|
||||
|
||||
# ---------------- 检索 ---------------- #
|
||||
def search_melody(
|
||||
self,
|
||||
melody: Melody,
|
||||
*,
|
||||
top_k: int | None = None,
|
||||
with_path: bool = True,
|
||||
candidates: int | None = None,
|
||||
) -> SearchResult:
|
||||
"""对已提取的旋律做检索。"""
|
||||
started = time.perf_counter()
|
||||
top_k = top_k or self.cfg.top_k
|
||||
query = fuse_repeated_notes(melody, self.cfg)
|
||||
|
||||
if query.n_notes < 2 or self.index.n_songs == 0:
|
||||
return SearchResult(query, [], (time.perf_counter() - started) * 1000.0, 0, self.index.n_songs)
|
||||
|
||||
index_scores = self.index.score(query)
|
||||
ranked_index = sorted(index_scores.items(), key=lambda kv: (-kv[1], kv[0]))
|
||||
cand_list, _ = self.index.candidates(query, top_n=candidates)
|
||||
coarse_only = False
|
||||
if len(cand_list) < 5:
|
||||
# 候选不足:全库扫描保证召回
|
||||
cand_list = [(m.song_id, index_scores.get(m.song_id, 0.0)) for m in self.library.melodies()]
|
||||
coarse_only = True
|
||||
|
||||
melody_map = self._melody_map()
|
||||
scored: list[Hit] = []
|
||||
for song_id, idx_score in cand_list:
|
||||
target = melody_map.get(song_id)
|
||||
if target is None or target.n_notes < 2:
|
||||
continue
|
||||
alignment = align(query, target, self.cfg, need_path=False)
|
||||
if not np.isfinite(alignment.cost):
|
||||
continue
|
||||
fused = self.cfg.w_dtw * alignment.sim + self.cfg.w_index * float(idx_score)
|
||||
record = self.library.get_song(song_id)
|
||||
scored.append(
|
||||
Hit(
|
||||
song_id=song_id,
|
||||
title=record.title if record else song_id,
|
||||
score=fused,
|
||||
dtw_sim=alignment.sim,
|
||||
index_sim=float(idx_score),
|
||||
shift=alignment.shift,
|
||||
target_start_s=alignment.target_start_s,
|
||||
target_end_s=alignment.target_end_s,
|
||||
target_note_start=alignment.target_note_start,
|
||||
target_note_end=alignment.target_note_end,
|
||||
origin=record.origin if record else "",
|
||||
tags=record.tags if record else (),
|
||||
has_audio=record is not None and bool(record.audio_file),
|
||||
)
|
||||
)
|
||||
|
||||
scored.sort(key=lambda h: (-h.score, h.song_id))
|
||||
hits = scored[:top_k]
|
||||
|
||||
# 只对最终 Top-K 重算对齐路径,用于前端画对齐图
|
||||
if with_path:
|
||||
for hit in hits:
|
||||
target = melody_map.get(hit.song_id)
|
||||
if target is None:
|
||||
continue
|
||||
best = align(query, target, self.cfg, need_path=True)
|
||||
hit.path = best.path
|
||||
hit.target_start_s = best.target_start_s
|
||||
hit.target_end_s = best.target_end_s
|
||||
hit.target_note_start = best.target_note_start
|
||||
hit.target_note_end = best.target_note_end
|
||||
|
||||
elapsed = (time.perf_counter() - started) * 1000.0
|
||||
return SearchResult(
|
||||
query=query,
|
||||
hits=hits,
|
||||
elapsed_ms=elapsed,
|
||||
n_candidates=len(cand_list),
|
||||
n_songs=self.index.n_songs,
|
||||
coarse_recall=coarse_only,
|
||||
)
|
||||
|
||||
def search_audio(
|
||||
self,
|
||||
samples: np.ndarray,
|
||||
sr: int,
|
||||
*,
|
||||
top_k: int | None = None,
|
||||
cfg: Config | None = None,
|
||||
**preprocess_kwargs,
|
||||
) -> tuple[SearchResult, Any]:
|
||||
"""对原始音频做完整检索,返回 (结果, 基频轨迹)。"""
|
||||
cfg = cfg or self.cfg
|
||||
y = preprocess(samples, sr, cfg, **preprocess_kwargs)
|
||||
track = extract_pitch(y, cfg.sample_rate, cfg)
|
||||
melody = segment_notes(track, cfg)
|
||||
return self.search_melody(melody, top_k=top_k), track
|
||||
|
||||
def search_file(self, path: str | Path, *, top_k: int | None = None) -> SearchResult:
|
||||
samples, sr = read_audio(path)
|
||||
result, _ = self.search_audio(samples, sr, top_k=top_k)
|
||||
return result
|
||||
|
||||
# ---------------- 评估辅助 ---------------- #
|
||||
def coarse_candidates(self, melody: Melody) -> list[tuple[str, float]]:
|
||||
"""只跑粗召回,用于度量候选召回率。"""
|
||||
cand, _ = self.index.candidates(melody)
|
||||
return cand
|
||||
+394
@@ -0,0 +1,394 @@
|
||||
"""SQLite 持久化层:曲库、旋律特征、用户账号、检索历史。
|
||||
|
||||
用数据库而不是裸 JSON,是为了让曲库能真正做增删改查,并让「谁在什么时候
|
||||
哼了什么、返回了什么」可追溯。密码用标准库 ``hashlib.scrypt`` 加盐派生,
|
||||
不引入额外依赖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .melody import Melody
|
||||
|
||||
__all__ = ["SongRecord", "Store", "hash_password", "verify_password"]
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS songs (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
origin TEXT DEFAULT '',
|
||||
tags TEXT DEFAULT '',
|
||||
source TEXT DEFAULT '',
|
||||
midi_file TEXT DEFAULT '',
|
||||
audio_file TEXT DEFAULT '',
|
||||
n_notes INTEGER DEFAULT 0,
|
||||
duration REAL DEFAULT 0,
|
||||
median_pitch REAL DEFAULT 0,
|
||||
added_at TEXT DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS melodies (
|
||||
song_id TEXT PRIMARY KEY,
|
||||
payload TEXT NOT NULL,
|
||||
updated_at TEXT DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_salt TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
email TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'active'
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS search_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
created_at TEXT DEFAULT '',
|
||||
source TEXT DEFAULT '',
|
||||
query_notes INTEGER DEFAULT 0,
|
||||
query_melody TEXT DEFAULT '',
|
||||
top_song TEXT DEFAULT '',
|
||||
top_title TEXT DEFAULT '',
|
||||
top_score REAL DEFAULT 0,
|
||||
elapsed_ms REAL DEFAULT 0,
|
||||
results TEXT DEFAULT '',
|
||||
FOREIGN KEY (user_id) REFERENCES users (user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_history_user ON search_history(user_id, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_history_time ON search_history(id DESC);
|
||||
"""
|
||||
|
||||
_SCRYPT_N = 2**14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_DKLEN = 32
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def hash_password(password: str, salt: bytes | None = None) -> tuple[str, str]:
|
||||
"""返回 (salt_hex, hash_hex)。"""
|
||||
if salt is None:
|
||||
salt = os.urandom(16)
|
||||
derived = hashlib.scrypt(
|
||||
password.encode("utf-8"), salt=salt, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_DKLEN
|
||||
)
|
||||
return salt.hex(), derived.hex()
|
||||
|
||||
|
||||
def verify_password(password: str, salt_hex: str, hash_hex: str) -> bool:
|
||||
try:
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
except ValueError:
|
||||
return False
|
||||
_, derived = hash_password(password, salt)
|
||||
return hmac.compare_digest(derived, hash_hex)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SongRecord:
|
||||
"""曲库中的一首曲目。"""
|
||||
|
||||
id: str
|
||||
title: str
|
||||
origin: str = ""
|
||||
tags: tuple[str, ...] = ()
|
||||
source: str = ""
|
||||
midi_file: str = ""
|
||||
audio_file: str = ""
|
||||
n_notes: int = 0
|
||||
duration: float = 0.0
|
||||
median_pitch: float = 0.0
|
||||
added_at: str = field(default_factory=_now)
|
||||
|
||||
def to_row(self) -> dict[str, Any]:
|
||||
row = asdict(self)
|
||||
row["tags"] = ",".join(self.tags)
|
||||
return row
|
||||
|
||||
@classmethod
|
||||
def from_row(cls, row: sqlite3.Row) -> "SongRecord":
|
||||
tags = tuple(t for t in (row["tags"] or "").split(",") if t)
|
||||
return cls(
|
||||
id=row["id"],
|
||||
title=row["title"],
|
||||
origin=row["origin"] or "",
|
||||
tags=tags,
|
||||
source=row["source"] or "",
|
||||
midi_file=row["midi_file"] or "",
|
||||
audio_file=row["audio_file"] or "",
|
||||
n_notes=int(row["n_notes"] or 0),
|
||||
duration=float(row["duration"] or 0.0),
|
||||
median_pitch=float(row["median_pitch"] or 0.0),
|
||||
added_at=row["added_at"] or "",
|
||||
)
|
||||
|
||||
|
||||
class Store:
|
||||
"""轻量 SQLite 封装;写操作串行化,读操作可并发。"""
|
||||
|
||||
def __init__(self, path: str | Path):
|
||||
self.path = Path(path)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._lock = threading.RLock()
|
||||
self._conn = sqlite3.connect(str(self.path), check_same_thread=False)
|
||||
self._conn.row_factory = sqlite3.Row
|
||||
self._conn.execute("PRAGMA journal_mode=WAL")
|
||||
self._conn.execute("PRAGMA foreign_keys=ON")
|
||||
with self._lock:
|
||||
self._conn.executescript(_SCHEMA)
|
||||
self._conn.commit()
|
||||
|
||||
# ---------------- 连接 ---------------- #
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._conn.close()
|
||||
|
||||
def __enter__(self) -> "Store":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
# ---------------- 曲库 ---------------- #
|
||||
def upsert_song(self, record: SongRecord) -> None:
|
||||
row = record.to_row()
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"""
|
||||
INSERT INTO songs (id, title, origin, tags, source, midi_file, audio_file,
|
||||
n_notes, duration, median_pitch, added_at)
|
||||
VALUES (:id, :title, :origin, :tags, :source, :midi_file, :audio_file,
|
||||
:n_notes, :duration, :median_pitch, :added_at)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
title=excluded.title, origin=excluded.origin, tags=excluded.tags,
|
||||
source=excluded.source, midi_file=excluded.midi_file,
|
||||
audio_file=excluded.audio_file, n_notes=excluded.n_notes,
|
||||
duration=excluded.duration, median_pitch=excluded.median_pitch
|
||||
""",
|
||||
row,
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
def get_song(self, song_id: str) -> SongRecord | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT * FROM songs WHERE id = ?", (song_id,))
|
||||
row = cur.fetchone()
|
||||
return SongRecord.from_row(row) if row else None
|
||||
|
||||
def list_songs(self) -> list[SongRecord]:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT * FROM songs ORDER BY id")
|
||||
rows = cur.fetchall()
|
||||
return [SongRecord.from_row(r) for r in rows]
|
||||
|
||||
def count_songs(self) -> int:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT COUNT(*) AS c FROM songs")
|
||||
return int(cur.fetchone()["c"])
|
||||
|
||||
def delete_song(self, song_id: str) -> bool:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("DELETE FROM songs WHERE id = ?", (song_id,))
|
||||
self._conn.execute("DELETE FROM melodies WHERE song_id = ?", (song_id,))
|
||||
self._conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
def clear_library(self) -> None:
|
||||
with self._lock:
|
||||
self._conn.execute("DELETE FROM songs")
|
||||
self._conn.execute("DELETE FROM melodies")
|
||||
self._conn.commit()
|
||||
|
||||
# ---------------- 旋律特征 ---------------- #
|
||||
def set_melody(self, mel: Melody) -> None:
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"INSERT INTO melodies (song_id, payload, updated_at) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(song_id) DO UPDATE SET payload=excluded.payload, "
|
||||
"updated_at=excluded.updated_at",
|
||||
(mel.song_id, mel.to_json(), _now()),
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
def set_melodies(self, melodies: Iterable[Melody]) -> int:
|
||||
rows = [(m.song_id, m.to_json(), _now()) for m in melodies]
|
||||
with self._lock:
|
||||
self._conn.executemany(
|
||||
"INSERT INTO melodies (song_id, payload, updated_at) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(song_id) DO UPDATE SET payload=excluded.payload, "
|
||||
"updated_at=excluded.updated_at",
|
||||
rows,
|
||||
)
|
||||
self._conn.commit()
|
||||
return len(rows)
|
||||
|
||||
def get_melody(self, song_id: str) -> Melody | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"SELECT payload FROM melodies WHERE song_id = ?", (song_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return Melody.from_json(row["payload"]) if row else None
|
||||
|
||||
def all_melodies(self) -> list[Melody]:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT payload FROM melodies ORDER BY song_id")
|
||||
rows = cur.fetchall()
|
||||
return [Melody.from_json(r["payload"]) for r in rows]
|
||||
|
||||
# ---------------- 用户 ---------------- #
|
||||
def create_user(
|
||||
self, username: str, password: str, email: str = ""
|
||||
) -> tuple[bool, str]:
|
||||
username = username.strip()
|
||||
if len(username) < 3:
|
||||
return False, "用户名至少 3 个字符"
|
||||
if len(password) < 6:
|
||||
return False, "密码至少 6 个字符"
|
||||
salt_hex, hash_hex = hash_password(password)
|
||||
try:
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"INSERT INTO users (username, password_salt, password_hash, email, "
|
||||
"created_at, status) VALUES (?, ?, ?, ?, ?, 'active')",
|
||||
(username, salt_hex, hash_hex, email, _now()),
|
||||
)
|
||||
self._conn.commit()
|
||||
except sqlite3.IntegrityError:
|
||||
return False, "用户名已存在"
|
||||
return True, "注册成功"
|
||||
|
||||
def verify_user(self, username: str, password: str) -> int | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"SELECT user_id, password_salt, password_hash, status FROM users "
|
||||
"WHERE username = ?",
|
||||
(username.strip(),),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row or row["status"] != "active":
|
||||
return None
|
||||
if not verify_password(password, row["password_salt"], row["password_hash"]):
|
||||
return None
|
||||
return int(row["user_id"])
|
||||
|
||||
def get_user(self, user_id: int) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"SELECT user_id, username, email, created_at, status FROM users "
|
||||
"WHERE user_id = ?",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
# ---------------- 检索历史 ---------------- #
|
||||
def add_history(
|
||||
self,
|
||||
*,
|
||||
user_id: int | None,
|
||||
source: str,
|
||||
query_notes: int,
|
||||
query_melody: str,
|
||||
top_song: str,
|
||||
top_title: str,
|
||||
top_score: float,
|
||||
elapsed_ms: float,
|
||||
results: list[dict[str, Any]],
|
||||
) -> int:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"INSERT INTO search_history (user_id, created_at, source, query_notes, "
|
||||
"query_melody, top_song, top_title, top_score, elapsed_ms, results) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
user_id,
|
||||
_now(),
|
||||
source,
|
||||
query_notes,
|
||||
query_melody,
|
||||
top_song,
|
||||
top_title,
|
||||
float(top_score),
|
||||
float(elapsed_ms),
|
||||
json.dumps(results, ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
self._conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
|
||||
def list_history(self, user_id: int | None = None, limit: int = 50) -> list[dict[str, Any]]:
|
||||
with self._lock:
|
||||
if user_id is None:
|
||||
cur = self._conn.execute(
|
||||
"SELECT * FROM search_history ORDER BY id DESC LIMIT ?", (limit,)
|
||||
)
|
||||
else:
|
||||
cur = self._conn.execute(
|
||||
"SELECT * FROM search_history WHERE user_id = ? ORDER BY id DESC LIMIT ?",
|
||||
(user_id, limit),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
try:
|
||||
item["results"] = json.loads(item.get("results") or "[]")
|
||||
except json.JSONDecodeError:
|
||||
item["results"] = []
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
def clear_history(self, user_id: int | None = None) -> int:
|
||||
with self._lock:
|
||||
if user_id is None:
|
||||
cur = self._conn.execute("DELETE FROM search_history")
|
||||
else:
|
||||
cur = self._conn.execute(
|
||||
"DELETE FROM search_history WHERE user_id = ?", (user_id,)
|
||||
)
|
||||
self._conn.commit()
|
||||
return cur.rowcount
|
||||
|
||||
# ---------------- 元数据 ---------------- #
|
||||
def set_meta(self, key: str, value: Any) -> None:
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"INSERT INTO meta (key, value) VALUES (?, ?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
||||
(key, json.dumps(value, ensure_ascii=False)),
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
def get_meta(self, key: str, default: Any = None) -> Any:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT value FROM meta WHERE key = ?", (key,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return default
|
||||
try:
|
||||
return json.loads(row["value"])
|
||||
except json.JSONDecodeError:
|
||||
return default
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
"""旋律合成:把音符序列渲染成可听音频。
|
||||
|
||||
两个用途:
|
||||
|
||||
* **曲库回放**——给每首曲目生成一段示范音频,前端可试听;
|
||||
* **评测查询**——按「人哼唱」的特点(起音滑音、颤音、弱谐波、呼吸噪声)
|
||||
合成查询音频,再交给完整流水线识别,从而端到端地度量系统性能。
|
||||
|
||||
注意:用同一套合成器生成曲库与查询会让评测偏乐观,因此正式评测
|
||||
以磁盘上的**真实 MIDI** 曲库为准,合成曲库只用于规模化测试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .melody import Melody
|
||||
|
||||
__all__ = ["render_notes", "render_melody", "SONG_TIMBRE", "HUM_TIMBRE"]
|
||||
|
||||
#: 曲库示范音:谐波较丰富、颤音浅、噪声低
|
||||
SONG_TIMBRE: dict = dict(
|
||||
harmonics=(1.0, 0.45, 0.22, 0.12, 0.06),
|
||||
vibrato_hz=5.0,
|
||||
vibrato_depth=0.12,
|
||||
glide_s=0.012,
|
||||
noise_sigma=0.0015,
|
||||
note_gap=0.06,
|
||||
)
|
||||
|
||||
#: 哼唱查询音:谐波弱、颤音深、起音滑音明显、呼吸噪声大
|
||||
HUM_TIMBRE: dict = dict(
|
||||
harmonics=(1.0, 0.30, 0.10, 0.04),
|
||||
vibrato_hz=5.4,
|
||||
vibrato_depth=0.30,
|
||||
glide_s=0.045,
|
||||
noise_sigma=0.004,
|
||||
note_gap=0.04,
|
||||
)
|
||||
|
||||
|
||||
def render_notes(
|
||||
midis: np.ndarray,
|
||||
starts: np.ndarray,
|
||||
durs: np.ndarray,
|
||||
sr: int = DEFAULT.sample_rate,
|
||||
*,
|
||||
harmonics: tuple[float, ...] = (1.0, 0.45, 0.22, 0.12, 0.06),
|
||||
vibrato_hz: float = 5.0,
|
||||
vibrato_depth: float = 0.12,
|
||||
glide_s: float = 0.012,
|
||||
noise_sigma: float = 0.0015,
|
||||
note_gap: float = 0.06,
|
||||
attack_s: float = 0.03,
|
||||
release_s: float = 0.08,
|
||||
sustain: float = 0.78,
|
||||
peak: float = 0.85,
|
||||
seed: int = 0,
|
||||
) -> np.ndarray:
|
||||
"""加法合成一段旋律,返回 float32 单声道波形。"""
|
||||
midis = np.asarray(midis, dtype=np.float64).reshape(-1)
|
||||
starts = np.asarray(starts, dtype=np.float64).reshape(-1)
|
||||
durs = np.asarray(durs, dtype=np.float64).reshape(-1)
|
||||
if midis.size == 0:
|
||||
return np.zeros(int(0.1 * sr), dtype=np.float32)
|
||||
|
||||
rng = np.random.default_rng(seed)
|
||||
total = float(starts[-1] + durs[-1] + release_s + 0.05)
|
||||
n_total = int(total * sr) + 1
|
||||
out = np.zeros(n_total, dtype=np.float64)
|
||||
|
||||
for i in range(midis.size):
|
||||
sounding = max(float(durs[i]) * (1.0 - note_gap), 0.02)
|
||||
n_samp = int(sounding * sr)
|
||||
if n_samp < 16:
|
||||
continue
|
||||
t = np.arange(n_samp, dtype=np.float64) / sr
|
||||
|
||||
base = float(midis[i])
|
||||
if glide_s > 0.0 and i > 0:
|
||||
g = np.clip(t / glide_s, 0.0, 1.0)
|
||||
g = g * g * (3.0 - 2.0 * g) # smoothstep
|
||||
pitch = float(midis[i - 1]) + (base - float(midis[i - 1])) * g
|
||||
else:
|
||||
pitch = np.full(n_samp, base)
|
||||
|
||||
# 颤音在起音后渐入,避免开头就抖
|
||||
if vibrato_depth > 0.0:
|
||||
ramp = np.minimum(t / 0.15, 1.0)
|
||||
pitch = pitch + vibrato_depth * ramp * np.sin(2.0 * np.pi * vibrato_hz * t)
|
||||
|
||||
freq = 440.0 * np.power(2.0, (pitch - 69.0) / 12.0)
|
||||
phase = 2.0 * np.pi * np.cumsum(freq) / sr
|
||||
|
||||
sig = np.zeros(n_samp, dtype=np.float64)
|
||||
for k, amp in enumerate(harmonics, start=1):
|
||||
if amp <= 0.0:
|
||||
continue
|
||||
sig += amp * np.sin(k * phase + rng.uniform(0.0, 2.0 * np.pi))
|
||||
|
||||
env = np.full(n_samp, sustain, dtype=np.float64)
|
||||
a_n = min(int(attack_s * sr), n_samp)
|
||||
if a_n > 1:
|
||||
env[:a_n] = np.linspace(0.0, 1.0, a_n)
|
||||
r_n = min(int(release_s * sr), n_samp)
|
||||
if r_n > 1:
|
||||
env[-r_n:] *= np.linspace(1.0, 0.0, r_n)
|
||||
sig *= env
|
||||
|
||||
i0 = int(float(starts[i]) * sr)
|
||||
i1 = min(i0 + n_samp, n_total)
|
||||
if i1 <= i0:
|
||||
continue
|
||||
out[i0:i1] += sig[: i1 - i0]
|
||||
|
||||
if noise_sigma > 0.0:
|
||||
out += rng.normal(0.0, noise_sigma, n_total)
|
||||
|
||||
peak_val = float(np.abs(out).max())
|
||||
if peak_val > 0.0:
|
||||
out *= peak / peak_val
|
||||
return out.astype(np.float32)
|
||||
|
||||
|
||||
def render_melody(
|
||||
mel: Melody,
|
||||
sr: int = DEFAULT.sample_rate,
|
||||
*,
|
||||
timbre: str = "song",
|
||||
seed: int = 0,
|
||||
**overrides,
|
||||
) -> np.ndarray:
|
||||
"""按预设音色渲染旋律。``timbre`` 取 ``"song"`` 或 ``"hum"``。"""
|
||||
params = dict(SONG_TIMBRE if timbre == "song" else HUM_TIMBRE)
|
||||
params.update(overrides)
|
||||
return render_notes(
|
||||
mel.midis, mel.starts, mel.durs, sr, seed=seed, **params
|
||||
)
|
||||
Reference in New Issue
Block a user