Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
@@ -0,0 +1,9 @@
|
|||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.pytest_cache/
|
||||||
|
data/qbh.db*
|
||||||
|
data/audio/
|
||||||
|
data/uploads/
|
||||||
|
data/*.png
|
||||||
|
*.egg-info/
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# 基于旋律的音乐哼唱检索系统(QBH)实现计划
|
||||||
|
|
||||||
|
## 背景(已勘察确认)
|
||||||
|
|
||||||
|
本机存在**同一任务的 8 个既往实现**(`F:\软件\基于旋律的音乐哼唱检索系统\`,含 `对比.xlsx` 与各模型 UI 截图),以及 `F:\glm\test20260827`、`F:\hy\test20260828`、`F:\qwen\test20260827` 等平行工作区。`对比.xlsx` 只记录了**用时/Token/费用**,未对输出质量打分。
|
||||||
|
|
||||||
|
8 个既往实现的共同短板:
|
||||||
|
1. **自证式评测**——曲库与查询由同一个合成器生成,准确率被高估(qwen 用真实曲谱测出 76% Top-1,是唯一诚实的数字)。
|
||||||
|
2. **曲库规模悬殊**(12~300 首),无共享基准。
|
||||||
|
3. 普遍缺少噪声鲁棒性量化、缺少可复现的评测产物。
|
||||||
|
|
||||||
|
本次实现的目标:功能完整 + **用真实曲库做可复现的诚实评测** + 补齐既往缺失的鲁棒性与规模化证据。
|
||||||
|
|
||||||
|
## 环境结论(已验证)
|
||||||
|
|
||||||
|
- Python 3.14.6(`C:\Python314`),当前仅装 pip;`tkinter`/`tcl` 可用。
|
||||||
|
- PyPI 轮子可用性:`numpy 2.5.3` ✅cp314、`scipy 1.18.1` ✅cp314、`fastapi`/`uvicorn`/`soundfile` 纯 Python ✅、`sounddevice 0.5.6` ✅`py3-none-win_amd64`。
|
||||||
|
- `matplotlib` 的 cp314 轮子无法确认 → **设为可选依赖**,图表改用浏览器 Canvas / Tkinter Canvas 绘制。
|
||||||
|
- 密码哈希改用 **stdlib `hashlib.scrypt`**(避免 `bcrypt` 的 cp314 风险)。
|
||||||
|
|
||||||
|
## 目录结构(`F:\zcode\test20260908\`)
|
||||||
|
|
||||||
|
```
|
||||||
|
qbh/ config audio pitch notes melody midiio scores synth
|
||||||
|
index dtw search store library evaluate bench
|
||||||
|
app/ main.py(FastAPI) + static/{index.html,app.js,style.css}
|
||||||
|
desktop/ client.py (Tkinter 客户端,调用同一 REST API)
|
||||||
|
scripts/ build_library run_eval run_bench noise_experiment
|
||||||
|
tests/ test_pitch notes midiio index dtw search store api
|
||||||
|
data/ midi/(复制 27 首真实 MIDI) audio/(合成回放) qbh.db
|
||||||
|
docs/ 设计文档.md 评测报告.md 界面说明.md
|
||||||
|
run.py run_desktop.py cli.py README.md requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 算法设计(融合 8 个既往实现中最有效的部分)
|
||||||
|
|
||||||
|
**1. 预处理** `audio.py`:stdlib `wave`+numpy 读 WAV;`scipy.signal.resample_poly` 重采样至 16 kHz;4 阶 Butterworth 带通 60–2000 Hz(哼唱频带);滑动均值去噪;RMS 归一化 + 静音裁剪。
|
||||||
|
|
||||||
|
**2. 音高提取** `pitch.py`:**向量化 YIN**——差函数用 FFT 自相关 + 前缀和改写为 `d(τ)=e1+e2−2·r(τ)`,避免 O(N·τ) 循环;CMNDF 归一化;阈值 0.12 + 首个局部极小 + 抛物线插值;帧 48 ms / 跳 10 ms。附加 **八度跳变修正**(与局部中值偏差落在 9–15 半音时折叠 ±12)与置信度/能量双重有声门限。
|
||||||
|
|
||||||
|
**3. 音符切分** `notes.py`:7 帧中值滤波 + 平滑;有声段切分阈值 0.8 半音;间隙 <60 ms 桥接;**重复音融合**(|Δ|<0.35 且间隙 < max(0.06, dur×0.9),**查询端与曲库端对称执行**——glm 报告此单项将 Top-1 从 68% 提到 100%);丢弃 <70 ms 短音;尾部房间噪声能量门限。
|
||||||
|
|
||||||
|
**4. 旋律表示** `melody.py`:MIDI 音高 / 起音时刻 / 时长;派生**音程序列**(移调不变)、**归一化时值**(除以中值,速度不变)、U/D/R 轮廓、对数时长比。
|
||||||
|
|
||||||
|
**5. 粗召回** `index.py`:**多码本音程 n-gram 倒排索引**——精确 3/4-gram、量级 4/5-gram、方向 5/6-gram、节奏 3/4-gram;IDF 加权 + `min(count_q,count_s)` 重叠打分;轮廓 delete-1 变体容忍增删;取 `max(40, 7√N)` 候选并设 10% 分数下限,不足则回退全库。
|
||||||
|
|
||||||
|
**6. 精排** `dtw.py`:**子序列 DTW**(起点开放 `D[0,:]=0`、终点取末行最小,支持只哼副歌片段);音高代价带**自由带** `clip(|Δ|−0.6,0,cap)` 吸收 YIN 量化误差;时长代价 `clip(|ln 比值|,cap)`;**粗到细移调搜索**(直方图匹配取 ±12 内 top-8 整数移调,各扩 ±1);行递推用前缀和最小值技巧向量化。
|
||||||
|
|
||||||
|
**7. 检索与融合** `search.py`:`score = w₁·dtw_sim + w₂·idx_sim`(可选第三通道:帧级轮廓 DTW,权重小);命中返回移调量、匹配片段起止秒、对齐路径。
|
||||||
|
|
||||||
|
**8. 曲库** `scores.py`(内置约 50 首简谱记谱)+ `midiio.py`(自研 MIDI 解析,不依赖 mido)+ `library.py`(**复制 `F:\glm\test20260827\data\midi` 的 27 首真实公版旋律到 `data/midi/`**,源目录只读不动)+ `store.py`(SQLite:`songs`/`melody_features`/`index`/`users`/`search_history`)。
|
||||||
|
|
||||||
|
## 评测(本次的核心差异化)
|
||||||
|
|
||||||
|
`evaluate.py`:查询合成器(切片 8–20 音 → 移调 ±5/±12 → 速度 0.8–1.3× → 音高抖动 σ=0.35 半音+慢漂移 → 5% 丢音/分裂、3% 插音 → 颤音/滑音 → 指定 SNR 加噪)→ 跑完整 audio→feature→search 链路。
|
||||||
|
|
||||||
|
指标:**Top-1/3/5/10、MRR、MAP、候选召回率、延迟 p50/p95**,附逐查询明细与失败分类。
|
||||||
|
|
||||||
|
**三套评测集**(既往均未同时做到):
|
||||||
|
- **A. 27 首真实 MIDI**(真实旋律,权威真值)
|
||||||
|
- **B. 内置约 50 首曲库**(自包含,权威真值)
|
||||||
|
- **C. 合成大规模库**(300/600/1000 首,测扩展性)
|
||||||
|
|
||||||
|
外加**易/难分层**(难:40–80% 片段 + 更强扰动)与 **SNR 消融曲线**(20→5 dB)。
|
||||||
|
|
||||||
|
## 额外能力(按你的选择)
|
||||||
|
|
||||||
|
- **噪声鲁棒性实验** `scripts/noise_experiment.py`:SNR 20/15/12.5/10/7.5/5 dB 下的 Top-1 曲线;预处理(去噪+带通)开/关对照;输出 CSV + 浏览器可看的 SVG(matplotlib 装了则另出 PNG)。
|
||||||
|
- **用户账号与检索历史**:SQLite `users`(`hashlib.scrypt` 加盐哈希)+ 登录会话 + 每次检索落库,Web 与桌面端都可查看历史。
|
||||||
|
- **大规模基准** `bench.py`:300/600/1000 首曲库下的候选召回率与 p50/p95 延迟。
|
||||||
|
|
||||||
|
## 界面
|
||||||
|
|
||||||
|
- **Web(主)** `app/main.py` + 原生 JS 单页:浏览器麦克风录音(MediaRecorder→16 kHz WAV 客户端编码)、文件上传、随机示范查询;音高轮廓阶梯图、Top-K 结果与分数拆解、DTW 对齐图、匹配片段一键回放、曲库管理、登录/历史。端口 **8700**(避开既往 8000/8090/8614/8636)。端点:`/api/search`、`/api/library`、`/api/auth/*`、`/api/history`、`/api/eval/*`。
|
||||||
|
- **桌面(附)** `desktop/client.py`:Tkinter,调用同一 REST API;`sounddevice` 可用则录音、否则文件选择;轮廓用 `tk.Canvas` 绘制(不依赖 matplotlib);含历史列表。
|
||||||
|
|
||||||
|
## 实施顺序
|
||||||
|
|
||||||
|
1. 建 venv(`.venv`)+ 安装核心依赖 + 导入冒烟测试
|
||||||
|
2. `audio.py` → `pitch.py`(YIN)+ 合成正弦/扫频单元测试
|
||||||
|
3. `notes.py` → `melody.py` + 测试
|
||||||
|
4. `scores.py`(内置曲库)→ `midiio.py` → 复制 27 首真实 MIDI → `store.py`/`library.py`
|
||||||
|
5. `index.py` → `dtw.py` → `search.py` + 测试
|
||||||
|
6. `evaluate.py` → 跑 A/B 两套评测 → 调参(候选数、时长权重、自由带宽度)
|
||||||
|
7. FastAPI 后端 + Web 前端
|
||||||
|
8. Tkinter 桌面客户端
|
||||||
|
9. 账号/历史 + `bench.py` + `noise_experiment.py`
|
||||||
|
10. 文档(README、设计文档、评测报告、界面说明)
|
||||||
|
11. 全量 pytest + 启动服务做 HTTP 端到端验证 + 结果写入 `docs/评测报告.md`
|
||||||
|
|
||||||
|
## 验收标准
|
||||||
|
|
||||||
|
- `python -m pytest tests` 全绿。
|
||||||
|
- `python cli.py eval` 在 **27 首真实 MIDI** 上产出可复现数字(固定随机种子),写入评测报告;同时给出内置曲库结果与 SNR 消融曲线。
|
||||||
|
- `python run.py` 启动后,浏览器可录音/上传并返回排序结果与轮廓/对齐图;`curl` 冒烟通过。
|
||||||
|
- `python run_desktop.py` 能完成一次完整检索。
|
||||||
|
- README 中如实标注:合成查询在合成曲库上的数字偏乐观,真实曲库数字才是可信基线。
|
||||||
|
|
||||||
|
## 说明
|
||||||
|
|
||||||
|
- 只**复制**(不修改)`F:\glm\test20260827\data\midi` 的 27 个 MIDI 文件到新项目 `data/midi/`。
|
||||||
|
- 不触碰任何既有工作区;所有新代码写入 `F:\zcode\test20260908\`。
|
||||||
|
- 目标规模约 4,000–5,000 行(含测试与文档)。
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
# 基于旋律的音乐哼唱检索系统(Query by Humming)
|
||||||
|
|
||||||
|
对着麦克风哼一段旋律,系统在曲库里找出对应的那首歌。
|
||||||
|
|
||||||
|
本项目是一个**完整可运行**的哼唱检索(QBH)系统:浏览器录音 → YIN 基频提取 →
|
||||||
|
音符切分 → 旋律表示 → 多码本倒排索引粗召回 → 子序列 DTW 精排 → Top-K 结果,
|
||||||
|
附带 Web 界面、桌面客户端、账号与检索历史、可复现的评测与实验脚本。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1) 安装依赖(Python 3.12+,已在 3.14.6 / Windows 上验证)
|
||||||
|
python -m venv .venv
|
||||||
|
.venv\Scripts\python.exe -m pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 2) 启动 Web 服务(首次启动会自动构建曲库与索引,约 3 秒)
|
||||||
|
.venv\Scripts\python.exe run.py
|
||||||
|
# 浏览器会自动打开 http://127.0.0.1:8700
|
||||||
|
```
|
||||||
|
|
||||||
|
界面上有三种查询方式:
|
||||||
|
|
||||||
|
| 方式 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 🎤 录音 | 浏览器麦克风实时录音,客户端重采样到 16 kHz 后上传 |
|
||||||
|
| 📁 文件 | 上传 WAV / MP3 / FLAC |
|
||||||
|
| 🎲 随机示范 | 由合成器生成一条**已知答案**的机器哼唱,用于快速验证系统 |
|
||||||
|
|
||||||
|
桌面客户端(复用同一套 REST 接口):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv\Scripts\python.exe run_desktop.py # 默认连接 127.0.0.1:8700
|
||||||
|
```
|
||||||
|
|
||||||
|
命令行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python cli.py list # 列出曲库
|
||||||
|
python cli.py search hum.wav --top-k 5 # 用音频文件检索
|
||||||
|
python cli.py demo --difficulty hard # 生成困难难度的示范查询
|
||||||
|
python cli.py eval --per-song 3 # 跑评测
|
||||||
|
python cli.py bench --sizes 300,600,1000 # 大规模基准
|
||||||
|
python cli.py noise # 噪声鲁棒性实验
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 系统架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────── 查询侧 ────────────────┐
|
||||||
|
麦克风/文件 → 预处理 → YIN 基频 → 音符切分 → 旋律表示 ─┐
|
||||||
|
│
|
||||||
|
┌──────────────── 曲库侧 ────────────────┤
|
||||||
|
内置曲谱 ─┐ │
|
||||||
|
MIDI 文件 ─┼→ 旋律特征 → SQLite → 多码本倒排索引 ──────┤
|
||||||
|
导入音频 ─┘ │
|
||||||
|
▼
|
||||||
|
粗召回(n-gram 倒排索引)
|
||||||
|
│
|
||||||
|
精排(子序列 DTW + 移调搜索)
|
||||||
|
│
|
||||||
|
分数融合 → Top-K 结果 + 对齐可视化
|
||||||
|
```
|
||||||
|
|
||||||
|
### 模块
|
||||||
|
|
||||||
|
| 模块 | 职责 |
|
||||||
|
|---|---|
|
||||||
|
| `qbh/config.py` | 全部算法阈值集中管理(冻结 dataclass,便于消融) |
|
||||||
|
| `qbh/audio.py` | WAV 读写、重采样、带通滤波、去噪、静音裁剪、归一化 |
|
||||||
|
| `qbh/pitch.py` | 向量化 YIN 基频提取 + 八度跳变修正 + 有声判定 |
|
||||||
|
| `qbh/notes.py` | 音符切分、间隙桥接、重复音融合 |
|
||||||
|
| `qbh/melody.py` | 旋律表示:音程序列、归一化时值、轮廓串 |
|
||||||
|
| `qbh/midiio.py` | 自研 MIDI 读写(不依赖 mido / pretty_midi) |
|
||||||
|
| `qbh/scores.py` | 34 首内置曲谱(简谱式记谱 DSL) |
|
||||||
|
| `qbh/synth.py` | 旋律合成(曲库示范音 / 哼唱查询音) |
|
||||||
|
| `qbh/index.py` | 多码本音程 n-gram 倒排索引 + IDF 加权 |
|
||||||
|
| `qbh/dtw.py` | 子序列 DTW、移调搜索、向量化行递推 |
|
||||||
|
| `qbh/search.py` | 两级检索引擎与分数融合 |
|
||||||
|
| `qbh/store.py` | SQLite:曲库 / 旋律 / 用户 / 检索历史 |
|
||||||
|
| `qbh/library.py` | 曲库构建、导入、示范音频管理 |
|
||||||
|
| `qbh/evaluate.py` | 哼唱查询合成、指标计算、SNR 消融 |
|
||||||
|
| `qbh/bench.py` | 大规模基准与合成旋律生成 |
|
||||||
|
| `app/main.py` | FastAPI 后端(检索 / 曲库 / 账号 / 历史 / 评测) |
|
||||||
|
| `app/static/` | 前端单页应用(原生 JS,无构建步骤) |
|
||||||
|
| `desktop/client.py` | Tkinter 桌面客户端 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心算法
|
||||||
|
|
||||||
|
### 1. 基频提取:向量化 YIN
|
||||||
|
|
||||||
|
YIN 的差函数原始定义需要 `O(N·τ)` 的双重求和。这里用恒等式
|
||||||
|
|
||||||
|
```
|
||||||
|
d(τ) = e1 + e2(τ) − 2·A(τ)
|
||||||
|
```
|
||||||
|
|
||||||
|
把逐帧计算改写成「平方前缀和 + FFT 互相关」,整段音频一次性批量算完。
|
||||||
|
一段 10 秒哼唱通常几十毫秒内完成。
|
||||||
|
|
||||||
|
选基音周期时没有用「首次低于阈值后取 ±3 邻域最小」的常见写法——低基频
|
||||||
|
(如 110 Hz)的 CMNDF 谷很宽,那个写法会系统性高估基频。本实现改为
|
||||||
|
**先定位所有局部极小,再取其中最早的一个低于阈值者**,并对谷底做抛物线插值。
|
||||||
|
实测纯音误差 < 0.03 半音。
|
||||||
|
|
||||||
|
此外还有两级纠错:
|
||||||
|
|
||||||
|
- **八度折叠**:与局部中值偏差落在 9–15 半音时折叠 ±12,修正 YIN 最常见的倍频误判;
|
||||||
|
- **双重有声判定**:置信度阈值 + 相对峰值能量门限,并对绝对静音单独设门(全零信号上
|
||||||
|
CMNDF 恒为 0,会被误判为满置信度)。
|
||||||
|
|
||||||
|
### 2. 音符切分
|
||||||
|
|
||||||
|
中值滤波去颤音毛刺 → 按音高突变或有声中断分段 → 合并音高接近且时间相邻的段 →
|
||||||
|
**重复音融合** → 丢弃过短音符。
|
||||||
|
|
||||||
|
其中「重复音融合」是准确率的关键:声学切分无法把一个持续音切成两半,而乐谱里
|
||||||
|
反复音是分开写的。**在查询端和曲库端对称地**把相邻同音高音符合并(时长累加),
|
||||||
|
两侧的表示才能对齐。实测这一项把 Top-1 从 6/10 提升到 39/43。
|
||||||
|
|
||||||
|
### 3. 旋律表示
|
||||||
|
|
||||||
|
统一用「连续 MIDI 音高 + 起音时刻 + 时长」三个等长数组表示。派生特征刻意设计成
|
||||||
|
对移调/速度不敏感:
|
||||||
|
|
||||||
|
| 特征 | 不变性 |
|
||||||
|
|---|---|
|
||||||
|
| `intervals()` 相邻音高差 | 移调不变 |
|
||||||
|
| `norm_durs()` 时值 ÷ 中值 | 速度不变 |
|
||||||
|
| `contour()` 上行/保持/下行串 | 两者皆不变 |
|
||||||
|
|
||||||
|
### 4. 粗召回:多码本 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)` 重叠度;候选数取
|
||||||
|
`max(40, 7·√N)` 并施加分数下限,候选不足时回退全库扫描。
|
||||||
|
|
||||||
|
### 5. 精排:子序列 DTW + 移调搜索
|
||||||
|
|
||||||
|
**开放起止**:起始代价置零(`D[0,:]=0`)、终点取末行最小值,因此查询可以落在
|
||||||
|
曲库旋律的任意连续片段上——人常常只哼副歌。
|
||||||
|
|
||||||
|
**自由带**:音高代价先减掉 0.3 半音再截断,吸收 YIN 在颤音/滑音处的量化误差。
|
||||||
|
|
||||||
|
**移调搜索**:主估计用**中值音高差**(整条旋律被整体移调后,两侧中值音高差就等于
|
||||||
|
移调量,且天然覆盖跨八度),再叠加音高直方图重叠度的 top 候选各扩 ±1。这比在
|
||||||
|
±12 半音上穷举快得多,也修正了「+17 半音查询永远匹配不上」的边界问题。
|
||||||
|
|
||||||
|
**向量化行递推**:`B[j] = min(A[j] − S[j−1], B[j−1])` 是累积最小,用
|
||||||
|
`np.minimum.accumulate` 一次算完,避免 Python 层双重循环(与朴素实现误差 < 1e-14)。
|
||||||
|
|
||||||
|
### 6. 分数融合
|
||||||
|
|
||||||
|
```
|
||||||
|
score = w_dtw · exp(−λ·平均代价) + w_index · 归一化重叠分
|
||||||
|
```
|
||||||
|
|
||||||
|
索引分能区分「音程走向一致但细节不同」的近邻曲目;DTW 分能判断整体旋律是否
|
||||||
|
连续对齐。默认 `w_dtw = 0.8`、`w_index = 0.2`、`λ = 0.6`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 曲库
|
||||||
|
|
||||||
|
默认曲库 **43 首**:
|
||||||
|
|
||||||
|
- **27 首真实 MIDI**(`data/midi/`,公版旋律:致爱丽丝、绿袖子、茉莉花、送别、
|
||||||
|
欢乐颂、天鹅湖、土耳其进行曲…… 其中 6 首为五声音阶合成旋律)
|
||||||
|
- **16 首内置曲谱**(`qbh/scores.py`,简谱式记谱 DSL,中西民歌与古典主题)
|
||||||
|
|
||||||
|
同名曲目会自动去重(以真实 MIDI 为准),避免两个版本互为近邻干扰检索。
|
||||||
|
|
||||||
|
支持通过界面或 `python cli.py import song.mid` 继续导入 MIDI / 音频。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 评测结果
|
||||||
|
|
||||||
|
评测用**显式扰动模型**合成「像人哼唱」的查询:取连续片段 → 移调 ±5 半音
|
||||||
|
(12% 概率再 ±12)→ 速度 0.82–1.28× → 逐音抖动 σ≈0.35 半音 + 缓慢漂移 →
|
||||||
|
丢音/劈音/插音 → 按哼唱音色渲染(滑音、颤音、弱谐波、呼吸噪声)→ 按目标 SNR 加噪。
|
||||||
|
随机种子固定,可完整复现。
|
||||||
|
|
||||||
|
<!-- EVAL_TABLE_START -->
|
||||||
|
曲库 **43 首**,每首 3 条查询,共 **129 条/难度**,随机种子 `20260908`:
|
||||||
|
|
||||||
|
| 难度 | Top-1 | Top-3 | Top-5 | Top-10 | MRR | 粗召回率 | 延迟 p50 | 延迟 p95 |
|
||||||
|
|---|---:|---:|---:|---:|---:|---:|---:|---:|
|
||||||
|
| 简单 | **89.9%** | 95.3% | 96.1% | 96.9% | 0.928 | 100.0% | 93 ms | 137 ms |
|
||||||
|
| 中等 | **76.0%** | 86.0% | 88.4% | 93.0% | 0.814 | 99.2% | 75 ms | 112 ms |
|
||||||
|
| 困难 | **62.0%** | 70.5% | 74.4% | 82.2% | 0.676 | 96.9% | 80 ms | 117 ms |
|
||||||
|
|
||||||
|
失败分析显示:31 个 Top-1 失误里有 **30 个答案仍在粗候选集内**——瓶颈在精排
|
||||||
|
而非召回;音符提取的音高误差中位数仅 0.08–0.10 半音,主要损失来自音符数偏少。
|
||||||
|
|
||||||
|
噪声鲁棒性:开启预处理后,Top-1 在 22 → 5 dB 信噪比区间稳定在 70–73%;
|
||||||
|
关闭预处理则 7.5 dB 时跌到 15.1%、5 dB 时 5.8%。完整数据见
|
||||||
|
[`docs/评测报告.md`](docs/评测报告.md)。
|
||||||
|
<!-- EVAL_TABLE_END -->
|
||||||
|
|
||||||
|
大规模基准(合成曲库,测扩展性):
|
||||||
|
|
||||||
|
| 曲库规模 | n-gram 数 | 候选召回率 | Top-1 | Top-5 | MRR | 平均候选数 | 延迟 p50 | 延迟 p95 | 索引构建 |
|
||||||
|
|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
|
||||||
|
| 300 | 11136 | 98.3% | 90.0% | 96.7% | 0.926 | 121 | 256 ms | 418 ms | 133 ms |
|
||||||
|
| 600 | 16451 | 95.0% | 80.0% | 86.7% | 0.835 | 166 | 324 ms | 486 ms | 189 ms |
|
||||||
|
| 1000 | 21918 | 90.0% | 80.0% | 88.3% | 0.836 | 220 | 433 ms | 673 ms | 322 ms |
|
||||||
|
|
||||||
|
曲库扩大 3.3 倍,延迟只增长约 1.7 倍——两级检索的扩展性来自粗召回把精排规模
|
||||||
|
限制在百量级,而不是随曲库线性增长。
|
||||||
|
|
||||||
|
**诚实性说明**:合成查询 + 合成曲库会让数字偏乐观。因此:
|
||||||
|
|
||||||
|
- 曲库中 27 首是**真实 MIDI**(权威真值),16 首是内置曲谱;
|
||||||
|
- 大规模基准用的是合成曲库与同源合成查询,其准确率只作**相对参考**,
|
||||||
|
真正有说服力的是召回率与延迟的**扩展趋势**;
|
||||||
|
- 参数调优采用坐标下降,**在留出种子上验证**——我们明确观察到调优在留出集上
|
||||||
|
收益不稳定,因此只采纳了跨种子一致有效的改动,未采纳过拟合的极端取值。
|
||||||
|
|
||||||
|
噪声鲁棒性曲线见 `docs/评测报告.md`(由 `python cli.py noise` 生成)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
qbh/ 核心库(音频、音高、切分、表示、索引、DTW、检索、评测、基准)
|
||||||
|
app/ FastAPI 后端 + 前端单页应用
|
||||||
|
desktop/ Tkinter 桌面客户端
|
||||||
|
scripts/ 评测、噪声实验、参数调优脚本
|
||||||
|
tests/ pytest 测试套件(105 个用例)
|
||||||
|
data/ 曲库(midi/)、示范音频(audio/)、SQLite(qbh.db)、报告
|
||||||
|
docs/ 设计文档、评测报告、界面说明
|
||||||
|
```
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv\Scripts\python.exe -m pytest tests -q # 105 passed
|
||||||
|
```
|
||||||
|
|
||||||
|
覆盖:音频编解码与预处理、YIN 精度与静音判定、音符切分与重复音融合、
|
||||||
|
旋律表示的不变性、MIDI 读写回环、倒排索引的移调不变性、DTW 与朴素实现一致性、
|
||||||
|
端到端检索、SQLite CRUD / 账号 / 历史、评测指标、以及全部 HTTP 接口。
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| GET | `/api/status` | 曲库与引擎状态 |
|
||||||
|
| GET | `/api/songs` | 曲库列表 |
|
||||||
|
| GET | `/api/songs/{id}` | 单曲详情(含旋律特征) |
|
||||||
|
| GET | `/api/songs/{id}/audio` | 示范音频(WAV) |
|
||||||
|
| POST | `/api/search` | 上传/录音检索(multipart 或 base64 JSON) |
|
||||||
|
| POST | `/api/demo` | 随机生成合成哼唱并检索 |
|
||||||
|
| GET | `/api/query/{qid}/audio` | 重放某条示范查询 |
|
||||||
|
| POST | `/api/library/import` | 导入 MIDI / 音频 |
|
||||||
|
| DELETE | `/api/library/{id}` | 删除曲目 |
|
||||||
|
| POST | `/api/library/rebuild` | 重建曲库与索引 |
|
||||||
|
| POST | `/api/auth/register\|login\|logout` | 账号 |
|
||||||
|
| GET | `/api/history` | 检索历史 |
|
||||||
|
| POST | `/api/eval/run` | 运行评测 |
|
||||||
|
| GET | `/api/eval/latest` | 最近一次评测报告 |
|
||||||
|
|
||||||
|
## 已知限制
|
||||||
|
|
||||||
|
- **曲库规模**:默认 43 首。更大曲库下粗召回率会下降(1000 首时约 90%),
|
||||||
|
可考虑提高候选数或引入更细的码本。
|
||||||
|
- **单声部假设**:从 MIDI 抽取旋律时用「重叠保留高音」的单声部化启发式,
|
||||||
|
对复调作品会丢失内声部。
|
||||||
|
- **音域**:YIN 配置为 70–1000 Hz,超出该范围的哼唱(如极低音或哨音)会失效。
|
||||||
|
- **噪声**:SNR 低于约 10 dB 时准确率明显下滑(见噪声实验曲线);预处理能缓解,
|
||||||
|
但无法完全抵消。
|
||||||
|
- **参数调优**:在留出种子上收益不稳定,说明当前搜索空间里存在过拟合;
|
||||||
|
更稳健的做法是扩大评测集后再调。
|
||||||
|
|
||||||
|
## 与既有实现的关系
|
||||||
|
|
||||||
|
本仓库在算法上融合并验证了多条已被证明有效的思路:两级检索(倒排索引 + DTW)、
|
||||||
|
重复音对称融合、开放起止的子序列 DTW、自由带代价、移调粗到细搜索。
|
||||||
|
与常见的「自证式评测」不同,本项目把**真实 MIDI 曲库**作为主基准,并显式标注了
|
||||||
|
合成数据的乐观偏差。
|
||||||
+523
@@ -0,0 +1,523 @@
|
|||||||
|
"""FastAPI 后端:把 qbh 检索引擎暴露为 REST 接口,并托管前端单页应用。
|
||||||
|
|
||||||
|
接口一览
|
||||||
|
--------
|
||||||
|
``GET /api/status`` 曲库与引擎状态
|
||||||
|
``GET /api/songs`` 曲库列表
|
||||||
|
``GET /api/songs/{id}`` 单曲详情(含旋律特征)
|
||||||
|
``GET /api/songs/{id}/audio`` 示范音频(WAV)
|
||||||
|
``POST /api/search`` 上传/录音检索(multipart 或 base64 JSON)
|
||||||
|
``POST /api/demo`` 随机生成一条合成哼唱查询并检索
|
||||||
|
``GET /api/query/{qid}/audio`` 重放某条示范查询的音频
|
||||||
|
``POST /api/library/import`` 导入 MIDI 文件
|
||||||
|
``DELETE /api/library/{id}`` 删除曲目
|
||||||
|
``POST /api/library/rebuild`` 重建曲库与索引
|
||||||
|
``POST /api/auth/register|login|logout`` 账号
|
||||||
|
``GET /api/auth/me`` 当前用户
|
||||||
|
``GET /api/history`` 检索历史
|
||||||
|
``POST /api/eval/run`` 跑一次评测
|
||||||
|
``GET /api/eval/latest`` 最近一次评测报告
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from dataclasses import asdict
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from fastapi import Cookie, FastAPI, File, HTTPException, Request, Response, UploadFile
|
||||||
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response as RawResponse
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from qbh.audio import encode_wav_bytes, read_audio
|
||||||
|
from qbh.config import DEFAULT, Config
|
||||||
|
from qbh.evaluate import evaluate, make_query_specs, perturb_melody, synth_query_audio
|
||||||
|
from qbh.library import Library
|
||||||
|
from qbh.melody import Melody
|
||||||
|
from qbh.search import SearchEngine
|
||||||
|
from qbh.store import Store
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
STATIC_DIR = Path(__file__).resolve().parent / "static"
|
||||||
|
DATA_DIR = ROOT / "data"
|
||||||
|
# 允许用环境变量覆盖,便于测试隔离(QBH_DB / QBH_MIDI_DIR / QBH_SKIP_AUDIO)
|
||||||
|
DB_PATH = Path(os.environ.get("QBH_DB", str(DATA_DIR / "qbh.db")))
|
||||||
|
MIDI_DIR = Path(os.environ.get("QBH_MIDI_DIR", str(DATA_DIR / "midi")))
|
||||||
|
AUDIO_DIR = Path(os.environ.get("QBH_AUDIO_DIR", str(DATA_DIR / "audio")))
|
||||||
|
SKIP_AUDIO = os.environ.get("QBH_SKIP_AUDIO", "") not in ("", "0", "false")
|
||||||
|
# 报告与数据库放在同一目录,测试用 QBH_DB 指向临时目录时不会污染正式报告
|
||||||
|
REPORT_DIR = DB_PATH.parent
|
||||||
|
EVAL_PATH = REPORT_DIR / "eval_report.json"
|
||||||
|
NOISE_PATH = REPORT_DIR / "noise_report.json"
|
||||||
|
|
||||||
|
SESSION_COOKIE = "qbh_session"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 全局状态
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
class AppState:
|
||||||
|
"""进程级单例:曲库、检索引擎、会话表。"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.store = Store(DB_PATH)
|
||||||
|
self.library = Library(
|
||||||
|
self.store, DEFAULT, midi_dir=MIDI_DIR, audio_dir=AUDIO_DIR
|
||||||
|
)
|
||||||
|
if self.library.count() == 0:
|
||||||
|
self.library.build(render_audio=not SKIP_AUDIO)
|
||||||
|
self.engine = SearchEngine(self.library, DEFAULT)
|
||||||
|
self.sessions: dict[str, int] = {}
|
||||||
|
self.demo_cache: dict[str, dict[str, Any]] = {}
|
||||||
|
self.lock = threading.RLock()
|
||||||
|
self.eval_lock = threading.Lock()
|
||||||
|
|
||||||
|
def rebuild(self) -> int:
|
||||||
|
with self.lock:
|
||||||
|
n = self.engine.rebuild_index()
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
state = AppState()
|
||||||
|
|
||||||
|
app = FastAPI(title="基于旋律的音乐哼唱检索系统", version="1.0.0")
|
||||||
|
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 鉴权辅助
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def current_user(session: str | None = Cookie(default=None, alias=SESSION_COOKIE)) -> int | None:
|
||||||
|
if not session:
|
||||||
|
return None
|
||||||
|
return state.sessions.get(session)
|
||||||
|
|
||||||
|
|
||||||
|
def require_user(session: str | None = Cookie(default=None, alias=SESSION_COOKIE)) -> int:
|
||||||
|
user_id = current_user(session)
|
||||||
|
if user_id is None:
|
||||||
|
raise HTTPException(status_code=401, detail="请先登录")
|
||||||
|
return user_id
|
||||||
|
|
||||||
|
|
||||||
|
def _set_session(response: Response, user_id: int) -> str:
|
||||||
|
token = secrets.token_urlsafe(24)
|
||||||
|
state.sessions[token] = user_id
|
||||||
|
response.set_cookie(
|
||||||
|
SESSION_COOKIE, token, httponly=True, samesite="lax", max_age=7 * 24 * 3600
|
||||||
|
)
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 序列化
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def _hit_payload(hit, *, with_target: bool = True) -> dict[str, Any]:
|
||||||
|
payload = hit.to_dict(include_path=True)
|
||||||
|
if with_target:
|
||||||
|
target = state.library.get_melody(hit.song_id)
|
||||||
|
if target is not None:
|
||||||
|
payload["target_midis"] = [round(float(v), 2) for v in target.midis]
|
||||||
|
payload["target_starts"] = [round(float(v), 3) for v in target.starts]
|
||||||
|
payload["target_durs"] = [round(float(v), 3) for v in target.durs]
|
||||||
|
payload["target_contour"] = target.contour()
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _result_payload(result) -> dict[str, Any]:
|
||||||
|
data = result.to_dict(include_path=False, include_query=True)
|
||||||
|
data["hits"] = [_hit_payload(h) for h in result.hits]
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _record_history(result, source: str, user_id: int | None) -> None:
|
||||||
|
top = result.top()
|
||||||
|
try:
|
||||||
|
state.store.add_history(
|
||||||
|
user_id=user_id,
|
||||||
|
source=source,
|
||||||
|
query_notes=result.query.n_notes,
|
||||||
|
query_melody=result.query.to_json(),
|
||||||
|
top_song=top.song_id if top else "",
|
||||||
|
top_title=top.title if top else "",
|
||||||
|
top_score=top.score if top else 0.0,
|
||||||
|
elapsed_ms=result.elapsed_ms,
|
||||||
|
results=[h.to_dict(include_path=False) for h in result.hits[:5]],
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass # 历史记录失败不应影响检索本身
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 静态页面
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
@app.get("/", response_class=HTMLResponse)
|
||||||
|
def index() -> HTMLResponse:
|
||||||
|
return HTMLResponse((STATIC_DIR / "index.html").read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 状态与曲库
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
@app.get("/api/status")
|
||||||
|
def api_status() -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"n_songs": state.library.count(),
|
||||||
|
"n_grams": state.engine.index.n_grams(),
|
||||||
|
"built_at": state.store.get_meta("library_built_at"),
|
||||||
|
"config": DEFAULT.to_dict(),
|
||||||
|
"has_eval": EVAL_PATH.exists(),
|
||||||
|
"has_noise": NOISE_PATH.exists(),
|
||||||
|
"db_path": str(DB_PATH),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/songs")
|
||||||
|
def api_songs() -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"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,
|
||||||
|
"median_pitch": r.median_pitch,
|
||||||
|
"has_audio": bool(r.audio_file),
|
||||||
|
}
|
||||||
|
for r in state.library.songs()
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/songs/{song_id}")
|
||||||
|
def api_song(song_id: str) -> dict[str, Any]:
|
||||||
|
record = state.library.get_song(song_id)
|
||||||
|
if record is None:
|
||||||
|
raise HTTPException(status_code=404, detail="曲目不存在")
|
||||||
|
melody = state.library.get_melody(song_id)
|
||||||
|
return {
|
||||||
|
"song": {
|
||||||
|
"id": record.id,
|
||||||
|
"title": record.title,
|
||||||
|
"origin": record.origin,
|
||||||
|
"tags": list(record.tags),
|
||||||
|
"source": record.source,
|
||||||
|
"n_notes": record.n_notes,
|
||||||
|
"duration": record.duration,
|
||||||
|
},
|
||||||
|
"melody": melody.to_dict() if melody else None,
|
||||||
|
"contour": melody.contour() if melody else "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/songs/{song_id}/audio")
|
||||||
|
def api_song_audio(song_id: str) -> RawResponse:
|
||||||
|
path = state.library.audio_path(song_id)
|
||||||
|
if path is None or not path.exists():
|
||||||
|
raise HTTPException(status_code=404, detail="示范音频不可用")
|
||||||
|
return RawResponse(content=path.read_bytes(), media_type="audio/wav")
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/library/{song_id}")
|
||||||
|
def api_delete_song(song_id: str) -> dict[str, Any]:
|
||||||
|
if not state.library.delete(song_id):
|
||||||
|
raise HTTPException(status_code=404, detail="曲目不存在")
|
||||||
|
state.rebuild()
|
||||||
|
return {"ok": True, "n_songs": state.library.count()}
|
||||||
|
|
||||||
|
|
||||||
|
class ImportPayload(BaseModel):
|
||||||
|
song_id: str | None = None
|
||||||
|
title: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/library/import")
|
||||||
|
async def api_import(file: UploadFile = File(...), song_id: str | None = None, title: str = "") -> dict[str, Any]:
|
||||||
|
suffix = Path(file.filename or "upload.mid").suffix.lower()
|
||||||
|
blob = await file.read()
|
||||||
|
tmp_dir = DATA_DIR / "uploads"
|
||||||
|
tmp_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
tmp_path = tmp_dir / (file.filename or "upload.mid")
|
||||||
|
tmp_path.write_bytes(blob)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if suffix in (".mid", ".midi"):
|
||||||
|
record = state.library.add_midi_file(tmp_path, song_id=song_id, title=title)
|
||||||
|
else:
|
||||||
|
samples, sr = read_audio(blob)
|
||||||
|
from qbh.notes import segment_notes
|
||||||
|
from qbh.pitch import extract_pitch
|
||||||
|
from qbh.audio import preprocess
|
||||||
|
|
||||||
|
track = extract_pitch(preprocess(samples, sr, DEFAULT), DEFAULT.sample_rate, DEFAULT)
|
||||||
|
melody = segment_notes(track, DEFAULT)
|
||||||
|
if melody.n_notes < 4:
|
||||||
|
raise HTTPException(status_code=400, detail="音频中识别到的音符过少")
|
||||||
|
sid = song_id or f"import_{tmp_path.stem}"
|
||||||
|
record = state.library.add_melody(
|
||||||
|
melody, song_id=sid, title=title or tmp_path.stem, origin="导入音频", source="audio"
|
||||||
|
)
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=f"导入失败:{exc}") from exc
|
||||||
|
|
||||||
|
state.rebuild()
|
||||||
|
return {"ok": True, "song": asdict(record), "n_songs": state.library.count()}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/library/rebuild")
|
||||||
|
def api_rebuild(force: bool = False) -> dict[str, Any]:
|
||||||
|
report = state.library.build(force=force)
|
||||||
|
state.rebuild()
|
||||||
|
return {"ok": True, "report": report.to_dict()}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 检索
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
class SearchJSON(BaseModel):
|
||||||
|
audio_base64: str
|
||||||
|
top_k: int = Field(default=10, ge=1, le=50)
|
||||||
|
source: str = "upload"
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/search")
|
||||||
|
async def api_search(
|
||||||
|
request: Request,
|
||||||
|
session: str | None = Cookie(default=None, alias=SESSION_COOKIE),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
content_type = request.headers.get("content-type", "")
|
||||||
|
source = "upload"
|
||||||
|
top_k = DEFAULT.top_k
|
||||||
|
|
||||||
|
if content_type.startswith("application/json"):
|
||||||
|
payload = SearchJSON(**await request.json())
|
||||||
|
try:
|
||||||
|
blob = base64.b64decode(payload.audio_base64)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=400, detail="base64 音频解码失败") from exc
|
||||||
|
top_k = payload.top_k
|
||||||
|
source = payload.source
|
||||||
|
elif content_type.startswith("multipart/form-data"):
|
||||||
|
form = await request.form()
|
||||||
|
upload = form.get("file") or form.get("audio")
|
||||||
|
if upload is None:
|
||||||
|
raise HTTPException(status_code=400, detail="缺少音频文件字段 file")
|
||||||
|
blob = await upload.read() if hasattr(upload, "read") else bytes(upload)
|
||||||
|
if form.get("top_k"):
|
||||||
|
top_k = max(1, min(50, int(form.get("top_k"))))
|
||||||
|
if form.get("source"):
|
||||||
|
source = str(form.get("source"))
|
||||||
|
else:
|
||||||
|
blob = await request.body()
|
||||||
|
if not blob:
|
||||||
|
raise HTTPException(status_code=400, detail="请求体为空")
|
||||||
|
|
||||||
|
started = time.perf_counter()
|
||||||
|
try:
|
||||||
|
samples, sr = read_audio(blob)
|
||||||
|
result, track = state.engine.search_audio(samples, sr, top_k=top_k)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=f"音频解析或识别失败:{exc}") from exc
|
||||||
|
|
||||||
|
payload = _result_payload(result)
|
||||||
|
payload["total_ms"] = round((time.perf_counter() - started) * 1000.0, 2)
|
||||||
|
payload["track"] = {
|
||||||
|
"voiced_ratio": round(track.voiced_ratio(), 3),
|
||||||
|
"duration": round(track.duration, 3),
|
||||||
|
"f0": [round(float(v), 1) for v in track.f0],
|
||||||
|
"times": [round(float(v), 3) for v in track.times],
|
||||||
|
}
|
||||||
|
_record_history(result, source, current_user(session))
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
class DemoPayload(BaseModel):
|
||||||
|
difficulty: str = "normal"
|
||||||
|
seed: int | None = None
|
||||||
|
song_id: str | None = None
|
||||||
|
top_k: int = Field(default=10, ge=1, le=50)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/demo")
|
||||||
|
def api_demo(
|
||||||
|
payload: DemoPayload,
|
||||||
|
session: str | None = Cookie(default=None, alias=SESSION_COOKIE),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
seed = payload.seed if payload.seed is not None else int(time.time() * 1000) % (2**31)
|
||||||
|
melodies = state.library.melodies()
|
||||||
|
if payload.song_id:
|
||||||
|
melodies = [m for m in melodies if m.song_id == payload.song_id]
|
||||||
|
if not melodies:
|
||||||
|
raise HTTPException(status_code=404, detail="曲目不存在")
|
||||||
|
specs = make_query_specs(melodies, n_per_song=1, difficulty=payload.difficulty, seed=seed)
|
||||||
|
if not specs:
|
||||||
|
raise HTTPException(status_code=400, detail="无法生成示范查询")
|
||||||
|
spec = specs[0]
|
||||||
|
source = next(m for m in state.library.melodies() if m.song_id == spec.song_id)
|
||||||
|
truth = perturb_melody(source, spec, DEFAULT)
|
||||||
|
audio = synth_query_audio(truth, spec, DEFAULT)
|
||||||
|
|
||||||
|
result, track = state.engine.search_audio(audio, DEFAULT.sample_rate, top_k=payload.top_k)
|
||||||
|
qid = f"d{seed % 10**8}"
|
||||||
|
state.demo_cache[qid] = {
|
||||||
|
"audio": encode_wav_bytes(audio, DEFAULT.sample_rate),
|
||||||
|
"spec": spec.to_dict(),
|
||||||
|
}
|
||||||
|
if len(state.demo_cache) > 50:
|
||||||
|
state.demo_cache.pop(next(iter(state.demo_cache)))
|
||||||
|
|
||||||
|
out = _result_payload(result)
|
||||||
|
out["demo"] = {
|
||||||
|
"qid": qid,
|
||||||
|
"audio_url": f"/api/query/{qid}/audio",
|
||||||
|
"answer": spec.song_id,
|
||||||
|
"answer_title": spec.title,
|
||||||
|
"difficulty": spec.difficulty,
|
||||||
|
"shift": spec.shift,
|
||||||
|
"tempo": round(spec.tempo, 3),
|
||||||
|
"snr_db": spec.snr_db,
|
||||||
|
"n_notes": spec.n_notes,
|
||||||
|
"rank": next(
|
||||||
|
(i + 1 for i, h in enumerate(result.hits) if h.song_id == spec.song_id), 0
|
||||||
|
),
|
||||||
|
}
|
||||||
|
out["track"] = {
|
||||||
|
"voiced_ratio": round(track.voiced_ratio(), 3),
|
||||||
|
"duration": round(track.duration, 3),
|
||||||
|
"f0": [round(float(v), 1) for v in track.f0],
|
||||||
|
"times": [round(float(v), 3) for v in track.times],
|
||||||
|
}
|
||||||
|
_record_history(result, "demo", current_user(session))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/query/{qid}/audio")
|
||||||
|
def api_query_audio(qid: str) -> RawResponse:
|
||||||
|
entry = state.demo_cache.get(qid)
|
||||||
|
if entry is None:
|
||||||
|
raise HTTPException(status_code=404, detail="示范查询已过期")
|
||||||
|
return RawResponse(content=entry["audio"], media_type="audio/wav")
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 账号
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
class Credentials(BaseModel):
|
||||||
|
username: str
|
||||||
|
password: str
|
||||||
|
email: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/auth/register")
|
||||||
|
def api_register(payload: Credentials, response: Response) -> dict[str, Any]:
|
||||||
|
ok, message = state.store.create_user(payload.username, payload.password, payload.email)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=400, detail=message)
|
||||||
|
user_id = state.store.verify_user(payload.username, payload.password)
|
||||||
|
if user_id is None:
|
||||||
|
raise HTTPException(status_code=400, detail="注册后自动登录失败")
|
||||||
|
_set_session(response, user_id)
|
||||||
|
return {"ok": True, "message": message, "user": state.store.get_user(user_id)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/auth/login")
|
||||||
|
def api_login(payload: Credentials, response: Response) -> dict[str, Any]:
|
||||||
|
user_id = state.store.verify_user(payload.username, payload.password)
|
||||||
|
if user_id is None:
|
||||||
|
raise HTTPException(status_code=401, detail="用户名或密码错误")
|
||||||
|
_set_session(response, user_id)
|
||||||
|
return {"ok": True, "user": state.store.get_user(user_id)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/auth/logout")
|
||||||
|
def api_logout(response: Response, session: str | None = Cookie(default=None, alias=SESSION_COOKIE)) -> dict[str, Any]:
|
||||||
|
if session:
|
||||||
|
state.sessions.pop(session, None)
|
||||||
|
response.delete_cookie(SESSION_COOKIE)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/auth/me")
|
||||||
|
def api_me(session: str | None = Cookie(default=None, alias=SESSION_COOKIE)) -> dict[str, Any]:
|
||||||
|
user_id = current_user(session)
|
||||||
|
if user_id is None:
|
||||||
|
return {"logged_in": False, "user": None}
|
||||||
|
return {"logged_in": True, "user": state.store.get_user(user_id)}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 历史
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
@app.get("/api/history")
|
||||||
|
def api_history(
|
||||||
|
limit: int = 30,
|
||||||
|
session: str | None = Cookie(default=None, alias=SESSION_COOKIE),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
user_id = current_user(session)
|
||||||
|
items = state.store.list_history(user_id=user_id, limit=max(1, min(limit, 200)))
|
||||||
|
for item in items:
|
||||||
|
item.pop("query_melody", None)
|
||||||
|
return {"history": items, "scoped_to_user": user_id is not None}
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/history")
|
||||||
|
def api_clear_history(session: str | None = Cookie(default=None, alias=SESSION_COOKIE)) -> dict[str, Any]:
|
||||||
|
removed = state.store.clear_history(current_user(session))
|
||||||
|
return {"ok": True, "removed": removed}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 评测
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
class EvalPayload(BaseModel):
|
||||||
|
difficulty: str = "normal"
|
||||||
|
per_song: int = Field(default=3, ge=1, le=10)
|
||||||
|
seed: int = 20260908
|
||||||
|
top_k: int = Field(default=10, ge=1, le=20)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/eval/run")
|
||||||
|
def api_eval_run(payload: EvalPayload) -> dict[str, Any]:
|
||||||
|
if not state.eval_lock.acquire(blocking=False):
|
||||||
|
raise HTTPException(status_code=429, detail="已有评测在运行中")
|
||||||
|
try:
|
||||||
|
specs = make_query_specs(
|
||||||
|
state.library.melodies(),
|
||||||
|
n_per_song=payload.per_song,
|
||||||
|
difficulty=payload.difficulty,
|
||||||
|
seed=payload.seed,
|
||||||
|
)
|
||||||
|
report = evaluate(
|
||||||
|
state.engine, specs, label=payload.difficulty, top_k=payload.top_k, cfg=DEFAULT
|
||||||
|
)
|
||||||
|
report.save(EVAL_PATH)
|
||||||
|
return {"ok": True, "report": report.to_dict(include_details=False)}
|
||||||
|
finally:
|
||||||
|
state.eval_lock.release()
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/eval/latest")
|
||||||
|
def api_eval_latest() -> dict[str, Any]:
|
||||||
|
if not EVAL_PATH.exists():
|
||||||
|
return {"available": False}
|
||||||
|
return {"available": True, "report": json.loads(EVAL_PATH.read_text(encoding="utf-8"))}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/noise/latest")
|
||||||
|
def api_noise_latest() -> dict[str, Any]:
|
||||||
|
if not NOISE_PATH.exists():
|
||||||
|
return {"available": False}
|
||||||
|
return {"available": True, "report": json.loads(NOISE_PATH.read_text(encoding="utf-8"))}
|
||||||
@@ -0,0 +1,728 @@
|
|||||||
|
/* 基于旋律的音乐哼唱检索系统 —— 前端逻辑(原生 JS,无构建步骤) */
|
||||||
|
|
||||||
|
const $ = (sel) => document.querySelector(sel);
|
||||||
|
const $$ = (sel) => Array.from(document.querySelectorAll(sel));
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
recording: false,
|
||||||
|
mediaRecorder: null,
|
||||||
|
chunks: [],
|
||||||
|
stream: null,
|
||||||
|
lastResult: null,
|
||||||
|
user: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 通用工具 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
async function api(path, options = {}) {
|
||||||
|
const res = await fetch(path, options);
|
||||||
|
const text = await res.text();
|
||||||
|
let data = null;
|
||||||
|
try { data = text ? JSON.parse(text) : null; } catch { data = { detail: text }; }
|
||||||
|
if (!res.ok) {
|
||||||
|
const message = (data && (data.detail || data.message)) || `HTTP ${res.status}`;
|
||||||
|
throw new Error(typeof message === 'string' ? message : JSON.stringify(message));
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function el(tag, cls, text) {
|
||||||
|
const node = document.createElement(tag);
|
||||||
|
if (cls) node.className = cls;
|
||||||
|
if (text !== undefined) node.textContent = text;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* WAV 编码 / 重采样(浏览器端,把录音转成后端可读的 16k 单声道 WAV) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
function encodeWav(samples, sampleRate) {
|
||||||
|
const buffer = new ArrayBuffer(44 + samples.length * 2);
|
||||||
|
const view = new DataView(buffer);
|
||||||
|
const writeStr = (off, s) => {
|
||||||
|
for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i));
|
||||||
|
};
|
||||||
|
writeStr(0, 'RIFF');
|
||||||
|
view.setUint32(4, 36 + samples.length * 2, true);
|
||||||
|
writeStr(8, 'WAVE');
|
||||||
|
writeStr(12, 'fmt ');
|
||||||
|
view.setUint32(16, 16, true);
|
||||||
|
view.setUint16(20, 1, true); // PCM
|
||||||
|
view.setUint16(22, 1, true); // mono
|
||||||
|
view.setUint32(24, sampleRate, true);
|
||||||
|
view.setUint32(28, sampleRate * 2, true);
|
||||||
|
view.setUint16(32, 2, true);
|
||||||
|
view.setUint16(34, 16, true);
|
||||||
|
writeStr(36, 'data');
|
||||||
|
view.setUint32(40, samples.length * 2, true);
|
||||||
|
let off = 44;
|
||||||
|
for (let i = 0; i < samples.length; i++, off += 2) {
|
||||||
|
const s = Math.max(-1, Math.min(1, samples[i]));
|
||||||
|
view.setInt16(off, s < 0 ? s * 0x8000 : s * 0x7fff, true);
|
||||||
|
}
|
||||||
|
return new Blob([view], { type: 'audio/wav' });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toWav16k(blob) {
|
||||||
|
const arrayBuffer = await blob.arrayBuffer();
|
||||||
|
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||||
|
const decoded = await ctx.decodeAudioData(arrayBuffer);
|
||||||
|
const targetRate = 16000;
|
||||||
|
const frames = Math.max(1, Math.ceil(decoded.duration * targetRate));
|
||||||
|
const off = new OfflineAudioContext(1, frames, targetRate);
|
||||||
|
const src = off.createBufferSource();
|
||||||
|
src.buffer = decoded;
|
||||||
|
src.connect(off.destination);
|
||||||
|
src.start();
|
||||||
|
const rendered = await off.startRendering();
|
||||||
|
await ctx.close();
|
||||||
|
return encodeWav(rendered.getChannelData(0), targetRate);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 图表:音高阶梯图 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
function drawContour(canvas, midis, starts, durs, options = {}) {
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
const W = canvas.clientWidth || 420;
|
||||||
|
const H = options.height || 140;
|
||||||
|
canvas.width = W * dpr;
|
||||||
|
canvas.height = H * dpr;
|
||||||
|
canvas.style.height = H + 'px';
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
ctx.clearRect(0, 0, W, H);
|
||||||
|
|
||||||
|
if (!midis || midis.length === 0) {
|
||||||
|
ctx.fillStyle = '#5b6b88';
|
||||||
|
ctx.font = '12px sans-serif';
|
||||||
|
ctx.fillText('未识别到音符', 12, H / 2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const padL = 34, padR = 10, padT = 12, padB = 18;
|
||||||
|
const lo = Math.min(...midis) - 1;
|
||||||
|
const hi = Math.max(...midis) + 1;
|
||||||
|
const span = Math.max(hi - lo, 1);
|
||||||
|
const y = (v) => H - padB - ((v - lo) / span) * (H - padT - padB);
|
||||||
|
const total = Math.max(starts[starts.length - 1] + durs[durs.length - 1], 0.001);
|
||||||
|
const x = (t) => padL + (t / total) * (W - padL - padR);
|
||||||
|
|
||||||
|
// 网格
|
||||||
|
ctx.strokeStyle = '#1d283c';
|
||||||
|
ctx.lineWidth = 1;
|
||||||
|
for (let v = Math.ceil(lo); v <= hi; v += 2) {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(padL, y(v));
|
||||||
|
ctx.lineTo(W - padR, y(v));
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 音符条
|
||||||
|
for (let i = 0; i < midis.length; i++) {
|
||||||
|
const x0 = x(starts[i]);
|
||||||
|
const x1 = x(starts[i] + durs[i]);
|
||||||
|
const yy = y(midis[i]);
|
||||||
|
ctx.fillStyle = options.color || '#4f8cff';
|
||||||
|
ctx.fillRect(x0, yy - 3, Math.max(x1 - x0 - 1.5, 2), 6);
|
||||||
|
if (i > 0) {
|
||||||
|
ctx.strokeStyle = 'rgba(79,140,255,.45)';
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(x(x(starts[i - 1] + durs[i - 1]) ? starts[i - 1] + durs[i - 1] : 0), y(midis[i - 1]));
|
||||||
|
ctx.lineTo(x0, yy);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 纵轴刻度
|
||||||
|
ctx.fillStyle = '#5b6b88';
|
||||||
|
ctx.font = '10px monospace';
|
||||||
|
for (let v = Math.ceil(lo); v <= hi; v += 2) {
|
||||||
|
ctx.fillText(String(v), 4, y(v) + 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 图表:DTW 对齐(左列查询 / 右列目标 / 中间连线) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
function drawAlignment(canvas, payload) {
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
const W = canvas.clientWidth || 880;
|
||||||
|
const H = 300;
|
||||||
|
canvas.width = W * dpr;
|
||||||
|
canvas.height = H * dpr;
|
||||||
|
canvas.style.height = H + 'px';
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
ctx.clearRect(0, 0, W, H);
|
||||||
|
|
||||||
|
const q = (payload.query && payload.query.midis) || [];
|
||||||
|
const t = payload.target_midis || [];
|
||||||
|
const path = payload.path || [];
|
||||||
|
const shift = payload.shift || 0;
|
||||||
|
if (q.length === 0 || t.length === 0) {
|
||||||
|
ctx.fillStyle = '#5b6b88';
|
||||||
|
ctx.font = '12px sans-serif';
|
||||||
|
ctx.fillText('没有可用的对齐数据', 12, H / 2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const qAligned = q.map((v) => v + shift);
|
||||||
|
const all = qAligned.concat(t);
|
||||||
|
const lo = Math.min(...all) - 1;
|
||||||
|
const hi = Math.max(...all) + 1;
|
||||||
|
const span = Math.max(hi - lo, 1);
|
||||||
|
const padT = 24, padB = 30;
|
||||||
|
const y = (v) => H - padB - ((v - lo) / span) * (H - padT - padB);
|
||||||
|
|
||||||
|
const leftX = 30, leftW = W * 0.36;
|
||||||
|
const rightX = W * 0.60, rightW = W * 0.36;
|
||||||
|
const xq = (i) => leftX + (q.length > 1 ? (i / (q.length - 1)) * leftW : 0);
|
||||||
|
const xt = (j) => rightX + (t.length > 1 ? (j / (t.length - 1)) * rightW : 0);
|
||||||
|
|
||||||
|
// 对齐路径连线(抽样,避免过密)
|
||||||
|
const step = Math.max(1, Math.floor(path.length / 220));
|
||||||
|
ctx.lineWidth = 1;
|
||||||
|
for (let k = 0; k < path.length; k += step) {
|
||||||
|
const [i, j] = path[k];
|
||||||
|
if (i >= q.length || j >= t.length) continue;
|
||||||
|
const err = Math.abs(qAligned[i] - t[j]);
|
||||||
|
const alpha = Math.max(0.06, 0.55 - err * 0.08);
|
||||||
|
ctx.strokeStyle = err < 0.6
|
||||||
|
? `rgba(53,208,165,${alpha})`
|
||||||
|
: `rgba(255,${Math.max(90, 180 - err * 12)},90,${alpha})`;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(xq(i), y(qAligned[i]));
|
||||||
|
ctx.lineTo(xt(j), y(t[j]));
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 左列:查询
|
||||||
|
ctx.fillStyle = '#4f8cff';
|
||||||
|
qAligned.forEach((v, i) => {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(xq(i), y(v), 3.2, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
});
|
||||||
|
// 右列:目标片段
|
||||||
|
ctx.fillStyle = '#35d0a5';
|
||||||
|
t.forEach((v, j) => {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(xt(j), y(v), 3.2, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 高亮命中的目标片段区间
|
||||||
|
const s = payload.target_note_start ?? 0;
|
||||||
|
const e = payload.target_note_end ?? t.length - 1;
|
||||||
|
ctx.strokeStyle = 'rgba(53,208,165,.85)';
|
||||||
|
ctx.lineWidth = 2;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(xt(s), H - padB + 8);
|
||||||
|
ctx.lineTo(xt(e), H - padB + 8);
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
ctx.fillStyle = '#93a1bb';
|
||||||
|
ctx.font = '11px sans-serif';
|
||||||
|
ctx.fillText(`哼唱查询(${q.length} 音)`, leftX, 14);
|
||||||
|
ctx.fillText(`曲库片段(第 ${s + 1}–${e + 1} 音)`, rightX, 14);
|
||||||
|
ctx.fillStyle = '#5b6b88';
|
||||||
|
ctx.font = '10px monospace';
|
||||||
|
for (let v = Math.ceil(lo); v <= hi; v += 2) ctx.fillText(String(v), 2, y(v) + 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 结果渲染 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
function renderResults(data) {
|
||||||
|
const container = $('#results');
|
||||||
|
container.innerHTML = '';
|
||||||
|
const hits = data.hits || [];
|
||||||
|
const meta = $('#results-meta');
|
||||||
|
meta.textContent = hits.length
|
||||||
|
? `候选 ${data.n_candidates}/${data.n_songs} 首 · 检索 ${data.elapsed_ms} ms` +
|
||||||
|
(data.total_ms ? ` · 端到端 ${data.total_ms} ms` : '')
|
||||||
|
: '';
|
||||||
|
|
||||||
|
if (!hits.length) {
|
||||||
|
container.appendChild(el('p', 'placeholder', '没有找到匹配的旋律。'));
|
||||||
|
$('#alignment-wrap').classList.add('hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const demo = data.demo || null;
|
||||||
|
if (demo) {
|
||||||
|
const banner = $('#demo-banner');
|
||||||
|
banner.classList.remove('hidden', 'ok', 'bad');
|
||||||
|
const hit = demo.rank === 1;
|
||||||
|
banner.classList.add(hit ? 'ok' : 'bad');
|
||||||
|
banner.innerHTML =
|
||||||
|
`示范查询:<b>${demo.answer_title}</b> · 移调 ${demo.shift > 0 ? '+' : ''}${demo.shift} 半音 · ` +
|
||||||
|
`速度 ${demo.tempo}× · 信噪比 ${demo.snr_db} dB · 片段 ${demo.n_notes} 音<br>` +
|
||||||
|
(hit ? '✅ 第 1 名命中' : (demo.rank ? `⚠️ 命中排在第 ${demo.rank} 名` : '❌ 未进入 Top-K')) +
|
||||||
|
(demo.audio_url ? ` · <a href="${demo.audio_url}" target="_blank">播放查询音频</a>` : '');
|
||||||
|
} else {
|
||||||
|
$('#demo-banner').classList.add('hidden');
|
||||||
|
}
|
||||||
|
|
||||||
|
hits.forEach((hit, idx) => {
|
||||||
|
const item = el('div', 'result-item' + (idx === 0 ? ' top' : '') + (demo && hit.song_id === demo.answer ? ' correct' : ''));
|
||||||
|
item.appendChild(el('div', 'rank', String(idx + 1)));
|
||||||
|
|
||||||
|
const main = el('div', 'result-main');
|
||||||
|
main.appendChild(el('div', 'result-title', hit.title || hit.song_id));
|
||||||
|
const bits = [];
|
||||||
|
if (hit.origin) bits.push(hit.origin);
|
||||||
|
bits.push(`DTW ${hit.dtw_sim.toFixed(3)}`);
|
||||||
|
bits.push(`索引 ${hit.index_sim.toFixed(3)}`);
|
||||||
|
bits.push(`移调 ${hit.shift > 0 ? '+' : ''}${hit.shift}`);
|
||||||
|
if (hit.target_end_s > hit.target_start_s) {
|
||||||
|
bits.push(`片段 ${hit.target_start_s.toFixed(1)}–${hit.target_end_s.toFixed(1)}s`);
|
||||||
|
}
|
||||||
|
main.appendChild(el('div', 'result-sub', bits.join(' · ')));
|
||||||
|
item.appendChild(main);
|
||||||
|
|
||||||
|
const right = el('div', 'score-wrap');
|
||||||
|
const bar = el('div', 'score-bar');
|
||||||
|
const fill = el('i');
|
||||||
|
fill.style.width = `${Math.max(2, Math.min(100, hit.score * 100))}%`;
|
||||||
|
bar.appendChild(fill);
|
||||||
|
right.appendChild(bar);
|
||||||
|
right.appendChild(el('span', 'score-num', hit.score.toFixed(3)));
|
||||||
|
|
||||||
|
if (hit.has_audio) {
|
||||||
|
const btn = el('button', 'play-btn', '▶');
|
||||||
|
btn.title = '播放命中片段';
|
||||||
|
btn.addEventListener('click', () => playSegment(hit));
|
||||||
|
right.appendChild(btn);
|
||||||
|
}
|
||||||
|
item.appendChild(right);
|
||||||
|
container.appendChild(item);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 对齐图用第一条结果
|
||||||
|
const top = hits[0];
|
||||||
|
if (top && data.query) {
|
||||||
|
$('#alignment-wrap').classList.remove('hidden');
|
||||||
|
drawAlignment($('#alignment'), {
|
||||||
|
query: data.query,
|
||||||
|
target_midis: top.target_midis,
|
||||||
|
path: top.path,
|
||||||
|
shift: top.shift,
|
||||||
|
target_note_start: top.target_note_start,
|
||||||
|
target_note_end: top.target_note_end,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
$('#alignment-wrap').classList.add('hidden');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询侧信息
|
||||||
|
if (data.query) {
|
||||||
|
$('#query-info').classList.remove('hidden');
|
||||||
|
const chips = $('#query-chips');
|
||||||
|
chips.innerHTML = '';
|
||||||
|
(data.query.midis || []).forEach((v, i) => {
|
||||||
|
const dur = data.query.durs[i];
|
||||||
|
chips.appendChild(el('span', 'chip', `${v.toFixed(0)}·${dur.toFixed(2)}s`));
|
||||||
|
});
|
||||||
|
drawContour($('#query-contour'), data.query.midis, data.query.starts, data.query.durs);
|
||||||
|
$('#query-meta').textContent =
|
||||||
|
`识别到 ${data.query.n_notes} 个音符,总时长 ${data.query.duration.toFixed(2)} 秒` +
|
||||||
|
(data.track ? ` · 有声帧占比 ${(data.track.voiced_ratio * 100).toFixed(0)}%` : '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let audioPlayer = null;
|
||||||
|
function playSegment(hit) {
|
||||||
|
const url = `/api/songs/${encodeURIComponent(hit.song_id)}/audio`;
|
||||||
|
if (!audioPlayer) {
|
||||||
|
audioPlayer = new Audio();
|
||||||
|
audioPlayer.addEventListener('timeupdate', () => {
|
||||||
|
if (audioPlayer.dataset.stop && audioPlayer.currentTime >= Number(audioPlayer.dataset.stop)) {
|
||||||
|
audioPlayer.pause();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
audioPlayer.src = url;
|
||||||
|
audioPlayer.dataset.stop = String(hit.target_end_s || 0);
|
||||||
|
audioPlayer.currentTime = Math.max(0, hit.target_start_s || 0);
|
||||||
|
audioPlayer.play().catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 查询动作 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
async function searchBlob(blob, source) {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('file', blob, 'query.wav');
|
||||||
|
form.append('top_k', $('#top-k').value || '10');
|
||||||
|
form.append('source', source);
|
||||||
|
const results = $('#results');
|
||||||
|
results.innerHTML = '<p class="placeholder">识别与检索中…</p>';
|
||||||
|
try {
|
||||||
|
const data = await api('/api/search', { method: 'POST', body: form });
|
||||||
|
state.lastResult = data;
|
||||||
|
renderResults(data);
|
||||||
|
refreshHistory();
|
||||||
|
} catch (err) {
|
||||||
|
results.innerHTML = '';
|
||||||
|
results.appendChild(el('p', 'placeholder', `检索失败:${err.message}`));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleRecord() {
|
||||||
|
const btn = $('#btn-record');
|
||||||
|
const hint = $('#record-hint');
|
||||||
|
if (!state.recording) {
|
||||||
|
try {
|
||||||
|
state.stream = await navigator.mediaDevices.getUserMedia({
|
||||||
|
audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false },
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
hint.textContent = `无法访问麦克风:${err.message}`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.chunks = [];
|
||||||
|
state.mediaRecorder = new MediaRecorder(state.stream);
|
||||||
|
state.mediaRecorder.ondataavailable = (e) => { if (e.data.size) state.chunks.push(e.data); };
|
||||||
|
state.mediaRecorder.onstop = async () => {
|
||||||
|
state.stream.getTracks().forEach((t) => t.stop());
|
||||||
|
const blob = new Blob(state.chunks, { type: state.mediaRecorder.mimeType });
|
||||||
|
try {
|
||||||
|
const wav = await toWav16k(blob);
|
||||||
|
await searchBlob(wav, 'mic');
|
||||||
|
} catch (err) {
|
||||||
|
$('#results').innerHTML = '';
|
||||||
|
$('#results').appendChild(el('p', 'placeholder', `录音处理失败:${err.message}`));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
state.mediaRecorder.start();
|
||||||
|
state.recording = true;
|
||||||
|
btn.textContent = '⏹ 停止录音并检索';
|
||||||
|
btn.classList.add('recording');
|
||||||
|
hint.textContent = '正在录音…哼唱一段旋律后点击停止';
|
||||||
|
} else {
|
||||||
|
state.mediaRecorder.stop();
|
||||||
|
state.recording = false;
|
||||||
|
btn.textContent = '🎤 开始录音';
|
||||||
|
btn.classList.remove('recording');
|
||||||
|
hint.textContent = '点击后对着麦克风哼唱 5–15 秒旋律片段';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runDemo() {
|
||||||
|
const btn = $('#btn-demo');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = '生成中…';
|
||||||
|
$('#results').innerHTML = '<p class="placeholder">生成机器哼唱并检索中…</p>';
|
||||||
|
try {
|
||||||
|
const data = await api('/api/demo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
difficulty: $('#demo-difficulty').value,
|
||||||
|
top_k: Number($('#top-k').value) || 10,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
state.lastResult = data;
|
||||||
|
renderResults(data);
|
||||||
|
refreshHistory();
|
||||||
|
} catch (err) {
|
||||||
|
$('#results').innerHTML = '';
|
||||||
|
$('#results').appendChild(el('p', 'placeholder', `示范查询失败:${err.message}`));
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = '🎲 生成机器哼唱并检索';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 曲库 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
async function refreshLibrary() {
|
||||||
|
const data = await api('/api/songs');
|
||||||
|
$('#lib-count').textContent = data.songs.length;
|
||||||
|
const tbody = $('#song-table tbody');
|
||||||
|
tbody.innerHTML = '';
|
||||||
|
data.songs.forEach((song) => {
|
||||||
|
const tr = document.createElement('tr');
|
||||||
|
tr.appendChild(el('td', null, song.title));
|
||||||
|
tr.appendChild(el('td', null, song.origin || '—'));
|
||||||
|
|
||||||
|
const tagCell = document.createElement('td');
|
||||||
|
(song.tags || []).forEach((t) => tagCell.appendChild(el('span', 'tag', t)));
|
||||||
|
tr.appendChild(tagCell);
|
||||||
|
|
||||||
|
tr.appendChild(el('td', null, String(song.n_notes)));
|
||||||
|
tr.appendChild(el('td', null, `${song.duration.toFixed(1)}s`));
|
||||||
|
|
||||||
|
const actionCell = document.createElement('td');
|
||||||
|
const play = el('button', 'play-btn', '▶');
|
||||||
|
play.addEventListener('click', () => {
|
||||||
|
const audio = new Audio(`/api/songs/${encodeURIComponent(song.id)}/audio`);
|
||||||
|
audio.play().catch(() => {});
|
||||||
|
});
|
||||||
|
actionCell.appendChild(play);
|
||||||
|
const del = el('button', 'play-btn', '删除');
|
||||||
|
del.style.marginLeft = '6px';
|
||||||
|
del.addEventListener('click', async () => {
|
||||||
|
if (!confirm(`确认从曲库删除「${song.title}」?`)) return;
|
||||||
|
await api(`/api/library/${encodeURIComponent(song.id)}`, { method: 'DELETE' });
|
||||||
|
refreshLibrary();
|
||||||
|
refreshStatus();
|
||||||
|
});
|
||||||
|
actionCell.appendChild(del);
|
||||||
|
tr.appendChild(actionCell);
|
||||||
|
tbody.appendChild(tr);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 历史 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
async function refreshHistory() {
|
||||||
|
const data = await api('/api/history?limit=40');
|
||||||
|
$('#history-scope').textContent = data.scoped_to_user
|
||||||
|
? '已登录:只显示你自己的检索记录。'
|
||||||
|
: '未登录:显示全部检索记录。登录后只会看到自己的记录。';
|
||||||
|
const tbody = $('#history-table tbody');
|
||||||
|
tbody.innerHTML = '';
|
||||||
|
data.history.forEach((row) => {
|
||||||
|
const tr = document.createElement('tr');
|
||||||
|
tr.appendChild(el('td', null, row.created_at));
|
||||||
|
tr.appendChild(el('td', null, row.source));
|
||||||
|
tr.appendChild(el('td', null, String(row.query_notes)));
|
||||||
|
tr.appendChild(el('td', null, row.top_title || row.top_song || '—'));
|
||||||
|
tr.appendChild(el('td', null, Number(row.top_score).toFixed(3)));
|
||||||
|
tr.appendChild(el('td', null, `${Number(row.elapsed_ms).toFixed(0)} ms`));
|
||||||
|
tbody.appendChild(tr);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 账号 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
function renderAuth() {
|
||||||
|
const box = $('#auth');
|
||||||
|
box.innerHTML = '';
|
||||||
|
if (state.user) {
|
||||||
|
box.appendChild(el('span', 'hint', `👤 ${state.user.username}`));
|
||||||
|
const out = el('button', 'secondary', '退出');
|
||||||
|
out.addEventListener('click', async () => {
|
||||||
|
await api('/api/auth/logout', { method: 'POST' });
|
||||||
|
state.user = null;
|
||||||
|
renderAuth();
|
||||||
|
refreshHistory();
|
||||||
|
});
|
||||||
|
box.appendChild(out);
|
||||||
|
} else {
|
||||||
|
const login = el('button', 'secondary', '登录');
|
||||||
|
login.addEventListener('click', () => openAuthDialog(false));
|
||||||
|
const reg = el('button', 'primary', '注册');
|
||||||
|
reg.addEventListener('click', () => openAuthDialog(true));
|
||||||
|
box.appendChild(login);
|
||||||
|
box.appendChild(reg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openAuthDialog(isRegister) {
|
||||||
|
const username = prompt(isRegister ? '注册用户名(≥3 字符)' : '用户名');
|
||||||
|
if (!username) return;
|
||||||
|
const password = prompt(isRegister ? '设置密码(≥6 字符)' : '密码');
|
||||||
|
if (!password) return;
|
||||||
|
const path = isRegister ? '/api/auth/register' : '/api/auth/login';
|
||||||
|
api(path, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ username, password }),
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
state.user = data.user;
|
||||||
|
renderAuth();
|
||||||
|
refreshHistory();
|
||||||
|
alert(isRegister ? '注册成功并已登录' : '登录成功');
|
||||||
|
})
|
||||||
|
.catch((err) => alert(`失败:${err.message}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 评测 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
function metricCard(k, v, cls) {
|
||||||
|
const box = el('div', 'metric');
|
||||||
|
box.appendChild(el('div', 'k', k));
|
||||||
|
box.appendChild(el('div', `v ${cls || ''}`, v));
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderEvalReport(report) {
|
||||||
|
const box = $('#eval-report');
|
||||||
|
box.innerHTML = '';
|
||||||
|
if (!report) {
|
||||||
|
box.appendChild(el('p', 'placeholder', '暂无评测报告。'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const grid = el('div', 'metric-grid');
|
||||||
|
const pct = (v) => `${(v * 100).toFixed(1)}%`;
|
||||||
|
grid.appendChild(metricCard('Top-1', pct(report.top1), report.top1 > 0.7 ? 'good' : 'warn'));
|
||||||
|
grid.appendChild(metricCard('Top-3', pct(report.top3)));
|
||||||
|
grid.appendChild(metricCard('Top-5', pct(report.top5)));
|
||||||
|
grid.appendChild(metricCard('MRR', report.mrr.toFixed(3)));
|
||||||
|
grid.appendChild(metricCard('粗召回率', pct(report.candidate_recall)));
|
||||||
|
grid.appendChild(metricCard('延迟 p50', `${report.p50_latency_ms.toFixed(0)} ms`));
|
||||||
|
grid.appendChild(metricCard('延迟 p95', `${report.p95_latency_ms.toFixed(0)} ms`));
|
||||||
|
grid.appendChild(metricCard('查询数', String(report.n_queries)));
|
||||||
|
box.appendChild(grid);
|
||||||
|
box.appendChild(el('p', 'hint',
|
||||||
|
`难度 ${report.difficulty} · 曲库 ${report.n_songs} 首 · 生成于 ${report.created_at} · ` +
|
||||||
|
`音符数比 ${report.note_count_ratio.toFixed(2)} · 音高误差中位数 ${report.pitch_err_median.toFixed(2)} 半音`));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderNoiseReport(report) {
|
||||||
|
const box = $('#noise-report');
|
||||||
|
box.innerHTML = '';
|
||||||
|
if (!report) return;
|
||||||
|
const table = document.createElement('table');
|
||||||
|
const thead = document.createElement('thead');
|
||||||
|
thead.innerHTML = '<tr><th>信噪比</th><th>Top-1</th><th>Top-5</th><th>MRR</th></tr>';
|
||||||
|
table.appendChild(thead);
|
||||||
|
const tbody = document.createElement('tbody');
|
||||||
|
(report.curve || []).forEach((row) => {
|
||||||
|
const tr = document.createElement('tr');
|
||||||
|
tr.appendChild(el('td', null, `${row.snr_db} dB`));
|
||||||
|
tr.appendChild(el('td', null, `${(row.top1 * 100).toFixed(1)}%`));
|
||||||
|
tr.appendChild(el('td', null, `${(row.top5 * 100).toFixed(1)}%`));
|
||||||
|
tr.appendChild(el('td', null, row.mrr.toFixed(3)));
|
||||||
|
tbody.appendChild(tr);
|
||||||
|
});
|
||||||
|
table.appendChild(tbody);
|
||||||
|
box.appendChild(table);
|
||||||
|
box.appendChild(el('p', 'hint', report.note || ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 状态栏 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
async function refreshStatus() {
|
||||||
|
try {
|
||||||
|
const data = await api('/api/status');
|
||||||
|
$('#status').innerHTML =
|
||||||
|
`曲库 <b>${data.n_songs}</b> 首 · 索引 <b>${data.n_grams}</b> 个 n-gram`;
|
||||||
|
} catch (err) {
|
||||||
|
$('#status').textContent = `服务不可用:${err.message}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadLatestEval() {
|
||||||
|
try {
|
||||||
|
const data = await api('/api/eval/latest');
|
||||||
|
renderEvalReport(data.available ? data.report : null);
|
||||||
|
} catch { renderEvalReport(null); }
|
||||||
|
try {
|
||||||
|
const data = await api('/api/noise/latest');
|
||||||
|
if (data.available) renderNoiseReport(data.report);
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* 事件绑定与初始化 */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
function bindTabs() {
|
||||||
|
$$('.tab').forEach((tab) => {
|
||||||
|
tab.addEventListener('click', () => {
|
||||||
|
$$('.tab').forEach((t) => t.classList.remove('active'));
|
||||||
|
$$('.tab-panel').forEach((p) => p.classList.remove('active'));
|
||||||
|
tab.classList.add('active');
|
||||||
|
$(`#tab-${tab.dataset.tab}`).classList.add('active');
|
||||||
|
if (tab.dataset.tab === 'library') refreshLibrary();
|
||||||
|
if (tab.dataset.tab === 'history') refreshHistory();
|
||||||
|
if (tab.dataset.tab === 'eval') loadLatestEval();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
bindTabs();
|
||||||
|
refreshStatus();
|
||||||
|
loadLatestEval();
|
||||||
|
|
||||||
|
api('/api/auth/me').then((data) => {
|
||||||
|
state.user = data.logged_in ? data.user : null;
|
||||||
|
renderAuth();
|
||||||
|
}).catch(() => renderAuth());
|
||||||
|
|
||||||
|
$('#btn-record').addEventListener('click', toggleRecord);
|
||||||
|
$('#btn-demo').addEventListener('click', runDemo);
|
||||||
|
|
||||||
|
$('#file-input').addEventListener('change', async (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (!file) return;
|
||||||
|
try {
|
||||||
|
const wav = await toWav16k(file);
|
||||||
|
await searchBlob(wav, 'upload');
|
||||||
|
} catch (err) {
|
||||||
|
$('#results').innerHTML = '';
|
||||||
|
$('#results').appendChild(el('p', 'placeholder', `音频处理失败:${err.message}`));
|
||||||
|
}
|
||||||
|
e.target.value = '';
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#import-file').addEventListener('change', async (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (!file) return;
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('file', file, file.name);
|
||||||
|
try {
|
||||||
|
await api('/api/library/import', { method: 'POST', body: form });
|
||||||
|
refreshLibrary();
|
||||||
|
refreshStatus();
|
||||||
|
alert('导入成功');
|
||||||
|
} catch (err) {
|
||||||
|
alert(`导入失败:${err.message}`);
|
||||||
|
}
|
||||||
|
e.target.value = '';
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#btn-rebuild').addEventListener('click', async () => {
|
||||||
|
if (!confirm('重建曲库会重新读取 data/midi 与内置曲谱,确认继续?')) return;
|
||||||
|
await api('/api/library/rebuild?force=true', { method: 'POST' });
|
||||||
|
refreshLibrary();
|
||||||
|
refreshStatus();
|
||||||
|
alert('曲库已重建');
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#btn-clear-history').addEventListener('click', async () => {
|
||||||
|
if (!confirm('清空检索历史?')) return;
|
||||||
|
await api('/api/history', { method: 'DELETE' });
|
||||||
|
refreshHistory();
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#btn-eval').addEventListener('click', async () => {
|
||||||
|
const btn = $('#btn-eval');
|
||||||
|
btn.disabled = true;
|
||||||
|
$('#eval-status').textContent = '评测运行中…(每首歌曲生成若干合成查询并跑完整流水线)';
|
||||||
|
try {
|
||||||
|
const data = await api('/api/eval/run', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
difficulty: $('#eval-difficulty').value,
|
||||||
|
per_song: Number($('#eval-per-song').value) || 2,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
renderEvalReport(data.report);
|
||||||
|
$('#eval-status').textContent = '评测完成。';
|
||||||
|
} catch (err) {
|
||||||
|
$('#eval-status').textContent = `评测失败:${err.message}`;
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
if (state.lastResult) renderResults(state.lastResult);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', init);
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>基于旋律的音乐哼唱检索系统</title>
|
||||||
|
<link rel="stylesheet" href="/static/style.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="brand">
|
||||||
|
<span class="logo">♪</span>
|
||||||
|
<div>
|
||||||
|
<h1>基于旋律的音乐哼唱检索系统</h1>
|
||||||
|
<p class="subtitle">Query by Humming · YIN 基频提取 + 多码本倒排索引 + 子序列 DTW</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="topbar-right">
|
||||||
|
<div id="status" class="status">加载中…</div>
|
||||||
|
<div id="auth" class="auth"></div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav class="tabs">
|
||||||
|
<button class="tab active" data-tab="search">哼唱检索</button>
|
||||||
|
<button class="tab" data-tab="library">曲库管理</button>
|
||||||
|
<button class="tab" data-tab="history">检索历史</button>
|
||||||
|
<button class="tab" data-tab="eval">评测与实验</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<!-- ================= 检索 ================= -->
|
||||||
|
<section class="tab-panel active" id="tab-search">
|
||||||
|
<div class="layout">
|
||||||
|
<aside class="panel query-panel">
|
||||||
|
<h2>输入查询</h2>
|
||||||
|
|
||||||
|
<div class="query-mode">
|
||||||
|
<button id="btn-record" class="primary big">🎤 开始录音</button>
|
||||||
|
<p id="record-hint" class="hint">点击后对着麦克风哼唱 5–15 秒旋律片段</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="divider">或</div>
|
||||||
|
|
||||||
|
<label class="file-drop">
|
||||||
|
<input type="file" id="file-input" accept="audio/*" hidden />
|
||||||
|
<span>📁 选择音频文件(WAV / MP3 / FLAC)</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div class="divider">或</div>
|
||||||
|
|
||||||
|
<div class="demo-box">
|
||||||
|
<div class="demo-row">
|
||||||
|
<label for="demo-difficulty">随机示范查询</label>
|
||||||
|
<select id="demo-difficulty">
|
||||||
|
<option value="easy">简单</option>
|
||||||
|
<option value="normal" selected>中等</option>
|
||||||
|
<option value="hard">困难</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<button id="btn-demo" class="secondary big">🎲 生成机器哼唱并检索</button>
|
||||||
|
<p class="hint">由合成器模拟人声哼唱(移调 / 变速 / 丢音 / 加噪),答案已知,便于验证系统</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="divider">参数</div>
|
||||||
|
<div class="demo-row">
|
||||||
|
<label for="top-k">返回条数</label>
|
||||||
|
<input type="number" id="top-k" value="10" min="1" max="50" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="query-info" class="query-info hidden">
|
||||||
|
<h3>识别到的旋律</h3>
|
||||||
|
<div id="query-chips" class="chips"></div>
|
||||||
|
<canvas id="query-contour" width="420" height="140"></canvas>
|
||||||
|
<p id="query-meta" class="hint"></p>
|
||||||
|
<audio id="query-audio" controls class="hidden"></audio>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="panel results-panel">
|
||||||
|
<div class="results-head">
|
||||||
|
<h2>检索结果</h2>
|
||||||
|
<span id="results-meta" class="hint"></span>
|
||||||
|
</div>
|
||||||
|
<div id="demo-banner" class="banner hidden"></div>
|
||||||
|
<div id="results" class="results">
|
||||||
|
<p class="placeholder">还没有查询。录一段哼唱、上传音频,或点「生成机器哼唱」试试。</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="alignment-wrap" class="alignment hidden">
|
||||||
|
<h3>DTW 对齐</h3>
|
||||||
|
<canvas id="alignment" width="880" height="300"></canvas>
|
||||||
|
<p class="hint">左列为哼唱查询,右列为命中曲目片段;连线表示对齐路径,颜色越红表示音高偏差越大。</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ================= 曲库 ================= -->
|
||||||
|
<section class="tab-panel" id="tab-library">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="results-head">
|
||||||
|
<h2>曲库(<span id="lib-count">0</span> 首)</h2>
|
||||||
|
<div class="lib-actions">
|
||||||
|
<label class="button-like">
|
||||||
|
<input type="file" id="import-file" accept=".mid,.midi,audio/*" hidden />
|
||||||
|
导入 MIDI / 音频
|
||||||
|
</label>
|
||||||
|
<button id="btn-rebuild" class="secondary">重建索引</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="song-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>曲目</th><th>来源</th><th>标签</th><th>音符数</th><th>时长</th><th>操作</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ================= 历史 ================= -->
|
||||||
|
<section class="tab-panel" id="tab-history">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="results-head">
|
||||||
|
<h2>检索历史</h2>
|
||||||
|
<button id="btn-clear-history" class="secondary">清空</button>
|
||||||
|
</div>
|
||||||
|
<p class="hint" id="history-scope"></p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="history-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>时间</th><th>来源</th><th>查询音符</th><th>最佳匹配</th><th>分数</th><th>耗时</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ================= 评测 ================= -->
|
||||||
|
<section class="tab-panel" id="tab-eval">
|
||||||
|
<div class="layout">
|
||||||
|
<div class="panel">
|
||||||
|
<h2>运行评测</h2>
|
||||||
|
<p class="hint">用合成哼唱查询跑完整流水线,统计 Top-K / MRR / 粗召回率 / 延迟。</p>
|
||||||
|
<div class="demo-row">
|
||||||
|
<label for="eval-difficulty">难度</label>
|
||||||
|
<select id="eval-difficulty">
|
||||||
|
<option value="easy">简单</option>
|
||||||
|
<option value="normal" selected>中等</option>
|
||||||
|
<option value="hard">困难</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="demo-row">
|
||||||
|
<label for="eval-per-song">每首查询数</label>
|
||||||
|
<input type="number" id="eval-per-song" value="2" min="1" max="10" />
|
||||||
|
</div>
|
||||||
|
<button id="btn-eval" class="primary big">▶ 开始评测</button>
|
||||||
|
<p id="eval-status" class="hint"></p>
|
||||||
|
</div>
|
||||||
|
<div class="panel">
|
||||||
|
<h2>最近一次评测</h2>
|
||||||
|
<div id="eval-report"><p class="placeholder">暂无评测报告。</p></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="panel" id="noise-panel">
|
||||||
|
<h2>噪声鲁棒性实验</h2>
|
||||||
|
<div id="noise-report"><p class="placeholder">尚未运行(可执行 <code>python -m scripts.noise_experiment</code>)。</p></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="footer">
|
||||||
|
<span>本系统为课程/科研用途实现,曲库含公版旋律与合成旋律。</span>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<script src="/static/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
:root {
|
||||||
|
--bg: #0f1420;
|
||||||
|
--bg-soft: #171e2e;
|
||||||
|
--panel: #1c2436;
|
||||||
|
--panel-2: #232d42;
|
||||||
|
--border: #2e3a52;
|
||||||
|
--text: #e6ecf7;
|
||||||
|
--text-dim: #93a1bb;
|
||||||
|
--accent: #4f8cff;
|
||||||
|
--accent-2: #35d0a5;
|
||||||
|
--warn: #ffb454;
|
||||||
|
--danger: #ff6b6b;
|
||||||
|
--radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: "Segoe UI", "Microsoft YaHei", system-ui, -apple-system, sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 { font-size: 18px; margin: 0; }
|
||||||
|
h2 { font-size: 15px; margin: 0 0 12px; color: var(--text); }
|
||||||
|
h3 { font-size: 13px; margin: 16px 0 8px; color: var(--text-dim); }
|
||||||
|
|
||||||
|
code {
|
||||||
|
background: #0b0f18;
|
||||||
|
padding: 1px 5px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 顶栏 ---------------- */
|
||||||
|
.topbar {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 14px 22px;
|
||||||
|
background: linear-gradient(180deg, #1a2334, #141b29);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand { display: flex; align-items: center; gap: 14px; }
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
width: 40px; height: 40px;
|
||||||
|
display: grid; place-items: center;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: linear-gradient(135deg, var(--accent), var(--accent-2));
|
||||||
|
font-size: 22px;
|
||||||
|
color: #06121f;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.subtitle { margin: 2px 0 0; color: var(--text-dim); font-size: 12px; }
|
||||||
|
|
||||||
|
.topbar-right { display: flex; align-items: center; gap: 14px; }
|
||||||
|
|
||||||
|
.status { color: var(--text-dim); font-size: 12px; text-align: right; }
|
||||||
|
.status b { color: var(--accent-2); }
|
||||||
|
|
||||||
|
.auth { display: flex; align-items: center; gap: 8px; }
|
||||||
|
|
||||||
|
/* ---------------- 标签页 ---------------- */
|
||||||
|
.tabs {
|
||||||
|
display: flex;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 0 22px;
|
||||||
|
background: var(--bg-soft);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
color: var(--text-dim);
|
||||||
|
padding: 11px 18px;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
border-bottom: 2px solid transparent;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab:hover { color: var(--text); }
|
||||||
|
.tab.active { color: var(--text); border-bottom-color: var(--accent); }
|
||||||
|
|
||||||
|
.tab-panel { display: none; padding: 20px 22px 40px; }
|
||||||
|
.tab-panel.active { display: block; }
|
||||||
|
|
||||||
|
/* ---------------- 布局 ---------------- */
|
||||||
|
.layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(320px, 400px) 1fr;
|
||||||
|
gap: 18px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1080px) {
|
||||||
|
.layout { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 18px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.query-panel { position: sticky; top: 16px; }
|
||||||
|
|
||||||
|
/* ---------------- 控件 ---------------- */
|
||||||
|
button, .button-like {
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--panel-2);
|
||||||
|
color: var(--text);
|
||||||
|
padding: 8px 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background .15s, border-color .15s, transform .05s;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover, .button-like:hover { background: #2b3750; border-color: #3d4d6d; }
|
||||||
|
button:active { transform: translateY(1px); }
|
||||||
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
||||||
|
|
||||||
|
button.primary { background: linear-gradient(135deg, #3a72e0, #4f8cff); border-color: #4f8cff; color: #fff; }
|
||||||
|
button.primary:hover { background: linear-gradient(135deg, #4a80ee, #5f9aff); }
|
||||||
|
button.secondary { background: #26314a; }
|
||||||
|
button.big { width: 100%; padding: 11px; font-size: 14px; }
|
||||||
|
|
||||||
|
button.recording {
|
||||||
|
background: linear-gradient(135deg, #c0392b, #ff6b6b) !important;
|
||||||
|
border-color: var(--danger) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="number"], select {
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
background: #131a28;
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 7px;
|
||||||
|
padding: 6px 9px;
|
||||||
|
width: 110px;
|
||||||
|
}
|
||||||
|
|
||||||
|
label { color: var(--text-dim); font-size: 13px; }
|
||||||
|
|
||||||
|
.divider {
|
||||||
|
text-align: center;
|
||||||
|
color: var(--text-dim);
|
||||||
|
font-size: 12px;
|
||||||
|
margin: 14px 0;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.divider::before, .divider::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
width: 38%;
|
||||||
|
height: 1px;
|
||||||
|
background: var(--border);
|
||||||
|
}
|
||||||
|
.divider::before { left: 0; }
|
||||||
|
.divider::after { right: 0; }
|
||||||
|
|
||||||
|
.file-drop {
|
||||||
|
display: block;
|
||||||
|
text-align: center;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px dashed var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
.file-drop:hover { border-color: var(--accent); color: var(--text); }
|
||||||
|
|
||||||
|
.demo-box { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
|
||||||
|
.demo-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 8px 0; }
|
||||||
|
|
||||||
|
.hint { color: var(--text-dim); font-size: 12px; margin: 6px 0 0; }
|
||||||
|
.hidden { display: none !important; }
|
||||||
|
|
||||||
|
/* ---------------- 结果 ---------------- */
|
||||||
|
.results-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; margin-bottom: 12px; }
|
||||||
|
|
||||||
|
.results { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
|
||||||
|
.placeholder { color: var(--text-dim); font-size: 13px; }
|
||||||
|
|
||||||
|
.result-item {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 38px 1fr auto;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: center;
|
||||||
|
padding: 11px 13px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--panel-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-item.top { border-color: var(--accent-2); box-shadow: 0 0 0 1px rgba(53, 208, 165, .25); }
|
||||||
|
.result-item.correct { border-color: var(--accent-2); }
|
||||||
|
|
||||||
|
.rank { font-size: 16px; color: var(--text-dim); text-align: center; font-weight: 600; }
|
||||||
|
.result-item.top .rank { color: var(--accent-2); }
|
||||||
|
|
||||||
|
.result-main { min-width: 0; }
|
||||||
|
.result-title { font-size: 14px; font-weight: 600; }
|
||||||
|
.result-sub { font-size: 12px; color: var(--text-dim); margin-top: 2px; }
|
||||||
|
|
||||||
|
.score-wrap { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.score-bar { width: 120px; height: 7px; background: #101725; border-radius: 4px; overflow: hidden; }
|
||||||
|
.score-bar > i { display: block; height: 100%; background: linear-gradient(90deg, var(--accent), var(--accent-2)); }
|
||||||
|
.score-num { font-variant-numeric: tabular-nums; color: var(--text); min-width: 46px; text-align: right; }
|
||||||
|
|
||||||
|
.play-btn { padding: 5px 10px; font-size: 12px; }
|
||||||
|
|
||||||
|
.chips { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 10px; }
|
||||||
|
|
||||||
|
.chip {
|
||||||
|
font-size: 11px;
|
||||||
|
padding: 2px 7px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #23304a;
|
||||||
|
color: #cfe0ff;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.banner {
|
||||||
|
padding: 10px 13px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: #1b2740;
|
||||||
|
}
|
||||||
|
.banner.ok { border-color: var(--accent-2); background: rgba(53, 208, 165, .12); }
|
||||||
|
.banner.bad { border-color: var(--warn); background: rgba(255, 180, 84, .12); }
|
||||||
|
|
||||||
|
canvas { width: 100%; height: auto; display: block; border-radius: 8px; background: #101725; }
|
||||||
|
|
||||||
|
/* ---------------- 表格 ---------------- */
|
||||||
|
.table-wrap { overflow-x: auto; }
|
||||||
|
|
||||||
|
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||||
|
th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--border); }
|
||||||
|
th { color: var(--text-dim); font-weight: 500; font-size: 12px; }
|
||||||
|
tbody tr:hover { background: #202a3e; }
|
||||||
|
|
||||||
|
.tag {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 11px;
|
||||||
|
padding: 1px 7px;
|
||||||
|
margin-right: 4px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #23304a;
|
||||||
|
color: #b9ccf0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; }
|
||||||
|
|
||||||
|
.metric {
|
||||||
|
background: var(--panel-2);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 9px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
}
|
||||||
|
.metric .k { color: var(--text-dim); font-size: 12px; }
|
||||||
|
.metric .v { font-size: 20px; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||||
|
.metric .v.good { color: var(--accent-2); }
|
||||||
|
.metric .v.warn { color: var(--warn); }
|
||||||
|
|
||||||
|
.footer { padding: 18px 22px 30px; color: var(--text-dim); font-size: 12px; text-align: center; }
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
"""统一命令行入口。
|
||||||
|
|
||||||
|
::
|
||||||
|
|
||||||
|
python cli.py build # 构建/重建曲库与索引
|
||||||
|
python cli.py list # 列出曲库
|
||||||
|
python cli.py search hum.wav --top-k 5 # 用音频文件检索
|
||||||
|
python cli.py demo --difficulty hard # 生成示范查询并检索
|
||||||
|
python cli.py eval --per-song 3 # 跑评测
|
||||||
|
python cli.py bench --sizes 300,600 # 大规模基准
|
||||||
|
python cli.py noise # 噪声鲁棒性实验
|
||||||
|
python cli.py import song.mid # 导入 MIDI
|
||||||
|
python cli.py serve --port 8700 # 启动 Web 服务
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from qbh.audio import read_audio # noqa: E402
|
||||||
|
from qbh.config import DEFAULT # noqa: E402
|
||||||
|
from qbh.evaluate import make_query_specs, perturb_melody, synth_query_audio # noqa: E402
|
||||||
|
from qbh.library import Library # noqa: E402
|
||||||
|
from qbh.search import SearchEngine # noqa: E402
|
||||||
|
from qbh.store import Store # noqa: E402
|
||||||
|
|
||||||
|
DB_PATH = ROOT / "data" / "qbh.db"
|
||||||
|
|
||||||
|
|
||||||
|
def _open_library(args) -> tuple[Store, Library, SearchEngine]:
|
||||||
|
store = Store(args.db)
|
||||||
|
library = Library(store, DEFAULT, midi_dir=ROOT / "data" / "midi", audio_dir=ROOT / "data" / "audio")
|
||||||
|
if library.count() == 0:
|
||||||
|
print("曲库为空,正在构建…")
|
||||||
|
library.build()
|
||||||
|
engine = SearchEngine(library, DEFAULT)
|
||||||
|
return store, library, engine
|
||||||
|
|
||||||
|
|
||||||
|
def _print_hits(result) -> None:
|
||||||
|
if not result.hits:
|
||||||
|
print("没有找到匹配的旋律。")
|
||||||
|
return
|
||||||
|
print(f"查询:{result.query.n_notes} 个音符 / {result.query.duration:.2f}s · "
|
||||||
|
f"候选 {result.n_candidates}/{result.n_songs} · 耗时 {result.elapsed_ms:.0f} ms")
|
||||||
|
for idx, hit in enumerate(result.hits, start=1):
|
||||||
|
print(f" {idx:2d}. {hit.title:<16s} score={hit.score:.3f} "
|
||||||
|
f"(DTW {hit.dtw_sim:.3f} / 索引 {hit.index_sim:.3f}) "
|
||||||
|
f"移调 {hit.shift:+.0f} · 片段 {hit.target_start_s:.1f}–{hit.target_end_s:.1f}s")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_build(args) -> int:
|
||||||
|
store = Store(args.db)
|
||||||
|
library = Library(store, DEFAULT, midi_dir=ROOT / "data" / "midi", audio_dir=ROOT / "data" / "audio")
|
||||||
|
report = library.build(force=args.force, render_audio=not args.no_audio)
|
||||||
|
print(json.dumps(report.to_dict(), ensure_ascii=False, indent=2))
|
||||||
|
engine = SearchEngine(library, DEFAULT)
|
||||||
|
print(f"索引:{engine.index.n_grams()} 个 n-gram,覆盖 {engine.index.n_songs} 首")
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_list(args) -> int:
|
||||||
|
store, library, _engine = _open_library(args)
|
||||||
|
print(f"曲库共 {library.count()} 首:")
|
||||||
|
for record in library.songs():
|
||||||
|
tags = ",".join(record.tags)
|
||||||
|
print(f" {record.id:<26s} {record.title:<18s} {record.n_notes:>3d} 音 "
|
||||||
|
f"{record.duration:6.1f}s [{record.source}] {tags}")
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_search(args) -> int:
|
||||||
|
store, library, engine = _open_library(args)
|
||||||
|
samples, sr = read_audio(args.audio)
|
||||||
|
result, _track = engine.search_audio(samples, sr, top_k=args.top_k)
|
||||||
|
_print_hits(result)
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_demo(args) -> int:
|
||||||
|
store, library, engine = _open_library(args)
|
||||||
|
specs = make_query_specs(
|
||||||
|
library.melodies(), n_per_song=1, difficulty=args.difficulty, seed=args.seed
|
||||||
|
)
|
||||||
|
if not specs:
|
||||||
|
print("无法生成示范查询。")
|
||||||
|
return 1
|
||||||
|
spec = specs[0]
|
||||||
|
source = next(m for m in library.melodies() if m.song_id == spec.song_id)
|
||||||
|
truth = perturb_melody(source, spec, DEFAULT)
|
||||||
|
audio = synth_query_audio(truth, spec, DEFAULT)
|
||||||
|
result, _track = engine.search_audio(audio, DEFAULT.sample_rate, top_k=args.top_k)
|
||||||
|
print(f"示范查询:{spec.title} · 移调 {spec.shift:+.0f} · 速度 {spec.tempo:.2f}× · "
|
||||||
|
f"SNR {spec.snr_db:g} dB · 片段 {spec.n_notes} 音")
|
||||||
|
_print_hits(result)
|
||||||
|
rank = next((i + 1 for i, h in enumerate(result.hits) if h.song_id == spec.song_id), 0)
|
||||||
|
print(f"\n正确答案「{spec.title}」排名:{rank if rank else '未进入 Top-K'}")
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_import(args) -> int:
|
||||||
|
store, library, _engine = _open_library(args)
|
||||||
|
path = Path(args.file)
|
||||||
|
if path.suffix.lower() in (".mid", ".midi"):
|
||||||
|
record = library.add_midi_file(path, song_id=args.id, title=args.title)
|
||||||
|
else:
|
||||||
|
from qbh.audio import preprocess
|
||||||
|
from qbh.notes import segment_notes
|
||||||
|
from qbh.pitch import extract_pitch
|
||||||
|
|
||||||
|
samples, sr = read_audio(path)
|
||||||
|
track = extract_pitch(preprocess(samples, sr, DEFAULT), DEFAULT.sample_rate, DEFAULT)
|
||||||
|
melody = segment_notes(track, DEFAULT)
|
||||||
|
record = library.add_melody(
|
||||||
|
melody, song_id=args.id or f"import_{path.stem}",
|
||||||
|
title=args.title or path.stem, origin="导入音频", source="audio",
|
||||||
|
)
|
||||||
|
print(f"已导入:{record.id} · {record.title} · {record.n_notes} 个音符")
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_eval(args) -> int:
|
||||||
|
from scripts.run_eval import main as run_eval_main
|
||||||
|
|
||||||
|
argv = ["--per-song", str(args.per_song), "--seed", str(args.seed)]
|
||||||
|
if args.difficulty != "all":
|
||||||
|
argv += ["--difficulty", args.difficulty]
|
||||||
|
if args.markdown:
|
||||||
|
argv += ["--markdown", args.markdown]
|
||||||
|
return run_eval_main(argv)
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_bench(args) -> int:
|
||||||
|
from qbh.bench import run_scale_benchmark
|
||||||
|
|
||||||
|
sizes = tuple(int(v) for v in args.sizes.split(","))
|
||||||
|
report = run_scale_benchmark(
|
||||||
|
sizes, n_queries_per_size=args.queries, seed=args.seed, cfg=DEFAULT
|
||||||
|
)
|
||||||
|
print()
|
||||||
|
print(report.markdown_table())
|
||||||
|
report.save(args.out)
|
||||||
|
print(f"\n→ {args.out}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_noise(args) -> int:
|
||||||
|
from scripts.noise_experiment import main as noise_main
|
||||||
|
|
||||||
|
return noise_main(["--per-song", str(args.per_song), "--levels", args.levels])
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_serve(args) -> int:
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
print(f"服务地址:http://{args.host}:{args.port}")
|
||||||
|
uvicorn.run("app.main:app", host=args.host, port=args.port, reload=args.reload)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_tune(args) -> int:
|
||||||
|
from scripts.tune import main as tune_main
|
||||||
|
|
||||||
|
return tune_main(["--per-song", str(args.per_song), "--rounds", str(args.rounds)])
|
||||||
|
|
||||||
|
|
||||||
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog="cli.py", description="基于旋律的音乐哼唱检索系统 —— 命令行入口"
|
||||||
|
)
|
||||||
|
parser.add_argument("--db", default=str(DB_PATH))
|
||||||
|
sub = parser.add_subparsers(dest="command", required=True)
|
||||||
|
|
||||||
|
p = sub.add_parser("build", help="构建/重建曲库与索引")
|
||||||
|
p.add_argument("--force", action="store_true", help="强制重建")
|
||||||
|
p.add_argument("--no-audio", action="store_true", help="跳过示范音频合成")
|
||||||
|
p.set_defaults(func=cmd_build)
|
||||||
|
|
||||||
|
p = sub.add_parser("list", help="列出曲库")
|
||||||
|
p.set_defaults(func=cmd_list)
|
||||||
|
|
||||||
|
p = sub.add_parser("search", help="用音频文件检索")
|
||||||
|
p.add_argument("audio", help="音频文件路径")
|
||||||
|
p.add_argument("--top-k", type=int, default=10)
|
||||||
|
p.set_defaults(func=cmd_search)
|
||||||
|
|
||||||
|
p = sub.add_parser("demo", help="生成示范查询并检索")
|
||||||
|
p.add_argument("--difficulty", default="normal", choices=("easy", "normal", "hard"))
|
||||||
|
p.add_argument("--seed", type=int, default=None)
|
||||||
|
p.add_argument("--top-k", type=int, default=10)
|
||||||
|
p.set_defaults(func=cmd_demo)
|
||||||
|
|
||||||
|
p = sub.add_parser("import", help="导入 MIDI 或音频")
|
||||||
|
p.add_argument("file")
|
||||||
|
p.add_argument("--id", default=None)
|
||||||
|
p.add_argument("--title", default="")
|
||||||
|
p.set_defaults(func=cmd_import)
|
||||||
|
|
||||||
|
p = sub.add_parser("eval", help="跑评测")
|
||||||
|
p.add_argument("--per-song", type=int, default=3)
|
||||||
|
p.add_argument("--seed", type=int, default=20260908)
|
||||||
|
p.add_argument("--difficulty", default="all", choices=("all", "easy", "normal", "hard"))
|
||||||
|
p.add_argument("--markdown", default="")
|
||||||
|
p.set_defaults(func=cmd_eval)
|
||||||
|
|
||||||
|
p = sub.add_parser("bench", help="大规模基准")
|
||||||
|
p.add_argument("--sizes", default="300,600,1000")
|
||||||
|
p.add_argument("--queries", type=int, default=60)
|
||||||
|
p.add_argument("--seed", type=int, default=20260908)
|
||||||
|
p.add_argument("--out", default="data/bench_report.json")
|
||||||
|
p.set_defaults(func=cmd_bench)
|
||||||
|
|
||||||
|
p = sub.add_parser("noise", help="噪声鲁棒性实验")
|
||||||
|
p.add_argument("--per-song", type=int, default=2)
|
||||||
|
p.add_argument("--levels", default="22,18,15,12.5,10,7.5,5")
|
||||||
|
p.set_defaults(func=cmd_noise)
|
||||||
|
|
||||||
|
p = sub.add_parser("serve", help="启动 Web 服务")
|
||||||
|
p.add_argument("--host", default="127.0.0.1")
|
||||||
|
p.add_argument("--port", type=int, default=8700)
|
||||||
|
p.add_argument("--reload", action="store_true")
|
||||||
|
p.set_defaults(func=cmd_serve)
|
||||||
|
|
||||||
|
p = sub.add_parser("tune", help="排序参数调优")
|
||||||
|
p.add_argument("--per-song", type=int, default=3)
|
||||||
|
p.add_argument("--rounds", type=int, default=2)
|
||||||
|
p.set_defaults(func=cmd_tune)
|
||||||
|
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
parser = build_parser()
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
return int(args.func(args) or 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
{
|
||||||
|
"sizes": [
|
||||||
|
300,
|
||||||
|
600,
|
||||||
|
1000
|
||||||
|
],
|
||||||
|
"difficulty": "normal",
|
||||||
|
"seed": 20260908,
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 4,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.8,
|
||||||
|
"w_index": 0.2,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"n_songs": 300,
|
||||||
|
"n_queries": 60,
|
||||||
|
"n_grams": 11136,
|
||||||
|
"build_seconds": 1.27,
|
||||||
|
"index_seconds": 0.133,
|
||||||
|
"candidate_recall": 0.9833,
|
||||||
|
"top1": 0.9,
|
||||||
|
"top5": 0.9667,
|
||||||
|
"mrr": 0.9264,
|
||||||
|
"mean_candidates": 121.1,
|
||||||
|
"p50_ms": 255.95,
|
||||||
|
"p95_ms": 418.03,
|
||||||
|
"mean_ms": 270.91
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"n_songs": 600,
|
||||||
|
"n_queries": 60,
|
||||||
|
"n_grams": 16451,
|
||||||
|
"build_seconds": 2.5,
|
||||||
|
"index_seconds": 0.189,
|
||||||
|
"candidate_recall": 0.95,
|
||||||
|
"top1": 0.8,
|
||||||
|
"top5": 0.8667,
|
||||||
|
"mrr": 0.8352,
|
||||||
|
"mean_candidates": 166.4,
|
||||||
|
"p50_ms": 324.18,
|
||||||
|
"p95_ms": 485.85,
|
||||||
|
"mean_ms": 326.49
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"n_songs": 1000,
|
||||||
|
"n_queries": 60,
|
||||||
|
"n_grams": 21918,
|
||||||
|
"build_seconds": 4.42,
|
||||||
|
"index_seconds": 0.322,
|
||||||
|
"candidate_recall": 0.9,
|
||||||
|
"top1": 0.8,
|
||||||
|
"top5": 0.8833,
|
||||||
|
"mrr": 0.8361,
|
||||||
|
"mean_candidates": 219.5,
|
||||||
|
"p50_ms": 432.9,
|
||||||
|
"p95_ms": 673.39,
|
||||||
|
"mean_ms": 457.14
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,15 @@
|
|||||||
|
mode,snr_db,top1,top3,top5,mrr,p50_ms
|
||||||
|
preprocess-on,22.0,0.7093023255813954,0.8023255813953488,0.8372093023255814,0.7671834625322997,72.02624999990803
|
||||||
|
preprocess-on,18.0,0.7093023255813954,0.8255813953488372,0.8488372093023255,0.7740586932447399,71.0425999996005
|
||||||
|
preprocess-on,15.0,0.7209302325581395,0.813953488372093,0.8372093023255814,0.7798080472499077,73.41159999941738
|
||||||
|
preprocess-on,12.5,0.7325581395348837,0.8023255813953488,0.8372093023255814,0.781423034330011,69.6736999998393
|
||||||
|
preprocess-on,10.0,0.7325581395348837,0.8255813953488372,0.8604651162790697,0.7786267995570321,69.56445000014355
|
||||||
|
preprocess-on,7.5,0.6976744186046512,0.813953488372093,0.8604651162790697,0.763016795865633,67.77520000014192
|
||||||
|
preprocess-on,5.0,0.7093023255813954,0.8255813953488372,0.872093023255814,0.7807308970099668,67.49765000040497
|
||||||
|
preprocess-off,22.0,0.7325581395348837,0.8255813953488372,0.8488372093023255,0.7829457364341085,71.09414999922592
|
||||||
|
preprocess-off,18.0,0.6976744186046512,0.8023255813953488,0.8372093023255814,0.7587624584717608,67.4398499995732
|
||||||
|
preprocess-off,15.0,0.7093023255813954,0.8255813953488372,0.8488372093023255,0.7755121816168328,67.29695000012725
|
||||||
|
preprocess-off,12.5,0.7093023255813954,0.8255813953488372,0.8604651162790697,0.775968992248062,70.59454999944137
|
||||||
|
preprocess-off,10.0,0.7558139534883721,0.8488372093023255,0.8604651162790697,0.8080703211517165,74.07790000070236
|
||||||
|
preprocess-off,7.5,0.1511627906976744,0.23255813953488372,0.32558139534883723,0.21590531561461795,216.6959999995015
|
||||||
|
preprocess-off,5.0,0.05813953488372093,0.12790697674418605,0.19767441860465115,0.11054355850867478,201.4866500003336
|
||||||
|
@@ -0,0 +1,132 @@
|
|||||||
|
{
|
||||||
|
"levels": [
|
||||||
|
22.0,
|
||||||
|
18.0,
|
||||||
|
15.0,
|
||||||
|
12.5,
|
||||||
|
10.0,
|
||||||
|
7.5,
|
||||||
|
5.0
|
||||||
|
],
|
||||||
|
"per_song": 2,
|
||||||
|
"seed": 20260908,
|
||||||
|
"n_songs": 43,
|
||||||
|
"curve": [
|
||||||
|
{
|
||||||
|
"snr_db": 22.0,
|
||||||
|
"top1": 0.7093023255813954,
|
||||||
|
"top3": 0.8023255813953488,
|
||||||
|
"top5": 0.8372093023255814,
|
||||||
|
"mrr": 0.7671834625322997,
|
||||||
|
"p50_ms": 72.02624999990803
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 18.0,
|
||||||
|
"top1": 0.7093023255813954,
|
||||||
|
"top3": 0.8255813953488372,
|
||||||
|
"top5": 0.8488372093023255,
|
||||||
|
"mrr": 0.7740586932447399,
|
||||||
|
"p50_ms": 71.0425999996005
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 15.0,
|
||||||
|
"top1": 0.7209302325581395,
|
||||||
|
"top3": 0.813953488372093,
|
||||||
|
"top5": 0.8372093023255814,
|
||||||
|
"mrr": 0.7798080472499077,
|
||||||
|
"p50_ms": 73.41159999941738
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 12.5,
|
||||||
|
"top1": 0.7325581395348837,
|
||||||
|
"top3": 0.8023255813953488,
|
||||||
|
"top5": 0.8372093023255814,
|
||||||
|
"mrr": 0.781423034330011,
|
||||||
|
"p50_ms": 69.6736999998393
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 10.0,
|
||||||
|
"top1": 0.7325581395348837,
|
||||||
|
"top3": 0.8255813953488372,
|
||||||
|
"top5": 0.8604651162790697,
|
||||||
|
"mrr": 0.7786267995570321,
|
||||||
|
"p50_ms": 69.56445000014355
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 7.5,
|
||||||
|
"top1": 0.6976744186046512,
|
||||||
|
"top3": 0.813953488372093,
|
||||||
|
"top5": 0.8604651162790697,
|
||||||
|
"mrr": 0.763016795865633,
|
||||||
|
"p50_ms": 67.77520000014192
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 5.0,
|
||||||
|
"top1": 0.7093023255813954,
|
||||||
|
"top3": 0.8255813953488372,
|
||||||
|
"top5": 0.872093023255814,
|
||||||
|
"mrr": 0.7807308970099668,
|
||||||
|
"p50_ms": 67.49765000040497
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"baseline_no_preprocess": [
|
||||||
|
{
|
||||||
|
"snr_db": 22.0,
|
||||||
|
"top1": 0.7325581395348837,
|
||||||
|
"top3": 0.8255813953488372,
|
||||||
|
"top5": 0.8488372093023255,
|
||||||
|
"mrr": 0.7829457364341085,
|
||||||
|
"p50_ms": 71.09414999922592
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 18.0,
|
||||||
|
"top1": 0.6976744186046512,
|
||||||
|
"top3": 0.8023255813953488,
|
||||||
|
"top5": 0.8372093023255814,
|
||||||
|
"mrr": 0.7587624584717608,
|
||||||
|
"p50_ms": 67.4398499995732
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 15.0,
|
||||||
|
"top1": 0.7093023255813954,
|
||||||
|
"top3": 0.8255813953488372,
|
||||||
|
"top5": 0.8488372093023255,
|
||||||
|
"mrr": 0.7755121816168328,
|
||||||
|
"p50_ms": 67.29695000012725
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 12.5,
|
||||||
|
"top1": 0.7093023255813954,
|
||||||
|
"top3": 0.8255813953488372,
|
||||||
|
"top5": 0.8604651162790697,
|
||||||
|
"mrr": 0.775968992248062,
|
||||||
|
"p50_ms": 70.59454999944137
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 10.0,
|
||||||
|
"top1": 0.7558139534883721,
|
||||||
|
"top3": 0.8488372093023255,
|
||||||
|
"top5": 0.8604651162790697,
|
||||||
|
"mrr": 0.8080703211517165,
|
||||||
|
"p50_ms": 74.07790000070236
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 7.5,
|
||||||
|
"top1": 0.1511627906976744,
|
||||||
|
"top3": 0.23255813953488372,
|
||||||
|
"top5": 0.32558139534883723,
|
||||||
|
"mrr": 0.21590531561461795,
|
||||||
|
"p50_ms": 216.6959999995015
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"snr_db": 5.0,
|
||||||
|
"top1": 0.05813953488372093,
|
||||||
|
"top3": 0.12790697674418605,
|
||||||
|
"top5": 0.19767441860465115,
|
||||||
|
"mrr": 0.11054355850867478,
|
||||||
|
"p50_ms": 201.4866500003336
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"knee_snr_db": null,
|
||||||
|
"note": "查询为合成哼唱(含颤音/滑音/丢音)按目标信噪比叠加白噪声;knee_snr_db 表示 Top-1 首次跌破 50% 的信噪比。"
|
||||||
|
}
|
||||||
@@ -0,0 +1,560 @@
|
|||||||
|
{
|
||||||
|
"best_top1": 0.7829457364341085,
|
||||||
|
"config_diff": {
|
||||||
|
"transpose_span": 2,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3
|
||||||
|
},
|
||||||
|
"history": [
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 4,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.8,
|
||||||
|
"w_index": 0.2,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7596899224806202
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 4,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7751937984496124
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 4,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7751937984496124
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 4,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7751937984496124
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 4,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7751937984496124
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 2,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7829457364341085
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 2,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7829457364341085
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 2,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7829457364341085
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 2,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7829457364341085
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 2,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7829457364341085
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"band_low_hz": 60.0,
|
||||||
|
"band_high_hz": 2000.0,
|
||||||
|
"band_order": 4,
|
||||||
|
"denoise_window": 3,
|
||||||
|
"target_rms": 0.06,
|
||||||
|
"trim_threshold_db": -45.0,
|
||||||
|
"trim_padding_ms": 50.0,
|
||||||
|
"frame_ms": 48.0,
|
||||||
|
"hop_ms": 10.0,
|
||||||
|
"fmin_hz": 70.0,
|
||||||
|
"fmax_hz": 1000.0,
|
||||||
|
"yin_threshold": 0.12,
|
||||||
|
"yin_max_cmndf": 0.55,
|
||||||
|
"voicing_conf": 0.5,
|
||||||
|
"voicing_db_below_peak": -45.0,
|
||||||
|
"median_filter_frames": 7,
|
||||||
|
"octave_fold_low": 9.0,
|
||||||
|
"octave_fold_high": 15.0,
|
||||||
|
"split_semitones": 0.8,
|
||||||
|
"min_note_ms": 70.0,
|
||||||
|
"bridge_gap_ms": 60.0,
|
||||||
|
"merge_semitones": 0.5,
|
||||||
|
"repeat_merge_semitones": 0.35,
|
||||||
|
"max_notes": 600,
|
||||||
|
"interval_clip": 12.0,
|
||||||
|
"contour_jump": 0.75,
|
||||||
|
"candidates_min": 40,
|
||||||
|
"candidates_per_sqrt": 7.0,
|
||||||
|
"candidate_score_floor": 0.1,
|
||||||
|
"full_scan_below_songs": 60,
|
||||||
|
"contour_variants_max": 40,
|
||||||
|
"dtw_pitch_free_band": 0.3,
|
||||||
|
"dtw_pitch_cap": 10.0,
|
||||||
|
"dtw_dur_cap": 2.5,
|
||||||
|
"dtw_pitch_weight": 1.0,
|
||||||
|
"dtw_dur_weight": 0.7,
|
||||||
|
"transpose_range": 24,
|
||||||
|
"transpose_span": 2,
|
||||||
|
"transpose_candidates": 8,
|
||||||
|
"dtw_score_lambda": 0.6,
|
||||||
|
"dtw_max_cells": 4000000,
|
||||||
|
"w_dtw": 0.7,
|
||||||
|
"w_index": 0.3,
|
||||||
|
"top_k": 10
|
||||||
|
},
|
||||||
|
"top1": 0.7829457364341085
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,558 @@
|
|||||||
|
"""Tkinter 桌面客户端:复用 Web 后端提供的 REST 接口。
|
||||||
|
|
||||||
|
与 Web 版功能对齐:录音/选文件检索、识别旋律可视化、Top-K 结果、DTW 对齐图、
|
||||||
|
命中片段回放、检索历史。设计上刻意**不引入 matplotlib**——音高轮廓与对齐图
|
||||||
|
都直接画在 ``tk.Canvas`` 上,因此桌面端只依赖标准库(+ 可选的 sounddevice 录音)。
|
||||||
|
|
||||||
|
用法::
|
||||||
|
|
||||||
|
python run_desktop.py # 默认连接 http://127.0.0.1:8700
|
||||||
|
python run_desktop.py --url http://127.0.0.1:8800
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import queue
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
import wave
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
from tkinter import filedialog, messagebox, ttk
|
||||||
|
|
||||||
|
try: # 可选:直接录音
|
||||||
|
import sounddevice as sd # type: ignore
|
||||||
|
|
||||||
|
HAS_SOUNDDEVICE = True
|
||||||
|
except Exception: # pragma: no cover - 环境相关
|
||||||
|
sd = None
|
||||||
|
HAS_SOUNDDEVICE = False
|
||||||
|
|
||||||
|
try: # Windows 下用标准库播放 WAV
|
||||||
|
import winsound # type: ignore
|
||||||
|
|
||||||
|
HAS_WINSOUND = True
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
winsound = None
|
||||||
|
HAS_WINSOUND = False
|
||||||
|
|
||||||
|
|
||||||
|
BG = "#141b29"
|
||||||
|
BG_PANEL = "#1c2436"
|
||||||
|
FG = "#e6ecf7"
|
||||||
|
FG_DIM = "#93a1bb"
|
||||||
|
ACCENT = "#4f8cff"
|
||||||
|
ACCENT2 = "#35d0a5"
|
||||||
|
GRID = "#243046"
|
||||||
|
|
||||||
|
|
||||||
|
def http_json(url: str, payload: dict | None = None, method: str = "GET") -> dict:
|
||||||
|
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url,
|
||||||
|
data=data,
|
||||||
|
method=method,
|
||||||
|
headers={"Content-Type": "application/json"} if data else {},
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||||
|
return json.loads(resp.read().decode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def http_bytes(url: str) -> bytes:
|
||||||
|
with urllib.request.urlopen(url, timeout=60) as resp:
|
||||||
|
return resp.read()
|
||||||
|
|
||||||
|
|
||||||
|
def encode_wav(samples, sr: int) -> bytes:
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with wave.open(buf, "wb") as wf:
|
||||||
|
wf.setnchannels(1)
|
||||||
|
wf.setsampwidth(2)
|
||||||
|
wf.setframerate(sr)
|
||||||
|
wf.writeframes((np.clip(samples, -1, 1) * 32767).astype("<i2").tobytes())
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
class QBHClient(tk.Tk):
|
||||||
|
"""桌面客户端主窗口。"""
|
||||||
|
|
||||||
|
def __init__(self, base_url: str = "http://127.0.0.1:8700"):
|
||||||
|
super().__init__()
|
||||||
|
self.base_url = base_url.rstrip("/")
|
||||||
|
self.title("基于旋律的音乐哼唱检索系统 —— 桌面客户端")
|
||||||
|
self.geometry("1180x780")
|
||||||
|
self.configure(bg=BG)
|
||||||
|
self.minsize(980, 640)
|
||||||
|
|
||||||
|
self.recording = False
|
||||||
|
self.last_result: dict[str, Any] | None = None
|
||||||
|
self.result_queue: queue.Queue = queue.Queue()
|
||||||
|
self._temp_audio: Path | None = None
|
||||||
|
|
||||||
|
self._build_style()
|
||||||
|
self._build_ui()
|
||||||
|
self.after(200, self.refresh_status)
|
||||||
|
self.after(300, self.refresh_history)
|
||||||
|
|
||||||
|
# ---------------- 界面 ---------------- #
|
||||||
|
def _build_style(self) -> None:
|
||||||
|
style = ttk.Style(self)
|
||||||
|
try:
|
||||||
|
style.theme_use("clam")
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
style.configure(".", background=BG, foreground=FG, fieldbackground=BG_PANEL)
|
||||||
|
style.configure("TFrame", background=BG)
|
||||||
|
style.configure("Panel.TFrame", background=BG_PANEL)
|
||||||
|
style.configure("TLabel", background=BG, foreground=FG)
|
||||||
|
style.configure("Dim.TLabel", background=BG_PANEL, foreground=FG_DIM)
|
||||||
|
style.configure("Title.TLabel", background=BG_PANEL, foreground=FG, font=("Segoe UI", 11, "bold"))
|
||||||
|
style.configure("TButton", background="#26314a", foreground=FG, borderwidth=0, padding=7)
|
||||||
|
style.map("TButton", background=[("active", "#33415f")])
|
||||||
|
style.configure("Primary.TButton", background=ACCENT, foreground="#ffffff")
|
||||||
|
style.map("Primary.TButton", background=[("active", "#5f9aff")])
|
||||||
|
style.configure("Treeview", background=BG_PANEL, fieldbackground=BG_PANEL,
|
||||||
|
foreground=FG, rowheight=24, borderwidth=0)
|
||||||
|
style.configure("Treeview.Heading", background="#232d42", foreground=FG_DIM, borderwidth=0)
|
||||||
|
style.map("Treeview", background=[("selected", "#2b3f63")])
|
||||||
|
|
||||||
|
def _build_ui(self) -> None:
|
||||||
|
header = tk.Frame(self, bg="#1a2334", height=54)
|
||||||
|
header.pack(fill="x")
|
||||||
|
tk.Label(header, text="♪", bg="#1a2334", fg=ACCENT2,
|
||||||
|
font=("Segoe UI", 18, "bold")).pack(side="left", padx=(18, 8))
|
||||||
|
tk.Label(header, text="基于旋律的音乐哼唱检索系统", bg="#1a2334", fg=FG,
|
||||||
|
font=("Segoe UI", 13, "bold")).pack(side="left")
|
||||||
|
self.status_label = tk.Label(header, text="连接中…", bg="#1a2334", fg=FG_DIM,
|
||||||
|
font=("Segoe UI", 9))
|
||||||
|
self.status_label.pack(side="right", padx=18)
|
||||||
|
|
||||||
|
body = tk.Frame(self, bg=BG)
|
||||||
|
body.pack(fill="both", expand=True, padx=14, pady=14)
|
||||||
|
|
||||||
|
# ---- 左侧操作区 ----
|
||||||
|
left = tk.Frame(body, bg=BG_PANEL, width=280)
|
||||||
|
left.pack(side="left", fill="y", padx=(0, 12))
|
||||||
|
left.pack_propagate(False)
|
||||||
|
|
||||||
|
tk.Label(left, text="输入查询", bg=BG_PANEL, fg=FG,
|
||||||
|
font=("Segoe UI", 11, "bold")).pack(anchor="w", padx=14, pady=(14, 8))
|
||||||
|
|
||||||
|
self.record_btn = ttk.Button(
|
||||||
|
left, text="🎤 开始录音", style="Primary.TButton", command=self.toggle_record
|
||||||
|
)
|
||||||
|
self.record_btn.pack(fill="x", padx=14)
|
||||||
|
hint = "录音后自动检索" if HAS_SOUNDDEVICE else "未安装 sounddevice,请改用文件"
|
||||||
|
tk.Label(left, text=hint, bg=BG_PANEL, fg=FG_DIM, font=("Segoe UI", 8),
|
||||||
|
wraplength=240, justify="left").pack(anchor="w", padx=14, pady=(4, 12))
|
||||||
|
|
||||||
|
ttk.Button(left, text="📁 选择音频文件", command=self.pick_file).pack(fill="x", padx=14)
|
||||||
|
|
||||||
|
tk.Label(left, text="随机示范查询", bg=BG_PANEL, fg=FG_DIM,
|
||||||
|
font=("Segoe UI", 9)).pack(anchor="w", padx=14, pady=(16, 4))
|
||||||
|
self.difficulty = tk.StringVar(value="normal")
|
||||||
|
row = tk.Frame(left, bg=BG_PANEL)
|
||||||
|
row.pack(fill="x", padx=14)
|
||||||
|
for value, label in (("easy", "简单"), ("normal", "中等"), ("hard", "困难")):
|
||||||
|
tk.Radiobutton(row, text=label, value=value, variable=self.difficulty,
|
||||||
|
bg=BG_PANEL, fg=FG, selectcolor="#26314a",
|
||||||
|
activebackground=BG_PANEL, activeforeground=FG,
|
||||||
|
highlightthickness=0, font=("Segoe UI", 9)).pack(side="left")
|
||||||
|
ttk.Button(left, text="🎲 生成机器哼唱并检索", command=self.run_demo).pack(
|
||||||
|
fill="x", padx=14, pady=(8, 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
tk.Label(left, text="返回条数", bg=BG_PANEL, fg=FG_DIM,
|
||||||
|
font=("Segoe UI", 9)).pack(anchor="w", padx=14, pady=(16, 2))
|
||||||
|
self.top_k = tk.Spinbox(left, from_=1, to=50, width=8, bg="#131a28", fg=FG,
|
||||||
|
insertbackground=FG, relief="flat")
|
||||||
|
self.top_k.delete(0, "end")
|
||||||
|
self.top_k.insert(0, "10")
|
||||||
|
self.top_k.pack(anchor="w", padx=14)
|
||||||
|
|
||||||
|
tk.Label(left, text="命中片段回放", bg=BG_PANEL, fg=FG_DIM,
|
||||||
|
font=("Segoe UI", 9)).pack(anchor="w", padx=14, pady=(16, 2))
|
||||||
|
ttk.Button(left, text="▶ 播放选中结果", command=self.play_selected).pack(fill="x", padx=14)
|
||||||
|
|
||||||
|
# ---- 右侧结果区 ----
|
||||||
|
right = tk.Frame(body, bg=BG)
|
||||||
|
right.pack(side="left", fill="both", expand=True)
|
||||||
|
|
||||||
|
self.notebook = ttk.Notebook(right)
|
||||||
|
self.notebook.pack(fill="both", expand=True)
|
||||||
|
|
||||||
|
# 结果页
|
||||||
|
result_tab = tk.Frame(self.notebook, bg=BG)
|
||||||
|
self.notebook.add(result_tab, text=" 检索结果 ")
|
||||||
|
|
||||||
|
self.banner = tk.Label(result_tab, text="", bg=BG_PANEL, fg=FG, anchor="w",
|
||||||
|
justify="left", font=("Segoe UI", 9), padx=10, pady=6)
|
||||||
|
self.banner.pack(fill="x", pady=(0, 8))
|
||||||
|
|
||||||
|
columns = ("rank", "title", "origin", "score", "dtw", "idx", "shift", "segment")
|
||||||
|
self.tree = ttk.Treeview(result_tab, columns=columns, show="headings", height=9)
|
||||||
|
headings = {
|
||||||
|
"rank": "#", "title": "曲目", "origin": "来源", "score": "总分",
|
||||||
|
"dtw": "DTW", "idx": "索引", "shift": "移调", "segment": "命中片段",
|
||||||
|
}
|
||||||
|
widths = {"rank": 34, "title": 190, "origin": 130, "score": 60,
|
||||||
|
"dtw": 60, "idx": 60, "shift": 56, "segment": 120}
|
||||||
|
for key in columns:
|
||||||
|
self.tree.heading(key, text=headings[key])
|
||||||
|
self.tree.column(key, width=widths[key], anchor="w" if key in ("title", "origin") else "center")
|
||||||
|
self.tree.pack(fill="x")
|
||||||
|
self.tree.bind("<Double-1>", lambda _e: self.play_selected())
|
||||||
|
|
||||||
|
charts = tk.Frame(result_tab, bg=BG)
|
||||||
|
charts.pack(fill="both", expand=True, pady=(10, 0))
|
||||||
|
tk.Label(charts, text="识别到的旋律", bg=BG, fg=FG_DIM,
|
||||||
|
font=("Segoe UI", 9)).grid(row=0, column=0, sticky="w")
|
||||||
|
self.contour_canvas = tk.Canvas(charts, bg="#101725", height=150, highlightthickness=0)
|
||||||
|
self.contour_canvas.grid(row=1, column=0, sticky="nsew", pady=(2, 8))
|
||||||
|
tk.Label(charts, text="DTW 对齐(左=哼唱查询,右=曲库片段)", bg=BG, fg=FG_DIM,
|
||||||
|
font=("Segoe UI", 9)).grid(row=2, column=0, sticky="w")
|
||||||
|
self.align_canvas = tk.Canvas(charts, bg="#101725", height=230, highlightthickness=0)
|
||||||
|
self.align_canvas.grid(row=3, column=0, sticky="nsew")
|
||||||
|
charts.columnconfigure(0, weight=1)
|
||||||
|
charts.rowconfigure(1, weight=1)
|
||||||
|
charts.rowconfigure(3, weight=2)
|
||||||
|
|
||||||
|
# 历史页
|
||||||
|
history_tab = tk.Frame(self.notebook, bg=BG)
|
||||||
|
self.notebook.add(history_tab, text=" 检索历史 ")
|
||||||
|
hist_cols = ("time", "source", "notes", "top", "score", "ms")
|
||||||
|
self.history_tree = ttk.Treeview(history_tab, columns=hist_cols, show="headings")
|
||||||
|
for key, text, width in (
|
||||||
|
("time", "时间", 150), ("source", "来源", 70), ("notes", "查询音符", 80),
|
||||||
|
("top", "最佳匹配", 220), ("score", "分数", 70), ("ms", "耗时(ms)", 90),
|
||||||
|
):
|
||||||
|
self.history_tree.heading(key, text=text)
|
||||||
|
self.history_tree.column(key, width=width, anchor="w" if key == "top" else "center")
|
||||||
|
self.history_tree.pack(fill="both", expand=True)
|
||||||
|
ttk.Button(history_tab, text="刷新历史", command=self.refresh_history).pack(
|
||||||
|
anchor="e", pady=8, padx=4
|
||||||
|
)
|
||||||
|
|
||||||
|
self.after(120, self._drain_queue)
|
||||||
|
|
||||||
|
# ---------------- 网络 ---------------- #
|
||||||
|
def refresh_status(self) -> None:
|
||||||
|
try:
|
||||||
|
data = http_json(f"{self.base_url}/api/status")
|
||||||
|
self.status_label.config(
|
||||||
|
text=f"曲库 {data['n_songs']} 首 · 索引 {data['n_grams']} 个 n-gram · {self.base_url}"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self.status_label.config(text=f"无法连接后端:{exc}")
|
||||||
|
|
||||||
|
def refresh_history(self) -> None:
|
||||||
|
try:
|
||||||
|
data = http_json(f"{self.base_url}/api/history?limit=60")
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
for item in self.history_tree.get_children():
|
||||||
|
self.history_tree.delete(item)
|
||||||
|
for row in data.get("history", []):
|
||||||
|
self.history_tree.insert("", "end", values=(
|
||||||
|
row.get("created_at", ""), row.get("source", ""), row.get("query_notes", 0),
|
||||||
|
row.get("top_title") or row.get("top_song", ""),
|
||||||
|
f"{float(row.get('top_score') or 0):.3f}",
|
||||||
|
f"{float(row.get('elapsed_ms') or 0):.0f}",
|
||||||
|
))
|
||||||
|
|
||||||
|
def _drain_queue(self) -> None:
|
||||||
|
"""在 Tk 主线程里消费后台线程回传的结果。
|
||||||
|
|
||||||
|
Tk 不是线程安全的,所有控件操作都必须回到主线程执行,因此后台线程
|
||||||
|
只往队列里投递事件。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
kind, payload = self.result_queue.get_nowait()
|
||||||
|
if kind == "result":
|
||||||
|
self.render_result(payload)
|
||||||
|
elif kind == "error":
|
||||||
|
messagebox.showerror("错误", str(payload))
|
||||||
|
elif kind == "status":
|
||||||
|
self.status_label.config(text=str(payload))
|
||||||
|
elif kind == "refresh_history":
|
||||||
|
self.refresh_history()
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
self.after(120, self._drain_queue)
|
||||||
|
|
||||||
|
# ---------------- 查询 ---------------- #
|
||||||
|
def _post_search(self, wav: bytes, source: str) -> None:
|
||||||
|
self.result_queue.put(("status", "识别与检索中…"))
|
||||||
|
# Tk 变量必须在主线程读取,后台线程只做纯网络/计算
|
||||||
|
top_k = int(self.top_k.get() or 10)
|
||||||
|
|
||||||
|
def worker() -> None:
|
||||||
|
try:
|
||||||
|
payload = {
|
||||||
|
"audio_base64": base64.b64encode(wav).decode("ascii"),
|
||||||
|
"top_k": top_k,
|
||||||
|
"source": source,
|
||||||
|
}
|
||||||
|
data = http_json(f"{self.base_url}/api/search", payload, method="POST")
|
||||||
|
self.result_queue.put(("result", data))
|
||||||
|
self.result_queue.put(("refresh_history", None))
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
body = exc.read().decode("utf-8", errors="replace")
|
||||||
|
try:
|
||||||
|
detail = json.loads(body).get("detail", body)
|
||||||
|
except Exception:
|
||||||
|
detail = body
|
||||||
|
self.result_queue.put(("error", f"检索失败:{detail}"))
|
||||||
|
except Exception as exc:
|
||||||
|
self.result_queue.put(("error", f"检索失败:{exc}"))
|
||||||
|
|
||||||
|
threading.Thread(target=worker, daemon=True).start()
|
||||||
|
|
||||||
|
def toggle_record(self) -> None:
|
||||||
|
if not HAS_SOUNDDEVICE:
|
||||||
|
messagebox.showinfo("提示", "未安装 sounddevice,请改用「选择音频文件」。")
|
||||||
|
return
|
||||||
|
if not self.recording:
|
||||||
|
self.recording = True
|
||||||
|
self.record_btn.config(text="⏹ 停止录音并检索")
|
||||||
|
self.result_queue.put(("status", "录音中…再次点击按钮停止"))
|
||||||
|
self._record_started = __import__("time").perf_counter()
|
||||||
|
self._record_buffer = []
|
||||||
|
|
||||||
|
def callback(indata, _frames, _time, status): # noqa: ANN001
|
||||||
|
self._record_buffer.append(indata.copy())
|
||||||
|
|
||||||
|
self._stream = sd.InputStream(samplerate=16000, channels=1, dtype="float32",
|
||||||
|
callback=callback)
|
||||||
|
self._stream.start()
|
||||||
|
else:
|
||||||
|
self.recording = False
|
||||||
|
self.record_btn.config(text="🎤 开始录音")
|
||||||
|
try:
|
||||||
|
self._stream.stop()
|
||||||
|
self._stream.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
if not self._record_buffer:
|
||||||
|
self.result_queue.put(("error", "没有录到音频"))
|
||||||
|
return
|
||||||
|
audio = np.concatenate(self._record_buffer, axis=0).reshape(-1)
|
||||||
|
self._post_search(encode_wav(audio, 16000), "mic")
|
||||||
|
|
||||||
|
def pick_file(self) -> None:
|
||||||
|
path = filedialog.askopenfilename(
|
||||||
|
title="选择音频文件",
|
||||||
|
filetypes=[("音频文件", "*.wav *.mp3 *.flac *.ogg *.m4a"), ("所有文件", "*.*")],
|
||||||
|
)
|
||||||
|
if not path:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
raw = Path(path).read_bytes()
|
||||||
|
except OSError as exc:
|
||||||
|
messagebox.showerror("错误", f"读取失败:{exc}")
|
||||||
|
return
|
||||||
|
self._post_search(raw, "upload")
|
||||||
|
|
||||||
|
def run_demo(self) -> None:
|
||||||
|
self.result_queue.put(("status", "生成示范查询中…"))
|
||||||
|
difficulty = self.difficulty.get()
|
||||||
|
top_k = int(self.top_k.get() or 10)
|
||||||
|
|
||||||
|
def worker() -> None:
|
||||||
|
try:
|
||||||
|
data = http_json(
|
||||||
|
f"{self.base_url}/api/demo",
|
||||||
|
{"difficulty": difficulty, "top_k": top_k},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
self.result_queue.put(("result", data))
|
||||||
|
self.result_queue.put(("refresh_history", None))
|
||||||
|
except Exception as exc:
|
||||||
|
self.result_queue.put(("error", f"示范查询失败:{exc}"))
|
||||||
|
|
||||||
|
threading.Thread(target=worker, daemon=True).start()
|
||||||
|
|
||||||
|
# ---------------- 渲染 ---------------- #
|
||||||
|
def render_result(self, data: dict[str, Any]) -> None:
|
||||||
|
self.last_result = data
|
||||||
|
for item in self.tree.get_children():
|
||||||
|
self.tree.delete(item)
|
||||||
|
|
||||||
|
demo = data.get("demo")
|
||||||
|
if demo:
|
||||||
|
hit = demo.get("rank") == 1
|
||||||
|
mark = "✅ 第 1 名命中" if hit else (
|
||||||
|
f"⚠️ 命中排在第 {demo['rank']} 名" if demo.get("rank") else "❌ 未进入 Top-K"
|
||||||
|
)
|
||||||
|
self.banner.config(
|
||||||
|
text=(f"示范查询:{demo['answer_title']} · 移调 {demo['shift']:+.0f} 半音 · "
|
||||||
|
f"速度 {demo['tempo']}× · 信噪比 {demo['snr_db']} dB · 片段 {demo['n_notes']} 音\n{mark}"),
|
||||||
|
fg=ACCENT2 if hit else "#ffb454",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.banner.config(text="上传/录音查询结果", fg=FG_DIM)
|
||||||
|
|
||||||
|
for idx, hit in enumerate(data.get("hits", []), start=1):
|
||||||
|
self.tree.insert("", "end", values=(
|
||||||
|
idx, hit.get("title", ""), hit.get("origin", ""),
|
||||||
|
f"{hit.get('score', 0):.3f}", f"{hit.get('dtw_sim', 0):.3f}",
|
||||||
|
f"{hit.get('index_sim', 0):.3f}", f"{hit.get('shift', 0):+.0f}",
|
||||||
|
f"{hit.get('target_start_s', 0):.1f}–{hit.get('target_end_s', 0):.1f}s",
|
||||||
|
))
|
||||||
|
|
||||||
|
query = data.get("query") or {}
|
||||||
|
self.draw_contour(query)
|
||||||
|
if data.get("hits"):
|
||||||
|
self.draw_alignment(query, data["hits"][0])
|
||||||
|
self.status_label.config(
|
||||||
|
text=(f"候选 {data.get('n_candidates')}/{data.get('n_songs')} 首 · "
|
||||||
|
f"检索 {data.get('elapsed_ms', 0):.0f} ms · {self.base_url}")
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------------- 绘图 ---------------- #
|
||||||
|
def draw_contour(self, query: dict[str, Any]) -> None:
|
||||||
|
canvas = self.contour_canvas
|
||||||
|
canvas.delete("all")
|
||||||
|
midis = query.get("midis") or []
|
||||||
|
starts = query.get("starts") or []
|
||||||
|
durs = query.get("durs") or []
|
||||||
|
w = max(canvas.winfo_width(), 400)
|
||||||
|
h = max(canvas.winfo_height(), 120)
|
||||||
|
if not midis:
|
||||||
|
canvas.create_text(12, h / 2, anchor="w", fill=FG_DIM,
|
||||||
|
text="未识别到音符", font=("Segoe UI", 9))
|
||||||
|
return
|
||||||
|
|
||||||
|
pad_l, pad_r, pad_t, pad_b = 34, 12, 12, 16
|
||||||
|
lo, hi = min(midis) - 1, max(midis) + 1
|
||||||
|
span = max(hi - lo, 1)
|
||||||
|
total = max(starts[-1] + durs[-1], 1e-3)
|
||||||
|
|
||||||
|
def y_of(v: float) -> float:
|
||||||
|
return h - pad_b - (v - lo) / span * (h - pad_t - pad_b)
|
||||||
|
|
||||||
|
def x_of(t: float) -> float:
|
||||||
|
return pad_l + t / total * (w - pad_l - pad_r)
|
||||||
|
|
||||||
|
for v in range(int(lo), int(hi) + 1, 2):
|
||||||
|
canvas.create_line(pad_l, y_of(v), w - pad_r, y_of(v), fill=GRID)
|
||||||
|
canvas.create_text(4, y_of(v), anchor="w", fill="#5b6b88",
|
||||||
|
text=str(v), font=("Consolas", 8))
|
||||||
|
|
||||||
|
for i, pitch in enumerate(midis):
|
||||||
|
x0, x1 = x_of(starts[i]), x_of(starts[i] + durs[i])
|
||||||
|
yy = y_of(pitch)
|
||||||
|
canvas.create_rectangle(x0, yy - 3, max(x1 - 1.5, x0 + 2), yy + 3,
|
||||||
|
fill=ACCENT, outline="")
|
||||||
|
if i:
|
||||||
|
canvas.create_line(x_of(starts[i - 1] + durs[i - 1]), y_of(midis[i - 1]),
|
||||||
|
x0, yy, fill="#3f6bb5")
|
||||||
|
|
||||||
|
def draw_alignment(self, query: dict[str, Any], hit: dict[str, Any]) -> None:
|
||||||
|
canvas = self.align_canvas
|
||||||
|
canvas.delete("all")
|
||||||
|
q = query.get("midis") or []
|
||||||
|
t = hit.get("target_midis") or []
|
||||||
|
path = hit.get("path") or []
|
||||||
|
shift = hit.get("shift", 0) or 0
|
||||||
|
w = max(canvas.winfo_width(), 500)
|
||||||
|
h = max(canvas.winfo_height(), 200)
|
||||||
|
if not q or not t:
|
||||||
|
canvas.create_text(12, h / 2, anchor="w", fill=FG_DIM,
|
||||||
|
text="没有可用的对齐数据", font=("Segoe UI", 9))
|
||||||
|
return
|
||||||
|
|
||||||
|
q_adj = [v + shift for v in q]
|
||||||
|
lo, hi = min(q_adj + t) - 1, max(q_adj + t) + 1
|
||||||
|
span = max(hi - lo, 1)
|
||||||
|
pad_t, pad_b = 20, 26
|
||||||
|
|
||||||
|
def y_of(v: float) -> float:
|
||||||
|
return h - pad_b - (v - lo) / span * (h - pad_t - pad_b)
|
||||||
|
|
||||||
|
left_x, left_w = 26, w * 0.34
|
||||||
|
right_x, right_w = w * 0.62, w * 0.34
|
||||||
|
|
||||||
|
def xq(i: int) -> float:
|
||||||
|
return left_x + (i / (len(q) - 1) * left_w if len(q) > 1 else 0)
|
||||||
|
|
||||||
|
def xt(j: int) -> float:
|
||||||
|
return right_x + (j / (len(t) - 1) * right_w if len(t) > 1 else 0)
|
||||||
|
|
||||||
|
step = max(1, len(path) // 200)
|
||||||
|
for k in range(0, len(path), step):
|
||||||
|
i, j = path[k][0], path[k][1]
|
||||||
|
if i >= len(q) or j >= len(t):
|
||||||
|
continue
|
||||||
|
err = abs(q_adj[i] - t[j])
|
||||||
|
color = ACCENT2 if err < 0.6 else ("#ffb454" if err < 1.5 else "#ff6b6b")
|
||||||
|
canvas.create_line(xq(i), y_of(q_adj[i]), xt(j), y_of(t[j]), fill=color)
|
||||||
|
|
||||||
|
for i, v in enumerate(q_adj):
|
||||||
|
canvas.create_oval(xq(i) - 3, y_of(v) - 3, xq(i) + 3, y_of(v) + 3,
|
||||||
|
fill=ACCENT, outline="")
|
||||||
|
for j, v in enumerate(t):
|
||||||
|
canvas.create_oval(xt(j) - 3, y_of(v) - 3, xt(j) + 3, y_of(v) + 3,
|
||||||
|
fill=ACCENT2, outline="")
|
||||||
|
|
||||||
|
s = hit.get("target_note_start", 0)
|
||||||
|
e = hit.get("target_note_end", len(t) - 1)
|
||||||
|
canvas.create_line(xt(s), h - pad_b + 8, xt(e), h - pad_b + 8, fill=ACCENT2, width=2)
|
||||||
|
canvas.create_text(left_x, 8, anchor="w", fill=FG_DIM,
|
||||||
|
text=f"哼唱查询({len(q)} 音)", font=("Segoe UI", 9))
|
||||||
|
canvas.create_text(right_x, 8, anchor="w", fill=FG_DIM,
|
||||||
|
text=f"曲库片段(第 {s + 1}–{e + 1} 音)", font=("Segoe UI", 9))
|
||||||
|
|
||||||
|
# ---------------- 播放 ---------------- #
|
||||||
|
def play_selected(self) -> None:
|
||||||
|
if not self.last_result or not self.last_result.get("hits"):
|
||||||
|
return
|
||||||
|
selection = self.tree.selection()
|
||||||
|
index = self.tree.index(selection[0]) if selection else 0
|
||||||
|
hit = self.last_result["hits"][index]
|
||||||
|
try:
|
||||||
|
blob = http_bytes(f"{self.base_url}/api/songs/{hit['song_id']}/audio")
|
||||||
|
except Exception as exc:
|
||||||
|
messagebox.showerror("错误", f"无法获取音频:{exc}")
|
||||||
|
return
|
||||||
|
tmp = Path(tempfile.gettempdir()) / f"qbh_{hit['song_id']}.wav"
|
||||||
|
tmp.write_bytes(blob)
|
||||||
|
self._temp_audio = tmp
|
||||||
|
if HAS_WINSOUND:
|
||||||
|
winsound.PlaySound(str(tmp), winsound.SND_FILENAME | winsound.SND_ASYNC)
|
||||||
|
self.result_queue.put((
|
||||||
|
"status",
|
||||||
|
f"正在播放 {hit.get('title')} 的命中片段 "
|
||||||
|
f"{hit.get('target_start_s', 0):.1f}–{hit.get('target_end_s', 0):.1f}s",
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
messagebox.showinfo("提示", f"音频已保存到 {tmp}(当前平台不支持直接播放)")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="QBH 桌面客户端")
|
||||||
|
parser.add_argument("--url", default="http://127.0.0.1:8700", help="后端地址")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
app = QBHClient(args.url)
|
||||||
|
app.mainloop()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main(sys.argv[1:]))
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
## 评测结果(合成哼唱查询 → 完整流水线)
|
||||||
|
|
||||||
|
- 曲库:**43 首**(27 首真实 MIDI + 16 首内置曲谱)
|
||||||
|
- 查询:每首 3 条,随机种子 20260908,共 129 条/难度
|
||||||
|
- 查询扰动:移调 ±5 半音(12% 概率再 ±12)、速度 0.82–1.28×、逐音抖动 σ≈0.35 半音、丢音/劈音/插音、哼唱音色渲染、按 SNR 加噪
|
||||||
|
|
||||||
|
| 难度 | Top-1 | Top-3 | Top-5 | Top-10 | MRR | 粗召回率 | 延迟 p50 | 延迟 p95 |
|
||||||
|
|---|---:|---:|---:|---:|---:|---:|---:|---:|
|
||||||
|
| easy | 89.9% | 95.3% | 96.1% | 96.9% | 0.928 | 100.0% | 93 ms | 137 ms |
|
||||||
|
| normal | 76.0% | 86.0% | 88.4% | 93.0% | 0.814 | 99.2% | 75 ms | 112 ms |
|
||||||
|
| hard | 62.0% | 70.5% | 74.4% | 82.2% | 0.676 | 96.9% | 80 ms | 117 ms |
|
||||||
|
|
||||||
|
> 说明:查询由合成器生成,曲库中 27 首为真实 MIDI、16 首为内置曲谱,因此这组数字是**自洽基准**而非绝对泛化能力。噪声鲁棒性见 `docs/评测报告.md` 的 SNR 消融章节。
|
||||||
+200
@@ -0,0 +1,200 @@
|
|||||||
|
# 界面说明
|
||||||
|
|
||||||
|
系统提供两种前端:**Web 单页应用**(主)与 **Tkinter 桌面客户端**(附)。
|
||||||
|
两者共用同一套 REST 接口,功能对齐。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、Web 界面
|
||||||
|
|
||||||
|
启动:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python run.py # 自动打开 http://127.0.0.1:8700
|
||||||
|
python run.py --port 8800 --no-browser
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.1 布局
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ ♪ 基于旋律的音乐哼唱检索系统 曲库 43 首 · 索引 1722 个 n-gram │
|
||||||
|
├────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ 哼唱检索 │ 曲库管理 │ 检索历史 │ 评测与实验 │
|
||||||
|
├──────────────────────┬─────────────────────────────────────────────┤
|
||||||
|
│ 输入查询 │ 检索结果 候选 41/43 首 · 检索 76 ms │
|
||||||
|
│ ┌──────────────────┐ │ ┌─────────────────────────────────────────┐ │
|
||||||
|
│ │ 🎤 开始录音 │ │ │ 示范查询:奇异恩典 · +4 半音 · 18 dB │ │
|
||||||
|
│ └──────────────────┘ │ │ ✅ 第 1 名命中 │ │
|
||||||
|
│ 或 │ └─────────────────────────────────────────┘ │
|
||||||
|
│ ┌──────────────────┐ │ 1 奇异恩典 ▓▓▓▓▓▓▓▓░░ 0.556 ▶ │
|
||||||
|
│ │ 📁 选择音频文件 │ │ 2 五声音阶旋律#6 ▓▓▓▓▓▓▓░░░ 0.504 ▶ │
|
||||||
|
│ └──────────────────┘ │ 3 五声音阶旋律#5 ▓▓▓▓▓▓░░░░ 0.477 ▶ │
|
||||||
|
│ 或 │ ... │
|
||||||
|
│ 随机示范查询 [中等] │ │
|
||||||
|
│ ┌──────────────────┐ │ ── DTW 对齐 ────────────────────────────── │
|
||||||
|
│ │ 🎲 生成机器哼唱 │ │ 哼唱查询(10音) 曲库片段(第11–22音) │
|
||||||
|
│ └──────────────────┘ │ ●───────●───────────● │
|
||||||
|
│ 返回条数 [10] │ ●────●──────────● │
|
||||||
|
│ │ (连线颜色表示音高偏差) │
|
||||||
|
│ 识别到的旋律 │ │
|
||||||
|
│ 73·0.34s 71·2.89s … │ │
|
||||||
|
│ ┌──────────────────┐ │ │
|
||||||
|
│ │ 音高阶梯图 │ │ │
|
||||||
|
│ └──────────────────┘ │ │
|
||||||
|
└──────────────────────┴─────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 三种查询方式
|
||||||
|
|
||||||
|
| 方式 | 操作 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| **录音** | 点「🎤 开始录音」→ 哼唱 → 再点一次停止 | 浏览器 `MediaRecorder` 采集,客户端用 `OfflineAudioContext` 重采样到 16 kHz 并编码为 WAV 后上传 |
|
||||||
|
| **文件** | 点「📁 选择音频文件」 | 支持 WAV / MP3 / FLAC(MP3 等需装了 `soundfile`) |
|
||||||
|
| **示范** | 选难度 → 点「🎲 生成机器哼唱并检索」 | 服务端合成一条**答案已知**的哼唱查询,用于快速验证;结果区顶部会显示答案与命中排名,并提供查询音频回放 |
|
||||||
|
|
||||||
|
录音建议:安静环境、5–15 秒、用「啊」或「嗯」持续发声、尽量把音高唱准但不必
|
||||||
|
在意起调(系统对移调不变)。
|
||||||
|
|
||||||
|
### 1.3 结果区
|
||||||
|
|
||||||
|
每条结果包含:
|
||||||
|
|
||||||
|
- **排名与标题**;第 1 名有高亮边框;
|
||||||
|
- **副信息**:来源 · DTW 相似度 · 索引分 · 移调量 · 命中片段起止秒;
|
||||||
|
- **分数条**:融合总分(0–1);
|
||||||
|
- **▶ 按钮**:播放该曲目的示范音频,并自动跳到命中片段。
|
||||||
|
|
||||||
|
下方的 **DTW 对齐图**:左列为哼唱查询的音符,右列为命中曲目的片段,连线表示
|
||||||
|
对齐路径。连线颜色:绿色(音高偏差 < 0.6 半音)、橙色(< 1.5)、红色(更大)。
|
||||||
|
右下方的绿色横条标出命中的音符区间。
|
||||||
|
|
||||||
|
### 1.4 曲库管理
|
||||||
|
|
||||||
|
列出全部曲目(标题 / 来源 / 标签 / 音符数 / 时长),支持:
|
||||||
|
|
||||||
|
- **▶** 试听示范音频;
|
||||||
|
- **删除** 移除曲目并重建索引;
|
||||||
|
- **导入 MIDI / 音频**:MIDI 直接解析;音频会先跑一遍识别流水线再入库;
|
||||||
|
- **重建索引**:重新读取 `data/midi` 与内置曲谱。
|
||||||
|
|
||||||
|
### 1.5 检索历史
|
||||||
|
|
||||||
|
记录每次检索的时间、来源(mic / upload / demo)、查询音符数、最佳匹配与耗时。
|
||||||
|
**登录后只显示自己的记录**,未登录则显示全部。
|
||||||
|
|
||||||
|
### 1.6 账号
|
||||||
|
|
||||||
|
右上角「注册 / 登录」。密码用 `hashlib.scrypt` 加盐派生后存储,会话通过
|
||||||
|
HttpOnly Cookie 维持。
|
||||||
|
|
||||||
|
### 1.7 评测与实验
|
||||||
|
|
||||||
|
- **运行评测**:选难度与每首查询数,服务端跑完整流水线并返回 Top-K / MRR /
|
||||||
|
召回率 / 延迟;
|
||||||
|
- **最近一次评测**:指标卡片;
|
||||||
|
- **噪声鲁棒性实验**:显示 SNR 消融曲线(需先运行 `python cli.py noise`)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、桌面客户端
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python run_desktop.py # 连接 http://127.0.0.1:8700
|
||||||
|
python run_desktop.py --url http://127.0.0.1:8800
|
||||||
|
```
|
||||||
|
|
||||||
|
需要先启动后端(`python run.py --no-browser`)。
|
||||||
|
|
||||||
|
### 2.1 功能
|
||||||
|
|
||||||
|
- **录音**:装了 `sounddevice` 时可直接录音(16 kHz 单声道),否则按钮会提示改用文件;
|
||||||
|
- **选择文件**:读取任意 WAV/MP3 并上传检索;
|
||||||
|
- **随机示范查询**:简单 / 中等 / 困难三档;
|
||||||
|
- **结果表**:排名、标题、来源、总分、DTW、索引分、移调、命中片段;
|
||||||
|
- **识别旋律图**:`tk.Canvas` 自绘的音高阶梯图(**不依赖 matplotlib**);
|
||||||
|
- **DTW 对齐图**:左列查询、右列目标、连线按音高偏差着色;
|
||||||
|
- **播放选中结果**:双击或点「▶ 播放选中结果」,用标准库 `winsound` 异步播放
|
||||||
|
(非 Windows 平台会提示音频保存位置);
|
||||||
|
- **检索历史**:与 Web 端共享同一份记录。
|
||||||
|
|
||||||
|
### 2.2 依赖降级策略
|
||||||
|
|
||||||
|
| 缺失的包 | 影响 | 降级行为 |
|
||||||
|
|---|---|---|
|
||||||
|
| `sounddevice` | 无法直接录音 | 提示改用文件选择 |
|
||||||
|
| `winsound`(非 Windows) | 无法直接播放 | 提示音频已保存到临时目录 |
|
||||||
|
|
||||||
|
核心检索不依赖桌面端任何可选包——桌面端只是 REST 客户端。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、REST 接口
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| GET | `/api/status` | 曲库规模、n-gram 数、配置 |
|
||||||
|
| GET | `/api/songs` | 曲库列表 |
|
||||||
|
| GET | `/api/songs/{id}` | 单曲详情(含旋律特征与轮廓) |
|
||||||
|
| GET | `/api/songs/{id}/audio` | 示范音频(audio/wav) |
|
||||||
|
| POST | `/api/search` | 检索。`multipart/form-data`(字段 `file`、`top_k`、`source`)或 `application/json`(`audio_base64`) |
|
||||||
|
| POST | `/api/demo` | 合成示范查询并检索,返回 `demo.qid` 与 `demo.audio_url` |
|
||||||
|
| GET | `/api/query/{qid}/audio` | 重放示范查询音频 |
|
||||||
|
| POST | `/api/library/import` | 上传 MIDI/音频入库 |
|
||||||
|
| DELETE | `/api/library/{id}` | 删除曲目 |
|
||||||
|
| POST | `/api/library/rebuild` | 重建曲库与索引 |
|
||||||
|
| POST | `/api/auth/register` \| `/login` \| `/logout` | 账号 |
|
||||||
|
| GET | `/api/auth/me` | 当前登录状态 |
|
||||||
|
| GET / DELETE | `/api/history` | 查询 / 清空检索历史 |
|
||||||
|
| POST | `/api/eval/run` | 运行评测 |
|
||||||
|
| GET | `/api/eval/latest` | 最近评测报告 |
|
||||||
|
| GET | `/api/noise/latest` | 最近噪声实验报告 |
|
||||||
|
|
||||||
|
### 检索响应示例
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"elapsed_ms": 76.0,
|
||||||
|
"n_candidates": 41,
|
||||||
|
"n_songs": 43,
|
||||||
|
"query": { "n_notes": 10, "duration": 10.7, "midis": [...], "contour": "DDUD..." },
|
||||||
|
"track": { "voiced_ratio": 0.95, "duration": 10.8, "f0": [...], "times": [...] },
|
||||||
|
"hits": [
|
||||||
|
{
|
||||||
|
"song_id": "amazing_grace", "title": "奇异恩典",
|
||||||
|
"score": 0.556, "dtw_sim": 0.645, "index_sim": 0.200, "shift": -4.0,
|
||||||
|
"target_start_s": 7.9, "target_end_s": 19.3,
|
||||||
|
"target_note_start": 10, "target_note_end": 21,
|
||||||
|
"origin": "美国传统", "tags": ["传统", "大调"], "has_audio": true,
|
||||||
|
"path": [[0,10],[1,11], ...],
|
||||||
|
"target_midis": [...], "target_starts": [...], "target_durs": [...]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 错误约定
|
||||||
|
|
||||||
|
- `400`:音频无法解析、音符过少、参数非法;
|
||||||
|
- `401`:需要登录;
|
||||||
|
- `404`:曲目 / 示范查询不存在(示范查询缓存上限 50 条,过期后返回 404);
|
||||||
|
- `429`:已有评测在运行。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、常见问题
|
||||||
|
|
||||||
|
**Q:录音按钮点了没反应?**
|
||||||
|
浏览器需要麦克风权限,且 `http://127.0.0.1` 被视为安全上下文。若用其它主机名
|
||||||
|
访问,浏览器可能拒绝 `getUserMedia`,此时改用文件上传。
|
||||||
|
|
||||||
|
**Q:识别出的音符数比哼的少?**
|
||||||
|
这是设计行为——相邻同音高音符会被融合成一个(查询与曲库两侧一致处理),
|
||||||
|
过短音符也会被丢弃。见 `docs/设计文档.md` 的「重复音融合」。
|
||||||
|
|
||||||
|
**Q:为什么只哼一小段也能搜到?**
|
||||||
|
子序列 DTW 的起点开放,查询可以对齐曲库旋律的任意连续片段。
|
||||||
|
|
||||||
|
**Q:示范查询的答案是怎么来的?**
|
||||||
|
由服务端从曲库中取一段旋律、施加扰动并渲染成音频,因此答案天然已知,
|
||||||
|
命中排名会直接显示在结果区顶部。
|
||||||
+192
@@ -0,0 +1,192 @@
|
|||||||
|
# 设计文档
|
||||||
|
|
||||||
|
## 1. 问题定义
|
||||||
|
|
||||||
|
**哼唱检索(Query by Humming, QBH)**:用户用哼唱给出旋律片段,系统在曲库中找出
|
||||||
|
对应的曲目。与「以曲搜曲」不同,哼唱输入有三个固有困难:
|
||||||
|
|
||||||
|
1. **没有绝对音高**——用户起调是任意的,必须做到移调不变;
|
||||||
|
2. **没有绝对速度**——哼唱快慢与录音长度都不确定,必须做到速度不变;
|
||||||
|
3. **切分不完美**——人声没有明确的音符边界,颤音、滑音、气声都会干扰音符切分。
|
||||||
|
|
||||||
|
因此系统的核心设计目标是:**表示对移调/速度不变**,**匹配对切分误差鲁棒**。
|
||||||
|
|
||||||
|
## 2. 整体流水线
|
||||||
|
|
||||||
|
```
|
||||||
|
查询侧: 音频 → 预处理 → YIN → 音符切分 → 旋律表示 ┐
|
||||||
|
├→ 粗召回 → 精排 → 融合 → Top-K
|
||||||
|
曲库侧: 曲谱/MIDI → 旋律特征 → 倒排索引 ──────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. 各阶段设计
|
||||||
|
|
||||||
|
### 3.1 预处理 `qbh/audio.py`
|
||||||
|
|
||||||
|
重采样到 16 kHz → 滑动均值去噪(窗长 3)→ 四阶巴特沃斯带通 60–2000 Hz →
|
||||||
|
静音裁剪 → RMS 归一化。
|
||||||
|
|
||||||
|
- **为什么是 60–2000 Hz**:哼唱基频与主要谐波都在这个范围;低于 60 Hz 是桌面
|
||||||
|
震动与直流漂移,高于 2000 Hz 是齿音与房间噪声。
|
||||||
|
- **为什么用 `sosfiltfilt`**:零相位滤波,不会引入时延导致音符起始时刻偏移。
|
||||||
|
- 全部开关可关闭,用于噪声鲁棒性实验中的对照。
|
||||||
|
|
||||||
|
### 3.2 基频提取 `qbh/pitch.py`
|
||||||
|
|
||||||
|
**向量化 YIN**。YIN 的差函数为
|
||||||
|
|
||||||
|
```
|
||||||
|
d(τ) = Σ_{j=0}^{W-1} (x[j] − x[j+τ])²
|
||||||
|
= e1 + e2(τ) − 2·A(τ)
|
||||||
|
```
|
||||||
|
|
||||||
|
其中 `e1` 是积分窗内的固定能量、`e2(τ)` 是滑动窗能量、`A(τ)` 是窗与帧的互相关。
|
||||||
|
实现上:
|
||||||
|
|
||||||
|
- `e1` 用平方前缀和;
|
||||||
|
- `e2(τ)` 用平方前缀和作差;
|
||||||
|
- `A(τ)` 用 FFT 卷积(`rfft` 批量计算,`irfft` 还原),并取 `τ + W − 1` 位置。
|
||||||
|
|
||||||
|
这样整段音频的差函数矩阵一次算完,避免 Python 双层循环。
|
||||||
|
|
||||||
|
**选周期**:先求 CMNDF,再定位所有局部极小(两侧邻点都不小于自身),取其中
|
||||||
|
**最早的一个低于阈值者**;若没有低于阈值的谷,退化为范围内全局最小。
|
||||||
|
|
||||||
|
> 这里踩过一个坑:常见写法是「首次低于阈值后在其 ±3 邻域取最小」。但低基频的
|
||||||
|
> CMNDF 谷很宽,首个低于阈值的位置可能离谷底十几个采样点,导致系统性高估基频
|
||||||
|
> (110 Hz 实测偏高 0.91 半音)。改为「所有局部极小中取最早合格者」后误差降到
|
||||||
|
> 0.0002 半音。
|
||||||
|
|
||||||
|
**两级纠错**:
|
||||||
|
|
||||||
|
- **八度折叠**:若某帧与邻域中值的偏差落在 9–15 半音,折叠 ±12。只在偏差接近
|
||||||
|
一个八度时才动,避免改坏真实的九度大跳。
|
||||||
|
- **有声判定**:`置信度 ≥ 0.5` 且 `CMNDF ≤ 0.55` 且 `RMS > 峰值 − 45 dB`;
|
||||||
|
另外对绝对静音(峰值 RMS < 1e-5)直接全判为无声——全零信号的 CMNDF 恒为 0,
|
||||||
|
会被误判为满置信度。
|
||||||
|
|
||||||
|
### 3.3 音符切分 `qbh/notes.py`
|
||||||
|
|
||||||
|
1. 中值滤波(7 帧)平滑音高轨迹;
|
||||||
|
2. 按「与当前平台参考音高相差 > 0.8 半音」或「有声中断 > 60 ms」分段;
|
||||||
|
3. 合并音高接近(< 0.5 半音)且间隔很小的相邻段;
|
||||||
|
4. **重复音融合**(见下);
|
||||||
|
5. 丢弃时长 < 70 ms 的音符。
|
||||||
|
|
||||||
|
**重复音融合**是准确率的关键设计。声学切分无法把一个持续音切成两半,而乐谱里
|
||||||
|
反复音是分开写的。若只在查询端融合,两侧音符数就系统性错位。因此在**查询端和
|
||||||
|
曲库端对称地**把相邻同音高(< 0.35 半音)且间隔足够小的音符合并、时长累加。
|
||||||
|
实测这一项把 10 条抽样查询的 Top-1 从 6/10 提升到 39/43。
|
||||||
|
|
||||||
|
### 3.4 旋律表示 `qbh/melody.py`
|
||||||
|
|
||||||
|
用三个等长数组 `midis / starts / durs` 表示。派生特征:
|
||||||
|
|
||||||
|
| 方法 | 含义 | 不变性 |
|
||||||
|
|---|---|---|
|
||||||
|
| `intervals()` | 相邻音高差(可截断) | 移调 |
|
||||||
|
| `norm_durs()` | 时值 ÷ 中值 | 速度 |
|
||||||
|
| `contour()` | U/D/R 符号串 | 移调 + 速度 |
|
||||||
|
| `log_dur_ratios()` | 相邻时值比的对数 | 速度 |
|
||||||
|
|
||||||
|
### 3.5 粗召回 `qbh/index.py`
|
||||||
|
|
||||||
|
倒排索引键为 `(码本名, n-gram)`,值为 `{song_id: 出现次数}`。十个码本覆盖不同
|
||||||
|
粒度(见 README 表格)。打分:
|
||||||
|
|
||||||
|
```
|
||||||
|
score(s) = Σ_cb w_cb · Σ_gram idf(gram) · min(count_q, count_s) / Σ_cb w_cb · Σ_gram count_q
|
||||||
|
```
|
||||||
|
|
||||||
|
其中 `idf(gram) = log(1 + N / (1 + df))`。候选数取
|
||||||
|
`max(40, 7·√N)`,并丢弃低于最高分 10% 的候选;候选少于 5 个时回退全库。
|
||||||
|
|
||||||
|
**为什么需要多码本**:只用精确音程 n-gram,哼唱抖动会让匹配彻底失败;只用方向
|
||||||
|
码本,则所有「先上后下」的旋律都无法区分。两者结合才能既容忍误差又保持区分度。
|
||||||
|
|
||||||
|
### 3.6 精排 `qbh/dtw.py`
|
||||||
|
|
||||||
|
**子序列 DTW**(开放起止):
|
||||||
|
|
||||||
|
```
|
||||||
|
D[0, :] = cost[0, :] # 起点开放
|
||||||
|
D[i, j] = cost[i, j] + min(D[i-1, j], D[i, j-1], D[i-1, j-1])
|
||||||
|
```
|
||||||
|
|
||||||
|
终点取末行最小值,路径长度用查询长度归一化。这样查询可以对齐曲库旋律的任意
|
||||||
|
连续片段。
|
||||||
|
|
||||||
|
**单元代价**:
|
||||||
|
|
||||||
|
```
|
||||||
|
cost(i,j) = w_p · min(max(|(q_i + shift) − t_j| − 0.3, 0), 10)
|
||||||
|
+ w_d · min(|ln(qdur_i / tdur_j)|, 2.5)
|
||||||
|
```
|
||||||
|
|
||||||
|
自由带 0.3 半音吸收 YIN 在颤音处的量化误差。
|
||||||
|
|
||||||
|
**向量化行递推**:令 `A[j] = min(prev[j], prev[j−1])`、`S[j] = Σ_{k≤j} cost[k]`,
|
||||||
|
可推出
|
||||||
|
|
||||||
|
```
|
||||||
|
B[j] = cur[j] − S[j] = min(A[j] − S[j−1], B[j−1])
|
||||||
|
```
|
||||||
|
|
||||||
|
即 `B` 是 `A[j] − S[j−1]` 的**累积最小**,用 `np.minimum.accumulate` 一次算出,
|
||||||
|
再 `cur = B + S`。与朴素三重循环实现的最大误差 < 1e-14。
|
||||||
|
|
||||||
|
**移调搜索**:主估计取两侧**中值音高差**(整条旋律被整体移调后,中值差等于移调量,
|
||||||
|
对片段查询同样成立),在其 ±4 半音邻域内搜索;再叠加音高直方图重叠度的 top 候选
|
||||||
|
各扩 ±1,覆盖查询中个别音被折叠了八度的情况。
|
||||||
|
|
||||||
|
### 3.7 分数融合 `qbh/search.py`
|
||||||
|
|
||||||
|
```
|
||||||
|
score = w_dtw · exp(−λ · 平均代价) + w_index · 归一化重叠分
|
||||||
|
```
|
||||||
|
|
||||||
|
- 索引分擅长区分「音程走向一致但细节不同」的近邻曲目;
|
||||||
|
- DTW 分擅长判断整体旋律是否连续对齐。
|
||||||
|
|
||||||
|
默认 `w_dtw = 0.8`、`w_index = 0.2`、`λ = 0.6`。只对最终 Top-K 重算对齐路径,
|
||||||
|
用于前端画对齐图,避免为全部候选维护回溯矩阵。
|
||||||
|
|
||||||
|
## 4. 曲库与数据
|
||||||
|
|
||||||
|
| 来源 | 数量 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `data/midi/*.mid` | 27 | 真实公版旋律 MIDI(含 6 首五声音阶合成) |
|
||||||
|
| `qbh/scores.py` | 34 | 内置曲谱(简谱式 DSL),与 MIDI 同名的 18 首自动去重 |
|
||||||
|
| **实际曲库** | **43** | 27 MIDI + 16 内置 |
|
||||||
|
|
||||||
|
记谱 DSL 形如 `"C4:1 D4:0.5 E4:2"`,`-` 为休止、`|` 为小节线(忽略)、支持 `#`/`b`。
|
||||||
|
|
||||||
|
## 5. 评测设计
|
||||||
|
|
||||||
|
见 [`评测报告.md`](评测报告.md)。要点:
|
||||||
|
|
||||||
|
- 查询扰动施加在**旋律层**,再渲染成音频交给系统从零识别,度量端到端能力;
|
||||||
|
- 除 Top-K/MRR 外,单独统计**粗召回率**以区分召回瓶颈与排序瓶颈;
|
||||||
|
- 噪声实验用**预处理开/关**对照,量化预处理的贡献;
|
||||||
|
- 参数调优在留出种子上验证,明确记录过拟合现象。
|
||||||
|
|
||||||
|
## 6. 工程取舍
|
||||||
|
|
||||||
|
| 取舍 | 选择 | 理由 |
|
||||||
|
|---|---|---|
|
||||||
|
| 是否依赖 librosa | 否,自研 YIN | 避免 numba/llvmlite 在新 Python 版本上的轮子风险;算法可控 |
|
||||||
|
| 是否依赖 mido/pretty_midi | 否,自研 MIDI 解析 | 只用到很少的子集,减少依赖 |
|
||||||
|
| 密码哈希 | 标准库 `hashlib.scrypt` | 避免 bcrypt 的编译依赖,安全性足够 |
|
||||||
|
| 前端构建 | 无,原生 JS | 零构建步骤,降低部署与复现成本 |
|
||||||
|
| 图表 | Canvas 自绘(+ 可选 matplotlib) | 前端不引入图表库;PNG 导出为可选项 |
|
||||||
|
| 索引存储 | SQLite | 支持真正的增删改查与检索历史 |
|
||||||
|
|
||||||
|
## 7. 后续可改进方向
|
||||||
|
|
||||||
|
1. **提高粗召回率**:大规模下召回率降到 90%,是 Top-1 的上限。可增加码本、
|
||||||
|
提高候选数,或引入语义哈希。
|
||||||
|
2. **更好的音符切分**:当前音符数比 0.83–0.92,是主要误差源。可尝试
|
||||||
|
基于 HMM/Viterbi 的切分或音符后处理。
|
||||||
|
3. **多声部**:当前从复调 MIDI 抽旋律用「重叠保留高音」,会丢失内声部。
|
||||||
|
4. **真实哼唱数据**:接入 MIREX-QBH 等真实人声数据集,验证泛化能力。
|
||||||
|
5. **更细的鲁棒性**:区分白噪声、粉噪声、人声干扰、混响等不同退化类型。
|
||||||
+169
@@ -0,0 +1,169 @@
|
|||||||
|
# 评测报告
|
||||||
|
|
||||||
|
本文汇总三组实验:**主评测**(43 首真实/内置曲库)、**大规模基准**(300/600/1000 首)、
|
||||||
|
**噪声鲁棒性消融**。所有实验固定随机种子,可通过下列命令复现:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python cli.py eval --per-song 3 --seed 20260908
|
||||||
|
python cli.py bench --sizes 300,600,1000 --queries 60
|
||||||
|
python cli.py noise --per-song 2
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 评测方法
|
||||||
|
|
||||||
|
### 1.1 查询合成(模拟人哼唱)
|
||||||
|
|
||||||
|
公开的哼唱数据集(如 MIREX-QBH)需要额外下载且体积很大,因此本项目用**显式扰动模型**
|
||||||
|
合成查询。每条查询按以下步骤从曲库旋律生成,参数全部由种子决定:
|
||||||
|
|
||||||
|
| 步骤 | 参数 |
|
||||||
|
|---|---|
|
||||||
|
| 取连续片段 | 简单 45–80%,中等 30–60%,困难 40–80% 的音符数 |
|
||||||
|
| 移调 | ±5 半音,12% 概率再 ±12 |
|
||||||
|
| 速度缩放 | 0.82–1.28× |
|
||||||
|
| 音高扰动 | 逐音抖动 σ ≈ 0.28–0.50 半音 + 缓慢漂移 |
|
||||||
|
| 音符级扰动 | 丢音 4–16%、劈音 3–8%、插入邻音 2–5% |
|
||||||
|
| 音色渲染 | 起音滑音、颤音(渐入)、弱谐波、呼吸噪声 |
|
||||||
|
| 加噪 | 简单 22 dB / 中等 18 dB / 困难 12 dB 白噪声 |
|
||||||
|
|
||||||
|
**关键点**:扰动施加在旋律层,渲染成音频后由系统**从零识别**,走完整流水线
|
||||||
|
(预处理 → YIN → 切分 → 检索),因此度量的是端到端能力,而不是对已知特征的匹配。
|
||||||
|
|
||||||
|
### 1.2 指标
|
||||||
|
|
||||||
|
- **Top-K 准确率**:正确答案排在前 K 名之内的比例;
|
||||||
|
- **MRR**:正确排名的倒数均值(单答案场景下等同 MAP);
|
||||||
|
- **粗召回率**:答案是否进入第一级倒排索引的候选集——用于区分「召回瓶颈」与「排序瓶颈」;
|
||||||
|
- **延迟 p50 / p95**:单次检索耗时(不含音频渲染)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 主评测结果
|
||||||
|
|
||||||
|
曲库 **43 首**(27 首真实 MIDI + 16 首内置曲谱),每首 3 条查询,共 **129 条/难度**,
|
||||||
|
随机种子 `20260908`。
|
||||||
|
|
||||||
|
| 难度 | Top-1 | Top-3 | Top-5 | Top-10 | MRR | 粗召回率 | 延迟 p50 | 延迟 p95 |
|
||||||
|
|---|---:|---:|---:|---:|---:|---:|---:|---:|
|
||||||
|
| 简单 | **89.9%** | 95.3% | 96.1% | 96.9% | 0.928 | 100.0% | 93 ms | 137 ms |
|
||||||
|
| 中等 | **76.0%** | 86.0% | 88.4% | 93.0% | 0.814 | 99.2% | 75 ms | 112 ms |
|
||||||
|
| 困难 | **62.0%** | 70.5% | 74.4% | 82.2% | 0.676 | 96.9% | 80 ms | 117 ms |
|
||||||
|
|
||||||
|
音符提取质量:
|
||||||
|
|
||||||
|
| 难度 | 音符数比(提取/真值) | 音高误差中位数 |
|
||||||
|
|---|---:|---:|
|
||||||
|
| 简单 | 0.92 | 0.10 半音 |
|
||||||
|
| 中等 | 0.89 | 0.08 半音 |
|
||||||
|
| 困难 | 0.83 | 1.44 半音 |
|
||||||
|
|
||||||
|
**读法**:音高提取非常准(0.1 半音以内),主要损失来自**音符数偏少**
|
||||||
|
(重复音融合 + 扰动丢音)。困难模式下音高误差跳到 1.44 半音,因为 12 dB 噪声
|
||||||
|
下 YIN 在颤音谷底会出现半音级抖动。
|
||||||
|
|
||||||
|
### 2.1 跨种子稳定性
|
||||||
|
|
||||||
|
单一种子的 129 条查询估计有噪声,我们另外用三个留出种子复测(Top-1):
|
||||||
|
|
||||||
|
| 种子 | 简单 | 中等 | 困难 |
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
| 777 | 83.7% | 67.4% | 58.9% |
|
||||||
|
| 1234 | 86.8% | 75.2% | 62.0% |
|
||||||
|
| 55 | 80.6% | 72.1% | 53.5% |
|
||||||
|
|
||||||
|
跨度约 ±5 个百分点,说明上表数字应理解为「同量级」而非精确值。
|
||||||
|
|
||||||
|
### 2.2 失败分析(中等难度,31 个 Top-1 失误)
|
||||||
|
|
||||||
|
| 观察 | 数值 |
|
||||||
|
|---|---|
|
||||||
|
| 失误中答案仍在粗候选集内的比例 | **30 / 31** |
|
||||||
|
| 失误的平均音符数比 | 0.849(命中为 0.897) |
|
||||||
|
| 失误的音高误差中位数 | 0.11 半音 |
|
||||||
|
|
||||||
|
结论:**瓶颈在精排而非召回**。音高提取不是主要问题,音符数偏少(少切/融合掉
|
||||||
|
关键音)才是。失误分布在多组曲目之间,没有单一「吸引子」;少数失误指向
|
||||||
|
`penta_0x` 这类五声音阶合成旋律——它们本身是随机游走,与许多民歌的局部
|
||||||
|
音程模式相似。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 大规模基准
|
||||||
|
|
||||||
|
合成曲库(随机游走 + 动机重复),每规模 60 条合成查询:
|
||||||
|
|
||||||
|
| 曲库规模 | n-gram 数 | 候选召回率 | Top-1 | Top-5 | MRR | 平均候选数 | 延迟 p50 | 延迟 p95 | 索引构建 |
|
||||||
|
|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
|
||||||
|
| 300 | 11136 | 98.3% | 90.0% | 96.7% | 0.926 | 121 | 256 ms | 418 ms | 133 ms |
|
||||||
|
| 600 | 16451 | 95.0% | 80.0% | 86.7% | 0.835 | 166 | 324 ms | 486 ms | 189 ms |
|
||||||
|
| 1000 | 21918 | 90.0% | 80.0% | 88.3% | 0.836 | 220 | 433 ms | 673 ms | 322 ms |
|
||||||
|
|
||||||
|
**扩展性**:曲库扩大 3.3 倍,p50 延迟只增长约 1.7 倍。原因是两级检索把精排规模
|
||||||
|
限制在「候选数」量级(1000 首时约 220 个候选),而不是随曲库线性增长。
|
||||||
|
**代价**是召回率随规模下降(98.3% → 90.0%),这直接限制了 Top-1 的上限。
|
||||||
|
若要进一步提升大规模表现,方向是提高候选数或增加码本,而不是改 DTW。
|
||||||
|
|
||||||
|
> ⚠️ 本节的曲库与查询由同一合成器生成,准确率只作**相对参考**;
|
||||||
|
> 召回率与延迟的**扩展趋势**才是这里要说明的重点。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 噪声鲁棒性
|
||||||
|
|
||||||
|
对同一批查询叠加白噪声,扫描信噪比。两组对照:预处理开启(滑动均值去噪 +
|
||||||
|
60–2000 Hz 四阶巴特沃斯带通)与关闭。
|
||||||
|
|
||||||
|
| SNR | 预处理开启 Top-1 | 预处理关闭 Top-1 |
|
||||||
|
|---:|---:|---:|
|
||||||
|
| 22 dB | 70.9% | 73.3% |
|
||||||
|
| 18 dB | 70.9% | 69.8% |
|
||||||
|
| 15 dB | 72.1% | 70.9% |
|
||||||
|
| 12.5 dB | 73.3% | 70.9% |
|
||||||
|
| 10 dB | 73.3% | 75.6% |
|
||||||
|
| 7.5 dB | 69.8% | **15.1%** |
|
||||||
|
| 5 dB | 70.9% | **5.8%** |
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
(曲线由 `python cli.py noise` 生成,原始数据见 `data/noise_curve.csv`。)
|
||||||
|
|
||||||
|
**结论**:
|
||||||
|
|
||||||
|
1. **预处理是低信噪比下的决定性因素**。开启时 Top-1 在 22 → 5 dB 全程稳定在
|
||||||
|
70–73%,几乎不衰减;关闭时 10 dB 以下急剧崩溃(7.5 dB 时仅 15.1%,
|
||||||
|
5 dB 时 5.8%)。
|
||||||
|
2. **高信噪比下预处理略有代价**(22 dB 时 70.9% vs 73.3%):带通会削掉哼唱中
|
||||||
|
一部分有用能量。这是「保真」与「抗噪」的典型取舍。
|
||||||
|
3. 关闭预处理时延迟显著上升(7.5 dB 时 p50 从 70 ms 涨到 216 ms),因为噪声
|
||||||
|
让更多帧被误判为有声,切分出的伪音符增加了检索负担。
|
||||||
|
|
||||||
|
> 注:本节的 Top-1 基线(约 71%)低于主评测的中等难度(76%),因为
|
||||||
|
> `noise_experiment` 使用 `--per-song 2` 的较小采样集,两者不可直接比较。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 参数调优与过拟合观察
|
||||||
|
|
||||||
|
用坐标下降在固定查询集上扫描 `w_index`、时长权重、自由带宽度、λ、移调搜索跨度。
|
||||||
|
观察到的现象值得记录:
|
||||||
|
|
||||||
|
- 在**调优种子**上 Top-1 从 76.0% 提到 78.3%(+2.3pp);
|
||||||
|
- 但在**留出种子**上,同一组参数在困难难度上反而下降 2–4pp;
|
||||||
|
- 因此最终**只采纳了跨种子一致有效的改动**(例如把移调搜索从固定 ±12 改为
|
||||||
|
中值音高差邻域,修掉了「+17 半音查询永远匹配不上」的边界问题,在留出集上
|
||||||
|
简单难度 +6.2pp、中等 +3.8pp、困难 +4.6pp),**拒绝了**只在调优集上有效的取值。
|
||||||
|
|
||||||
|
这说明 129 条查询的评测集对参数选择而言太小。更稳健的做法是先把评测集扩大到
|
||||||
|
数百条,再做调优。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 诚实性声明
|
||||||
|
|
||||||
|
- 曲库中 27 首是**真实 MIDI**(公版旋律,权威真值),16 首是手工录入的内置曲谱;
|
||||||
|
- 查询是**合成**的,因此「合成查询 → 合成/真实混合曲库」的数字应理解为
|
||||||
|
**自洽基准**,不能直接外推为对真实人声哼唱的泛化能力;
|
||||||
|
- 大规模基准的曲库与查询同源,准确率只作相对参考,重点看召回率与延迟趋势;
|
||||||
|
- 所有实验固定种子、输出 JSON 明细,可逐条复核。
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
[project]
|
||||||
|
name = "qbh"
|
||||||
|
version = "1.0.0"
|
||||||
|
description = "基于旋律的音乐哼唱检索系统(Query by Humming)"
|
||||||
|
requires-python = ">=3.12"
|
||||||
|
dependencies = [
|
||||||
|
"numpy>=2.1",
|
||||||
|
"scipy>=1.15",
|
||||||
|
"fastapi>=0.115",
|
||||||
|
"uvicorn>=0.30",
|
||||||
|
"python-multipart>=0.0.9",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
audio = ["soundfile>=0.12"]
|
||||||
|
desktop = ["sounddevice>=0.5"]
|
||||||
|
plots = ["matplotlib>=3.10"]
|
||||||
|
dev = ["pytest>=8", "httpx>=0.27"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
addopts = "-q"
|
||||||
|
filterwarnings = [
|
||||||
|
"ignore::DeprecationWarning:starlette.*",
|
||||||
|
"ignore::UserWarning:starlette.*",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.setuptools]
|
||||||
|
packages = ["qbh", "app", "desktop"]
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# 核心运行时依赖(全部提供 CPython 3.14 / Windows 轮子)
|
||||||
|
numpy>=2.1
|
||||||
|
scipy>=1.15
|
||||||
|
fastapi>=0.115
|
||||||
|
uvicorn>=0.30
|
||||||
|
python-multipart>=0.0.9
|
||||||
|
|
||||||
|
# 可选增强(缺失时系统自动降级,不影响核心检索)
|
||||||
|
soundfile>=0.12 # MP3 / FLAC / OGG 解码;缺失时仅支持 WAV
|
||||||
|
sounddevice>=0.5 # 桌面客户端直接录音;缺失时桌面端改用文件选择
|
||||||
|
matplotlib>=3.10 # 实验图表导出 PNG;缺失时仅导出 SVG/CSV
|
||||||
|
|
||||||
|
# 开发与测试
|
||||||
|
pytest>=8
|
||||||
|
httpx>=0.27
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""一键启动 Web 服务(默认 http://127.0.0.1:8700 并自动打开浏览器)。
|
||||||
|
|
||||||
|
用法::
|
||||||
|
|
||||||
|
python run.py # 启动并打开浏览器
|
||||||
|
python run.py --no-browser # 只启动服务
|
||||||
|
python run.py --port 8800 # 换端口
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import threading
|
||||||
|
import webbrowser
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="基于旋律的音乐哼唱检索系统 —— Web 服务")
|
||||||
|
parser.add_argument("--host", default="127.0.0.1")
|
||||||
|
parser.add_argument("--port", type=int, default=8700)
|
||||||
|
parser.add_argument("--no-browser", action="store_true", help="不自动打开浏览器")
|
||||||
|
parser.add_argument("--reload", action="store_true", help="代码热重载(开发用)")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
url = f"http://{args.host}:{args.port}"
|
||||||
|
if not args.no_browser:
|
||||||
|
threading.Timer(1.5, lambda: webbrowser.open(url)).start()
|
||||||
|
|
||||||
|
print(f"服务地址:{url}")
|
||||||
|
print("按 Ctrl+C 停止。")
|
||||||
|
uvicorn.run(
|
||||||
|
"app.main:app",
|
||||||
|
host=args.host,
|
||||||
|
port=args.port,
|
||||||
|
reload=args.reload,
|
||||||
|
log_level="info",
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
"""启动 Tkinter 桌面客户端。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
|
||||||
|
from desktop.client import main # noqa: E402
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main(sys.argv[1:]))
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
"""噪声鲁棒性实验。
|
||||||
|
|
||||||
|
做两组对照:
|
||||||
|
|
||||||
|
1. **信噪比消融**:固定预处理开,扫描 SNR 22 → 5 dB,看 Top-1 如何衰减;
|
||||||
|
2. **预处理消融**:固定若干 SNR,对比「去噪 + 带通」开/关的效果。
|
||||||
|
|
||||||
|
输出 ``data/noise_report.json``(网页端读取)、``data/noise_curve.csv``
|
||||||
|
(便于外部绘图),若装了 matplotlib 还会导出 PNG。
|
||||||
|
|
||||||
|
用法::
|
||||||
|
|
||||||
|
python -m scripts.noise_experiment
|
||||||
|
python -m scripts.noise_experiment --per-song 2 --levels 22,18,15,12.5,10,7.5,5
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT # noqa: E402
|
||||||
|
from qbh.evaluate import evaluate, make_query_specs # noqa: E402
|
||||||
|
from qbh.library import Library # noqa: E402
|
||||||
|
from qbh.search import SearchEngine # noqa: E402
|
||||||
|
from qbh.store import Store # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _run_levels(
|
||||||
|
engine: SearchEngine,
|
||||||
|
library: Library,
|
||||||
|
levels: list[float],
|
||||||
|
*,
|
||||||
|
per_song: int,
|
||||||
|
seed: int,
|
||||||
|
preprocess_on: bool,
|
||||||
|
label: str,
|
||||||
|
) -> list[dict]:
|
||||||
|
rows: list[dict] = []
|
||||||
|
for snr in levels:
|
||||||
|
specs = make_query_specs(
|
||||||
|
library.melodies(),
|
||||||
|
n_per_song=per_song,
|
||||||
|
difficulty="normal",
|
||||||
|
seed=seed,
|
||||||
|
snr_db=snr,
|
||||||
|
)
|
||||||
|
# 通过覆写 engine.search_audio 的预处理开关来实现消融
|
||||||
|
original = engine.search_audio
|
||||||
|
|
||||||
|
def patched(samples, sr, *, top_k=None, cfg=None, **kw):
|
||||||
|
kw.setdefault("do_bandpass", preprocess_on)
|
||||||
|
kw.setdefault("do_denoise", preprocess_on)
|
||||||
|
return original(samples, sr, top_k=top_k, cfg=cfg, **kw)
|
||||||
|
|
||||||
|
engine.search_audio = patched # type: ignore[assignment]
|
||||||
|
try:
|
||||||
|
report = evaluate(engine, specs, label=f"{label}-{snr:g}dB", cfg=DEFAULT)
|
||||||
|
finally:
|
||||||
|
engine.search_audio = original # type: ignore[assignment]
|
||||||
|
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"snr_db": snr,
|
||||||
|
"top1": report.top1,
|
||||||
|
"top3": report.top3,
|
||||||
|
"top5": report.top5,
|
||||||
|
"mrr": report.mrr,
|
||||||
|
"p50_ms": report.p50_latency_ms,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
print(f" [{label}] SNR {snr:>5.1f} dB → Top-1 {report.top1*100:5.1f}% "
|
||||||
|
f"Top-5 {report.top5*100:5.1f}% MRR {report.mrr:.3f}")
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="噪声鲁棒性实验")
|
||||||
|
parser.add_argument("--db", default="data/qbh.db")
|
||||||
|
parser.add_argument("--per-song", type=int, default=2)
|
||||||
|
parser.add_argument("--seed", type=int, default=20260908)
|
||||||
|
parser.add_argument("--levels", default="22,18,15,12.5,10,7.5,5")
|
||||||
|
parser.add_argument("--out", default="data/noise_report.json")
|
||||||
|
parser.add_argument("--csv", default="data/noise_curve.csv")
|
||||||
|
parser.add_argument("--png", default="data/noise_curve.png")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
levels = [float(v) for v in args.levels.split(",")]
|
||||||
|
store = Store(args.db)
|
||||||
|
library = Library(store, DEFAULT)
|
||||||
|
if library.count() == 0:
|
||||||
|
library.build()
|
||||||
|
engine = SearchEngine(library, DEFAULT)
|
||||||
|
|
||||||
|
print(f"曲库 {library.count()} 首,每首 {args.per_song} 条查询\n")
|
||||||
|
print("预处理开启(去噪 + 带通 60–2000 Hz):")
|
||||||
|
on_rows = _run_levels(
|
||||||
|
engine, library, levels, per_song=args.per_song, seed=args.seed,
|
||||||
|
preprocess_on=True, label="preprocess-on",
|
||||||
|
)
|
||||||
|
print("\n预处理关闭(原始波形直接送 YIN):")
|
||||||
|
off_rows = _run_levels(
|
||||||
|
engine, library, levels, per_song=args.per_song, seed=args.seed,
|
||||||
|
preprocess_on=False, label="preprocess-off",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 找 50% Top-1 的拐点
|
||||||
|
def knee(rows: list[dict]) -> float | None:
|
||||||
|
for row in sorted(rows, key=lambda r: -r["snr_db"]):
|
||||||
|
if row["top1"] < 0.5:
|
||||||
|
return float(row["snr_db"])
|
||||||
|
return None
|
||||||
|
|
||||||
|
report = {
|
||||||
|
"levels": levels,
|
||||||
|
"per_song": args.per_song,
|
||||||
|
"seed": args.seed,
|
||||||
|
"n_songs": library.count(),
|
||||||
|
"curve": on_rows,
|
||||||
|
"baseline_no_preprocess": off_rows,
|
||||||
|
"knee_snr_db": knee(on_rows),
|
||||||
|
"note": (
|
||||||
|
"查询为合成哼唱(含颤音/滑音/丢音)按目标信噪比叠加白噪声;"
|
||||||
|
"knee_snr_db 表示 Top-1 首次跌破 50% 的信噪比。"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
Path(args.out).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
print(f"\n→ {args.out}")
|
||||||
|
|
||||||
|
csv_path = Path(args.csv)
|
||||||
|
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with csv_path.open("w", newline="", encoding="utf-8") as fh:
|
||||||
|
writer = csv.writer(fh)
|
||||||
|
writer.writerow(["mode", "snr_db", "top1", "top3", "top5", "mrr", "p50_ms"])
|
||||||
|
for mode, rows in (("preprocess-on", on_rows), ("preprocess-off", off_rows)):
|
||||||
|
for row in rows:
|
||||||
|
writer.writerow([mode, row["snr_db"], row["top1"], row["top3"],
|
||||||
|
row["top5"], row["mrr"], row["p50_ms"]])
|
||||||
|
print(f"→ {csv_path}")
|
||||||
|
|
||||||
|
try: # 可选:画图
|
||||||
|
import matplotlib
|
||||||
|
|
||||||
|
matplotlib.use("Agg")
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
# 让中文标题正常显示(Windows 自带字体)
|
||||||
|
matplotlib.rcParams["font.sans-serif"] = [
|
||||||
|
"Microsoft YaHei", "SimHei", "DejaVu Sans"
|
||||||
|
]
|
||||||
|
matplotlib.rcParams["axes.unicode_minus"] = False
|
||||||
|
|
||||||
|
fig, ax = plt.subplots(figsize=(7, 4.2), dpi=140)
|
||||||
|
for mode, rows, style in (
|
||||||
|
("预处理开启", on_rows, "o-"),
|
||||||
|
("预处理关闭", off_rows, "s--"),
|
||||||
|
):
|
||||||
|
xs = [r["snr_db"] for r in rows]
|
||||||
|
ys = [r["top1"] * 100 for r in rows]
|
||||||
|
ax.plot(xs, ys, style, label=mode)
|
||||||
|
ax.set_xlabel("SNR (dB)")
|
||||||
|
ax.set_ylabel("Top-1 准确率 (%)")
|
||||||
|
ax.set_title("哼唱检索在不同信噪比下的 Top-1")
|
||||||
|
ax.invert_xaxis()
|
||||||
|
ax.grid(alpha=0.3)
|
||||||
|
ax.legend()
|
||||||
|
fig.tight_layout()
|
||||||
|
fig.savefig(args.png)
|
||||||
|
print(f"→ {args.png}")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"(跳过 PNG 绘图:{exc})")
|
||||||
|
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""跑完整评测并输出可复现的报告。
|
||||||
|
|
||||||
|
用法::
|
||||||
|
|
||||||
|
python -m scripts.run_eval # 三个难度各跑一遍
|
||||||
|
python -m scripts.run_eval --per-song 5 # 每首 5 条查询
|
||||||
|
python -m scripts.run_eval --difficulty normal # 只跑中等难度
|
||||||
|
python -m scripts.run_eval --markdown docs/评测报告.md
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT # noqa: E402
|
||||||
|
from qbh.evaluate import evaluate, make_query_specs # noqa: E402
|
||||||
|
from qbh.library import Library # noqa: E402
|
||||||
|
from qbh.search import SearchEngine # noqa: E402
|
||||||
|
from qbh.store import Store # noqa: E402
|
||||||
|
|
||||||
|
DIFFICULTIES = ("easy", "normal", "hard")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="QBH 评测")
|
||||||
|
parser.add_argument("--db", default="data/qbh.db")
|
||||||
|
parser.add_argument("--per-song", type=int, default=3)
|
||||||
|
parser.add_argument("--seed", type=int, default=20260908)
|
||||||
|
parser.add_argument("--top-k", type=int, default=10)
|
||||||
|
parser.add_argument("--difficulty", default="all", choices=("all",) + DIFFICULTIES)
|
||||||
|
parser.add_argument("--out-dir", default="data")
|
||||||
|
parser.add_argument("--markdown", default="")
|
||||||
|
parser.add_argument("--verbose", action="store_true")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
store = Store(args.db)
|
||||||
|
library = Library(store, DEFAULT)
|
||||||
|
if library.count() == 0:
|
||||||
|
print("曲库为空,先构建…")
|
||||||
|
library.build()
|
||||||
|
engine = SearchEngine(library, DEFAULT)
|
||||||
|
|
||||||
|
difficulties = DIFFICULTIES if args.difficulty == "all" else (args.difficulty,)
|
||||||
|
reports = []
|
||||||
|
print(f"曲库 {library.count()} 首,每首 {args.per_song} 条查询,随机种子 {args.seed}\n")
|
||||||
|
|
||||||
|
for difficulty in difficulties:
|
||||||
|
specs = make_query_specs(
|
||||||
|
library.melodies(),
|
||||||
|
n_per_song=args.per_song,
|
||||||
|
difficulty=difficulty,
|
||||||
|
seed=args.seed,
|
||||||
|
)
|
||||||
|
report = evaluate(
|
||||||
|
engine, specs, label=difficulty, top_k=args.top_k, cfg=DEFAULT, verbose=args.verbose
|
||||||
|
)
|
||||||
|
reports.append(report)
|
||||||
|
print(report.summary_line())
|
||||||
|
print(f" 音符数比 {report.note_count_ratio:.2f} · "
|
||||||
|
f"音高误差中位数 {report.pitch_err_median:.2f} 半音 · "
|
||||||
|
f"平均排名 {report.mean_rank:.2f}")
|
||||||
|
out = Path(args.out_dir) / f"eval_report_{difficulty}.json"
|
||||||
|
report.save(out)
|
||||||
|
print(f" → {out}")
|
||||||
|
|
||||||
|
# 网页端读取的主报告用中等难度
|
||||||
|
primary = next((r for r in reports if r.label == "normal"), reports[0])
|
||||||
|
primary.save(Path(args.out_dir) / "eval_report.json")
|
||||||
|
|
||||||
|
if args.markdown:
|
||||||
|
lines = [
|
||||||
|
"## 评测结果(合成哼唱查询 → 完整流水线)",
|
||||||
|
"",
|
||||||
|
f"- 曲库:**{primary.n_songs} 首**(27 首真实 MIDI + 16 首内置曲谱)",
|
||||||
|
f"- 查询:每首 {args.per_song} 条,随机种子 {args.seed},共 {primary.n_queries} 条/难度",
|
||||||
|
"- 查询扰动:移调 ±5 半音(12% 概率再 ±12)、速度 0.82–1.28×、"
|
||||||
|
"逐音抖动 σ≈0.35 半音、丢音/劈音/插音、哼唱音色渲染、按 SNR 加噪",
|
||||||
|
"",
|
||||||
|
"| 难度 | Top-1 | Top-3 | Top-5 | Top-10 | MRR | 粗召回率 | 延迟 p50 | 延迟 p95 |",
|
||||||
|
"|---|---:|---:|---:|---:|---:|---:|---:|---:|",
|
||||||
|
]
|
||||||
|
for report in reports:
|
||||||
|
lines.append(
|
||||||
|
f"| {report.label} | {report.top1*100:.1f}% | {report.top3*100:.1f}% | "
|
||||||
|
f"{report.top5*100:.1f}% | {report.top10*100:.1f}% | {report.mrr:.3f} | "
|
||||||
|
f"{report.candidate_recall*100:.1f}% | {report.p50_latency_ms:.0f} ms | "
|
||||||
|
f"{report.p95_latency_ms:.0f} ms |"
|
||||||
|
)
|
||||||
|
lines += [
|
||||||
|
"",
|
||||||
|
"> 说明:查询由合成器生成,曲库中 27 首为真实 MIDI、16 首为内置曲谱,"
|
||||||
|
"因此这组数字是**自洽基准**而非绝对泛化能力。噪声鲁棒性见"
|
||||||
|
" `docs/评测报告.md` 的 SNR 消融章节。",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
Path(args.markdown).write_text("\n".join(lines), encoding="utf-8")
|
||||||
|
print(f"\nMarkdown 片段已写入 {args.markdown}")
|
||||||
|
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
+136
@@ -0,0 +1,136 @@
|
|||||||
|
"""参数调优:坐标下降法在固定查询集上搜索更好的排序参数。
|
||||||
|
|
||||||
|
为避免重复的音频处理开销,先一次性把查询音频转成旋律特征并缓存,
|
||||||
|
之后只重跑「粗召回 + DTW 精排」,因此一轮扫描只需几十秒。
|
||||||
|
|
||||||
|
用法::
|
||||||
|
|
||||||
|
python -m scripts.tune [--per-song 3] [--rounds 2]
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import itertools
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from dataclasses import replace
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT, Config # noqa: E402
|
||||||
|
from qbh.evaluate import make_query_specs, perturb_melody, synth_query_audio # noqa: E402
|
||||||
|
from qbh.library import Library # noqa: E402
|
||||||
|
from qbh.search import SearchEngine # noqa: E402
|
||||||
|
from qbh.store import Store # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def build_cache(engine: SearchEngine, specs, cfg: Config):
|
||||||
|
"""预计算每条查询的旋律特征(音频处理只做一次)。"""
|
||||||
|
melodies = {m.song_id: m for m in engine.library.melodies()}
|
||||||
|
cache = []
|
||||||
|
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)
|
||||||
|
from qbh.audio import preprocess
|
||||||
|
from qbh.notes import segment_notes
|
||||||
|
from qbh.pitch import extract_pitch
|
||||||
|
|
||||||
|
track = extract_pitch(preprocess(audio, cfg.sample_rate, cfg), cfg.sample_rate, cfg)
|
||||||
|
cache.append((spec.song_id, segment_notes(track, cfg), truth.n_notes))
|
||||||
|
return cache
|
||||||
|
|
||||||
|
|
||||||
|
def score_config(library: Library, cache, cfg: Config, top_k: int = 10) -> float:
|
||||||
|
engine = SearchEngine(library, cfg)
|
||||||
|
hits = 0
|
||||||
|
for answer, query, _ in cache:
|
||||||
|
result = engine.search_melody(query, top_k=top_k, with_path=False)
|
||||||
|
if result.hits and result.hits[0].song_id == answer:
|
||||||
|
hits += 1
|
||||||
|
return hits / max(len(cache), 1)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="QBH 排序参数调优")
|
||||||
|
parser.add_argument("--per-song", type=int, default=3)
|
||||||
|
parser.add_argument("--difficulty", default="normal")
|
||||||
|
parser.add_argument("--rounds", type=int, default=2)
|
||||||
|
parser.add_argument("--db", default="data/qbh.db")
|
||||||
|
parser.add_argument("--out", default="data/tuning_report.json")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
store = Store(args.db)
|
||||||
|
library = Library(store, DEFAULT)
|
||||||
|
engine = SearchEngine(library, DEFAULT)
|
||||||
|
|
||||||
|
specs = make_query_specs(
|
||||||
|
library.melodies(), n_per_song=args.per_song, difficulty=args.difficulty, seed=20260908
|
||||||
|
)
|
||||||
|
print(f"查询数 {len(specs)},曲库 {library.count()} 首,预计算特征…")
|
||||||
|
started = time.perf_counter()
|
||||||
|
cache = build_cache(engine, specs, DEFAULT)
|
||||||
|
print(f"缓存完成 {len(cache)} 条,用时 {time.perf_counter()-started:.1f}s")
|
||||||
|
|
||||||
|
grid = {
|
||||||
|
"w_index": [0.0, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4],
|
||||||
|
"dtw_dur_weight": [0.0, 0.2, 0.35, 0.5, 0.7, 0.9],
|
||||||
|
"dtw_pitch_free_band": [0.0, 0.2, 0.3, 0.5, 0.8],
|
||||||
|
"dtw_score_lambda": [0.2, 0.32, 0.45, 0.6, 0.8],
|
||||||
|
"transpose_span": [2, 3, 4, 6],
|
||||||
|
}
|
||||||
|
|
||||||
|
def derive(cfg: Config, name: str, value) -> Config:
|
||||||
|
"""w_index 与 w_dtw 是互补权重,需成对调整。"""
|
||||||
|
if name == "w_index":
|
||||||
|
return cfg.with_(w_index=value, w_dtw=1.0 - value)
|
||||||
|
return cfg.with_(**{name: value})
|
||||||
|
|
||||||
|
current = DEFAULT
|
||||||
|
best_score = score_config(library, cache, current)
|
||||||
|
print(f"初始 Top-1 = {best_score*100:.1f}%")
|
||||||
|
history = [{"config": current.to_dict(), "top1": best_score}]
|
||||||
|
|
||||||
|
for round_idx in range(args.rounds):
|
||||||
|
improved = False
|
||||||
|
for name, values in grid.items():
|
||||||
|
best_value = getattr(current, name)
|
||||||
|
for value in values:
|
||||||
|
if value == best_value:
|
||||||
|
continue
|
||||||
|
candidate = derive(current, name, value)
|
||||||
|
value_score = score_config(library, cache, candidate)
|
||||||
|
if value_score > best_score + 1e-9:
|
||||||
|
best_score, best_value, improved = value_score, value, True
|
||||||
|
if best_value != getattr(current, name):
|
||||||
|
current = derive(current, name, best_value)
|
||||||
|
print(f" round{round_idx+1} {name} -> {best_value} Top-1={best_score*100:.1f}%")
|
||||||
|
history.append({"config": current.to_dict(), "top1": best_score})
|
||||||
|
if not improved:
|
||||||
|
print(f" round{round_idx+1} 无改进,提前结束")
|
||||||
|
break
|
||||||
|
|
||||||
|
print(f"\n最终 Top-1 = {best_score*100:.1f}%")
|
||||||
|
diff = {k: v for k, v in current.to_dict().items() if getattr(DEFAULT, k) != v}
|
||||||
|
print("相对默认值的改动:", json.dumps(diff, ensure_ascii=False, indent=2))
|
||||||
|
|
||||||
|
Path(args.out).write_text(
|
||||||
|
json.dumps(
|
||||||
|
{"best_top1": best_score, "config_diff": diff, "history": history},
|
||||||
|
ensure_ascii=False,
|
||||||
|
indent=2,
|
||||||
|
),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
print(f"报告已写入 {args.out}")
|
||||||
|
store.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""pytest 公共夹具。
|
||||||
|
|
||||||
|
测试尽量不依赖磁盘上的真实曲库:多数用例用合成的小旋律,只有 API 端到端
|
||||||
|
测试才会构建一个临时曲库(并跳过音频渲染以加速)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT, Config # noqa: E402
|
||||||
|
from qbh.melody import Melody # noqa: E402
|
||||||
|
from qbh.synth import render_melody # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
def cfg() -> Config:
|
||||||
|
return DEFAULT
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def c_major_melody() -> Melody:
|
||||||
|
"""C 大调音阶上的一段旋律(8 个音)。"""
|
||||||
|
midis = [60, 62, 64, 67, 69, 67, 64, 62]
|
||||||
|
starts = np.arange(8) * 0.5
|
||||||
|
durs = np.full(8, 0.45)
|
||||||
|
return Melody(np.array(midis, float), starts, durs, "scale", "C大调音阶")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def long_melody() -> Melody:
|
||||||
|
"""20 个音的旋律,用于片段/子序列相关测试。"""
|
||||||
|
midis = [60, 62, 64, 65, 67, 69, 71, 72, 71, 69, 67, 65, 64, 62, 60, 62, 64, 67, 69, 72]
|
||||||
|
starts = np.arange(20) * 0.5
|
||||||
|
durs = np.full(20, 0.45)
|
||||||
|
return Melody(np.array(midis, float), starts, durs, "long", "长旋律")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tiny_library(cfg: Config):
|
||||||
|
"""三条合成旋律构成的极简曲库(内存 SQLite)。"""
|
||||||
|
from qbh.library import Library
|
||||||
|
from qbh.store import Store
|
||||||
|
|
||||||
|
store = Store(":memory:")
|
||||||
|
library = Library(store, cfg, midi_dir=Path("__nonexistent__"), audio_dir=Path("__nonexistent__"))
|
||||||
|
melodies = [
|
||||||
|
Melody(np.array([60, 62, 64, 67, 69, 67, 64, 62], float),
|
||||||
|
np.arange(8) * 0.5, np.full(8, 0.45), "m_a", "旋律A"),
|
||||||
|
Melody(np.array([72, 71, 69, 67, 65, 64, 62, 60], float),
|
||||||
|
np.arange(8) * 0.5, np.full(8, 0.45), "m_b", "旋律B"),
|
||||||
|
Melody(np.array([60, 60, 67, 67, 69, 69, 67], float),
|
||||||
|
np.arange(7) * 0.5, np.full(7, 0.45), "m_c", "旋律C"),
|
||||||
|
]
|
||||||
|
for melody in melodies:
|
||||||
|
library.add_melody(melody, song_id=melody.song_id, title=melody.title,
|
||||||
|
source="test", render_audio=False)
|
||||||
|
yield library
|
||||||
|
store.close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def hum_audio(c_major_melody, cfg):
|
||||||
|
"""把 C 大调旋律渲染成「哼唱」音频。"""
|
||||||
|
return render_melody(c_major_melody, cfg.sample_rate, timbre="hum", seed=7)
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
"""FastAPI 接口测试(使用临时曲库,跳过音频渲染以加速)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
_TMP_DIR = Path(tempfile.mkdtemp(prefix="qbh_api_test_"))
|
||||||
|
os.environ["QBH_DB"] = str(_TMP_DIR / "test.db")
|
||||||
|
os.environ["QBH_AUDIO_DIR"] = str(_TMP_DIR / "audio")
|
||||||
|
os.environ["QBH_SKIP_AUDIO"] = "1"
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient # noqa: E402
|
||||||
|
|
||||||
|
from app.main import app # noqa: E402
|
||||||
|
from qbh.audio import encode_wav_bytes # noqa: E402
|
||||||
|
from qbh.synth import render_melody # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client():
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def query_wav(client):
|
||||||
|
"""用后端自己的曲库造一条可检索的查询音频。"""
|
||||||
|
from app.main import state
|
||||||
|
|
||||||
|
melody = state.library.melodies()[0]
|
||||||
|
audio = render_melody(melody.transpose(3), 16000, timbre="hum", seed=31)
|
||||||
|
return encode_wav_bytes(audio, 16000), melody.song_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_status(client):
|
||||||
|
data = client.get("/api/status").json()
|
||||||
|
assert data["n_songs"] > 0
|
||||||
|
assert data["n_grams"] > 0
|
||||||
|
assert "config" in data
|
||||||
|
|
||||||
|
|
||||||
|
def test_songs_list(client):
|
||||||
|
data = client.get("/api/songs").json()
|
||||||
|
assert len(data["songs"]) > 0
|
||||||
|
song = data["songs"][0]
|
||||||
|
for key in ("id", "title", "n_notes", "source", "tags"):
|
||||||
|
assert key in song
|
||||||
|
|
||||||
|
|
||||||
|
def test_song_detail(client):
|
||||||
|
song_id = client.get("/api/songs").json()["songs"][0]["id"]
|
||||||
|
data = client.get(f"/api/songs/{song_id}").json()
|
||||||
|
assert data["song"]["id"] == song_id
|
||||||
|
assert data["melody"]["midis"]
|
||||||
|
assert data["contour"] == data["melody"]["contour"] if "contour" in data["melody"] else True
|
||||||
|
|
||||||
|
|
||||||
|
def test_song_detail_404(client):
|
||||||
|
assert client.get("/api/songs/does-not-exist").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_index_page(client):
|
||||||
|
response = client.get("/")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert "基于旋律的音乐哼唱检索系统" in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_static_assets(client):
|
||||||
|
for asset in ("/static/app.js", "/static/style.css"):
|
||||||
|
assert client.get(asset).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_multipart(client, query_wav):
|
||||||
|
blob, song_id = query_wav
|
||||||
|
response = client.post(
|
||||||
|
"/api/search",
|
||||||
|
files={"file": ("query.wav", blob, "audio/wav")},
|
||||||
|
data={"top_k": "5"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
data = response.json()
|
||||||
|
assert data["hits"]
|
||||||
|
assert data["query"]["n_notes"] > 0
|
||||||
|
assert data["elapsed_ms"] >= 0
|
||||||
|
assert any(hit["song_id"] == song_id for hit in data["hits"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_base64(client, query_wav):
|
||||||
|
blob, _ = query_wav
|
||||||
|
response = client.post(
|
||||||
|
"/api/search",
|
||||||
|
json={"audio_base64": base64.b64encode(blob).decode("ascii"), "top_k": 3},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
assert len(response.json()["hits"]) <= 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_rejects_garbage(client):
|
||||||
|
response = client.post(
|
||||||
|
"/api/search",
|
||||||
|
files={"file": ("bad.wav", b"not audio at all", "audio/wav")},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_demo_endpoint(client):
|
||||||
|
response = client.post("/api/demo", json={"difficulty": "easy", "seed": 123, "top_k": 5})
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
data = response.json()
|
||||||
|
assert data["hits"]
|
||||||
|
assert data["demo"]["answer"]
|
||||||
|
assert data["demo"]["qid"]
|
||||||
|
assert data["track"]["voiced_ratio"] > 0
|
||||||
|
|
||||||
|
audio = client.get(data["demo"]["audio_url"])
|
||||||
|
assert audio.status_code == 200
|
||||||
|
assert audio.headers["content-type"] == "audio/wav"
|
||||||
|
|
||||||
|
|
||||||
|
def test_auth_flow(client):
|
||||||
|
assert client.get("/api/auth/me").json()["logged_in"] is False
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/register", json={"username": "tester", "password": "secret123"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
assert client.get("/api/auth/me").json()["logged_in"] is True
|
||||||
|
|
||||||
|
# 重复注册
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/register", json={"username": "tester", "password": "secret123"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
assert client.post("/api/auth/logout").status_code == 200
|
||||||
|
assert client.get("/api/auth/me").json()["logged_in"] is False
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login", json={"username": "tester", "password": "secret123"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
response = client.post("/api/auth/login", json={"username": "tester", "password": "bad"})
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_endpoint(client):
|
||||||
|
client.post("/api/demo", json={"difficulty": "easy", "seed": 55, "top_k": 3})
|
||||||
|
data = client.get("/api/history?limit=5").json()
|
||||||
|
assert "history" in data
|
||||||
|
assert len(data["history"]) > 0
|
||||||
|
assert "top_song" in data["history"][0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_library_rebuild(client):
|
||||||
|
response = client.post("/api/library/rebuild")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["ok"] is True
|
||||||
|
assert client.get("/api/status").json()["n_songs"] > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_eval_run(client):
|
||||||
|
response = client.post(
|
||||||
|
"/api/eval/run", json={"difficulty": "easy", "per_song": 1, "seed": 1, "top_k": 5}
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
report = response.json()["report"]
|
||||||
|
assert report["n_queries"] > 0
|
||||||
|
assert 0.0 <= report["top1"] <= 1.0
|
||||||
|
|
||||||
|
latest = client.get("/api/eval/latest").json()
|
||||||
|
assert latest["available"] is True
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""音频输入与预处理测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.audio import (
|
||||||
|
bandpass,
|
||||||
|
denoise,
|
||||||
|
encode_wav_bytes,
|
||||||
|
frame_signal,
|
||||||
|
normalize,
|
||||||
|
read_audio,
|
||||||
|
read_wav_bytes,
|
||||||
|
resample,
|
||||||
|
rms_db,
|
||||||
|
trim_silence,
|
||||||
|
write_wav,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _tone(freq: float, seconds: float, sr: int, amp: float = 0.5) -> np.ndarray:
|
||||||
|
t = np.arange(int(sr * seconds)) / sr
|
||||||
|
return (amp * np.sin(2 * np.pi * freq * t)).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def test_wav_roundtrip(tmp_path):
|
||||||
|
sr = 16000
|
||||||
|
signal = _tone(440.0, 0.5, sr)
|
||||||
|
path = tmp_path / "tone.wav"
|
||||||
|
write_wav(path, signal, sr)
|
||||||
|
|
||||||
|
loaded, loaded_sr = read_audio(path)
|
||||||
|
assert loaded_sr == sr
|
||||||
|
assert loaded.shape == signal.shape
|
||||||
|
# 16-bit 量化误差应很小
|
||||||
|
assert np.max(np.abs(loaded - signal)) < 1e-3
|
||||||
|
|
||||||
|
|
||||||
|
def test_wav_bytes_roundtrip():
|
||||||
|
sr = 8000
|
||||||
|
signal = _tone(300.0, 0.2, sr)
|
||||||
|
blob = encode_wav_bytes(signal, sr)
|
||||||
|
loaded, loaded_sr = read_wav_bytes(blob)
|
||||||
|
assert loaded_sr == sr
|
||||||
|
assert np.allclose(loaded, signal, atol=1e-3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_resample_preserves_duration():
|
||||||
|
sr = 44100
|
||||||
|
signal = _tone(220.0, 0.4, sr)
|
||||||
|
out = resample(signal, sr, 16000)
|
||||||
|
assert abs(out.size / 16000 - 0.4) < 0.01
|
||||||
|
|
||||||
|
|
||||||
|
def test_resample_identity():
|
||||||
|
signal = _tone(440.0, 0.1, 16000)
|
||||||
|
out = resample(signal, 16000, 16000)
|
||||||
|
assert np.array_equal(out, signal)
|
||||||
|
|
||||||
|
|
||||||
|
def test_bandpass_rejects_out_of_band():
|
||||||
|
sr = 16000
|
||||||
|
low = _tone(20.0, 0.3, sr) # 低于通带
|
||||||
|
mid = _tone(440.0, 0.3, sr) # 通带内
|
||||||
|
high = _tone(6000.0, 0.3, sr) # 高于通带
|
||||||
|
|
||||||
|
low_out = bandpass(low, sr, 60.0, 2000.0)
|
||||||
|
mid_out = bandpass(mid, sr, 60.0, 2000.0)
|
||||||
|
high_out = bandpass(high, sr, 60.0, 2000.0)
|
||||||
|
|
||||||
|
def rms(x: np.ndarray) -> float:
|
||||||
|
return float(np.sqrt(np.mean(x**2)))
|
||||||
|
|
||||||
|
assert rms(mid_out) > 10 * rms(low_out)
|
||||||
|
assert rms(mid_out) > 10 * rms(high_out)
|
||||||
|
|
||||||
|
|
||||||
|
def test_denoise_reduces_high_frequency_noise():
|
||||||
|
rng = np.random.default_rng(0)
|
||||||
|
signal = _tone(440.0, 0.3, 16000, amp=0.5)
|
||||||
|
noisy = signal + rng.normal(0, 0.05, signal.size).astype(np.float32)
|
||||||
|
cleaned = denoise(noisy, 5)
|
||||||
|
assert np.std(cleaned - signal) < np.std(noisy - signal)
|
||||||
|
|
||||||
|
|
||||||
|
def test_trim_silence_removes_padding():
|
||||||
|
sr = 16000
|
||||||
|
core = _tone(440.0, 0.3, sr)
|
||||||
|
padded = np.concatenate([np.zeros(sr // 2, np.float32), core, np.zeros(sr // 2, np.float32)])
|
||||||
|
trimmed = trim_silence(padded, sr)
|
||||||
|
assert trimmed.size < padded.size
|
||||||
|
assert abs(trimmed.size / sr - 0.3) < 0.15
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_sets_rms():
|
||||||
|
signal = _tone(440.0, 0.2, 16000, amp=0.01)
|
||||||
|
out = normalize(signal, target_rms=0.1)
|
||||||
|
assert abs(rms_db(out) - 20 * np.log10(0.1)) < 1.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_rms_db_of_silence_is_negative_infinity():
|
||||||
|
assert rms_db(np.zeros(100, dtype=np.float32)) == float("-inf")
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_signal_shape():
|
||||||
|
x = np.arange(1000, dtype=np.float32)
|
||||||
|
frames = frame_signal(x, 100, 50)
|
||||||
|
assert frames.shape == (19, 100)
|
||||||
|
assert np.allclose(frames[0][:5], x[:5])
|
||||||
|
assert np.allclose(frames[1][:5], x[50:55])
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_audio_rejects_empty():
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
read_wav_bytes(b"")
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
"""DTW 与移调搜索测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT
|
||||||
|
from qbh.dtw import _cost_matrix, _dp_matrix, align, shift_candidates, subsequence_dtw
|
||||||
|
from qbh.melody import Melody
|
||||||
|
|
||||||
|
|
||||||
|
def _melody(midis, note_s=0.5, song_id="t") -> Melody:
|
||||||
|
midis = np.asarray(midis, dtype=float)
|
||||||
|
return Melody(midis, np.arange(midis.size) * note_s, np.full(midis.size, note_s * 0.9), song_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _naive_dp(cost: np.ndarray) -> np.ndarray:
|
||||||
|
rows, cols = cost.shape
|
||||||
|
D = np.full((rows, cols), np.inf)
|
||||||
|
D[0, :] = cost[0, :]
|
||||||
|
for i in range(1, rows):
|
||||||
|
for j in range(cols):
|
||||||
|
best = D[i - 1, j]
|
||||||
|
if j > 0:
|
||||||
|
best = min(best, D[i, j - 1], D[i - 1, j - 1])
|
||||||
|
D[i, j] = cost[i, j] + best
|
||||||
|
return D
|
||||||
|
|
||||||
|
|
||||||
|
def test_vectorized_dp_matches_naive():
|
||||||
|
rng = np.random.default_rng(0)
|
||||||
|
cost = rng.random((9, 14)) * 3.0
|
||||||
|
assert np.allclose(_dp_matrix(cost), _naive_dp(cost))
|
||||||
|
|
||||||
|
|
||||||
|
def test_fragment_alignment_finds_correct_span():
|
||||||
|
target = _melody(list(range(60, 75)))
|
||||||
|
query = target.slice(4, 12)
|
||||||
|
result = subsequence_dtw(query, target, shift=0.0, cfg=DEFAULT, need_path=True)
|
||||||
|
assert result.cost == pytest.approx(0.0, abs=1e-6)
|
||||||
|
assert result.target_note_start == 4
|
||||||
|
assert result.target_note_end == 11
|
||||||
|
assert result.sim == pytest.approx(1.0, abs=1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
def test_transposed_query_needs_shift():
|
||||||
|
target = _melody(list(range(60, 75)))
|
||||||
|
query = target.slice(4, 12).transpose(5)
|
||||||
|
|
||||||
|
good = subsequence_dtw(query, target, shift=-5.0, cfg=DEFAULT)
|
||||||
|
bad = subsequence_dtw(query, target, shift=0.0, cfg=DEFAULT)
|
||||||
|
assert good.cost < bad.cost
|
||||||
|
assert good.sim > 0.95
|
||||||
|
|
||||||
|
|
||||||
|
def test_shift_candidates_cover_octave_offsets():
|
||||||
|
target = _melody([60, 62, 64, 67, 69, 67, 64, 62])
|
||||||
|
query = target.transpose(17) # 跨八度的移调
|
||||||
|
candidates = shift_candidates(query, target, DEFAULT)
|
||||||
|
assert -17 in candidates
|
||||||
|
|
||||||
|
|
||||||
|
def test_shift_candidates_cover_plain_transposition():
|
||||||
|
target = _melody([60, 62, 64, 67, 69])
|
||||||
|
query = target.transpose(-5)
|
||||||
|
candidates = shift_candidates(query, target, DEFAULT)
|
||||||
|
assert 5 in candidates
|
||||||
|
|
||||||
|
|
||||||
|
def test_align_picks_best_shift_automatically():
|
||||||
|
target = _melody([60, 62, 64, 67, 69, 67, 64, 62, 60, 62])
|
||||||
|
query = target.slice(1, 7).transpose(4)
|
||||||
|
result = align(query, target, DEFAULT)
|
||||||
|
assert result.shift == pytest.approx(-4.0)
|
||||||
|
assert result.sim > 0.9
|
||||||
|
|
||||||
|
|
||||||
|
def test_duration_cost_penalizes_tempo_mismatch():
|
||||||
|
target = _melody([60, 62, 64, 67])
|
||||||
|
fast = target.scaled(0.25) # 时值全变成 1/4
|
||||||
|
cost = _cost_matrix(fast, target, 0.0, DEFAULT)
|
||||||
|
assert cost.mean() > 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_melody_alignment():
|
||||||
|
target = _melody([60, 62, 64])
|
||||||
|
result = subsequence_dtw(Melody.empty(), target, cfg=DEFAULT)
|
||||||
|
assert result.cost == float("inf")
|
||||||
|
assert result.sim == 0.0
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""评测模块测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT
|
||||||
|
from qbh.evaluate import (
|
||||||
|
DIFFICULTY_PRESETS,
|
||||||
|
add_noise,
|
||||||
|
evaluate,
|
||||||
|
make_query_specs,
|
||||||
|
perturb_melody,
|
||||||
|
synth_query_audio,
|
||||||
|
)
|
||||||
|
from qbh.melody import Melody
|
||||||
|
from qbh.search import SearchEngine
|
||||||
|
|
||||||
|
|
||||||
|
def _melody(song_id="m", n=24) -> Melody:
|
||||||
|
rng = np.random.default_rng(hash(song_id) % 2**31)
|
||||||
|
midis = 60 + np.cumsum(rng.integers(-2, 3, n)).astype(float)
|
||||||
|
midis = np.clip(midis, 55, 80)
|
||||||
|
starts = np.arange(n) * 0.5
|
||||||
|
return Melody(midis, starts, np.full(n, 0.45), song_id, song_id)
|
||||||
|
|
||||||
|
|
||||||
|
def test_make_query_specs_respects_difficulty():
|
||||||
|
melodies = [_melody(f"m{i}") for i in range(3)]
|
||||||
|
easy = make_query_specs(melodies, n_per_song=2, difficulty="easy", seed=1)
|
||||||
|
hard = make_query_specs(melodies, n_per_song=2, difficulty="hard", seed=1)
|
||||||
|
|
||||||
|
assert len(easy) == len(hard) == 6
|
||||||
|
assert easy[0].snr_db > hard[0].snr_db
|
||||||
|
for spec in easy + hard:
|
||||||
|
assert 4 <= spec.n_notes <= 24
|
||||||
|
assert spec.start_idx >= 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_query_specs_are_reproducible():
|
||||||
|
melodies = [_melody("m")]
|
||||||
|
a = make_query_specs(melodies, n_per_song=3, seed=123)
|
||||||
|
b = make_query_specs(melodies, n_per_song=3, seed=123)
|
||||||
|
assert [s.to_dict() for s in a] == [s.to_dict() for s in b]
|
||||||
|
|
||||||
|
|
||||||
|
def test_perturb_melody_applies_transposition_and_tempo():
|
||||||
|
source = _melody()
|
||||||
|
spec = make_query_specs([source], n_per_song=1, seed=5)[0]
|
||||||
|
query = perturb_melody(source, spec, DEFAULT)
|
||||||
|
|
||||||
|
# 音高整体平移(允许抖动带来的偏差)
|
||||||
|
offset = float(np.median(query.midis) - np.median(source.midis))
|
||||||
|
assert abs(offset - spec.shift) < 1.5
|
||||||
|
# 时长被速度缩放
|
||||||
|
ratio = float(np.median(query.durs) / np.median(source.durs))
|
||||||
|
assert abs(ratio - spec.tempo) < 0.3
|
||||||
|
|
||||||
|
|
||||||
|
def test_perturb_melody_changes_note_count():
|
||||||
|
source = _melody(n=40)
|
||||||
|
spec = make_query_specs([source], n_per_song=1, difficulty="hard", seed=9)[0]
|
||||||
|
query = perturb_melody(source, spec, DEFAULT)
|
||||||
|
assert query.n_notes >= 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_noise_achieves_rough_snr():
|
||||||
|
rng = np.random.default_rng(0)
|
||||||
|
t = np.arange(16000) / 16000
|
||||||
|
signal = (0.5 * np.sin(2 * np.pi * 440 * t)).astype(np.float32)
|
||||||
|
for target in (20.0, 10.0):
|
||||||
|
noisy = add_noise(signal, target, rng)
|
||||||
|
noise = noisy - signal
|
||||||
|
measured = 10 * np.log10(np.mean(signal**2) / np.mean(noise**2))
|
||||||
|
assert abs(measured - target) < 1.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_synth_query_audio_has_signal():
|
||||||
|
source = _melody()
|
||||||
|
spec = make_query_specs([source], n_per_song=1, seed=3)[0]
|
||||||
|
query = perturb_melody(source, spec, DEFAULT)
|
||||||
|
audio = synth_query_audio(query, spec, DEFAULT)
|
||||||
|
assert audio.size > 0
|
||||||
|
assert float(np.abs(audio).max()) > 0.1
|
||||||
|
|
||||||
|
|
||||||
|
def test_evaluate_returns_sane_metrics(tiny_library):
|
||||||
|
engine = SearchEngine(tiny_library, DEFAULT)
|
||||||
|
specs = make_query_specs(tiny_library.melodies(), n_per_song=2, difficulty="easy", seed=4)
|
||||||
|
report = evaluate(engine, specs, label="test", cfg=DEFAULT)
|
||||||
|
|
||||||
|
assert report.n_queries == len(specs)
|
||||||
|
assert 0.0 <= report.top1 <= 1.0
|
||||||
|
assert report.top3 >= report.top1
|
||||||
|
assert 0.0 <= report.mrr <= 1.0
|
||||||
|
assert report.p95_latency_ms >= report.p50_latency_ms
|
||||||
|
assert len(report.details) == report.n_queries
|
||||||
|
payload = report.to_dict()
|
||||||
|
assert payload["n_songs"] == 3
|
||||||
|
assert "config" in payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_evaluate_empty_specs():
|
||||||
|
class _Empty:
|
||||||
|
class index:
|
||||||
|
n_songs = 0
|
||||||
|
|
||||||
|
class library:
|
||||||
|
@staticmethod
|
||||||
|
def melodies():
|
||||||
|
return []
|
||||||
|
|
||||||
|
report = evaluate(_Empty(), [], label="empty", cfg=DEFAULT)
|
||||||
|
assert report.n_queries == 0
|
||||||
|
assert report.top1 == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_save_and_summary(tiny_library, tmp_path):
|
||||||
|
engine = SearchEngine(tiny_library, DEFAULT)
|
||||||
|
specs = make_query_specs(tiny_library.melodies(), n_per_song=1, seed=6)
|
||||||
|
report = evaluate(engine, specs, label="save", cfg=DEFAULT)
|
||||||
|
path = tmp_path / "report.json"
|
||||||
|
report.save(path)
|
||||||
|
assert path.exists()
|
||||||
|
assert "Top-1" in report.summary_line()
|
||||||
|
|
||||||
|
|
||||||
|
def test_difficulty_presets_have_expected_keys():
|
||||||
|
for name, preset in DIFFICULTY_PRESETS.items():
|
||||||
|
for key in ("fragment_low", "fragment_high", "drop", "jitter", "snr_db"):
|
||||||
|
assert key in preset, (name, key)
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""倒排索引测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT
|
||||||
|
from qbh.index import NgramIndex, quantize_direction, quantize_magnitude, quantize_rhythm
|
||||||
|
from qbh.melody import Melody
|
||||||
|
|
||||||
|
|
||||||
|
def _melody(midis, song_id="m", note_s=0.5) -> Melody:
|
||||||
|
midis = np.asarray(midis, dtype=float)
|
||||||
|
return Melody(midis, np.arange(midis.size) * note_s, np.full(midis.size, note_s * 0.9), song_id)
|
||||||
|
|
||||||
|
|
||||||
|
def test_quantizers():
|
||||||
|
assert list(quantize_magnitude(np.array([0.1, 1.0, 2.0, 4.0, 6.0, 12.0]))) == [0, 1, 2, 3, 4, 5]
|
||||||
|
assert list(quantize_direction(np.array([2.0, 0.0, -2.0]))) == [2, 1, 0]
|
||||||
|
assert list(quantize_rhythm(np.array([0.0, 0.45, -0.9]))) == [0, 1, -2]
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_and_gram_count():
|
||||||
|
index = NgramIndex(cfg=DEFAULT)
|
||||||
|
index.build([_melody([60, 62, 64, 67, 69, 67, 64, 62], "a"),
|
||||||
|
_melody([72, 71, 69, 67, 65], "b")])
|
||||||
|
assert index.n_songs == 2
|
||||||
|
assert index.n_grams() > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_score_is_transposition_invariant():
|
||||||
|
index = NgramIndex(cfg=DEFAULT)
|
||||||
|
base = _melody([60, 62, 64, 67, 69, 67, 64, 62], "a")
|
||||||
|
index.build([base, _melody([72, 71, 69, 67, 65, 64, 62, 60], "b")])
|
||||||
|
|
||||||
|
score_original = index.score(base)
|
||||||
|
score_shifted = index.score(base.transpose(9))
|
||||||
|
assert score_original.get("a", 0) > 0.8
|
||||||
|
assert abs(score_original.get("a", 0) - score_shifted.get("a", 0)) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_candidates_contain_answer():
|
||||||
|
index = NgramIndex(cfg=DEFAULT)
|
||||||
|
target = _melody([60, 62, 64, 67, 69, 71, 72, 71, 69, 67, 64, 62], "target")
|
||||||
|
others = [_melody([60, 60, 67, 67, 69, 69, 67, 67], f"o{i}") for i in range(8)]
|
||||||
|
index.build([target] + others)
|
||||||
|
|
||||||
|
query = target.slice(2, 9).transpose(4)
|
||||||
|
candidates, _ = index.candidates(query)
|
||||||
|
ids = [sid for sid, _ in candidates]
|
||||||
|
assert "target" in ids
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_melody_scores_nothing():
|
||||||
|
index = NgramIndex(cfg=DEFAULT)
|
||||||
|
index.build([_melody([60, 62, 64], "a")])
|
||||||
|
assert index.score(Melody.empty()) == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_load_roundtrip(tmp_path):
|
||||||
|
index = NgramIndex(cfg=DEFAULT)
|
||||||
|
index.build([_melody([60, 62, 64, 67, 69], "a"), _melody([72, 71, 69, 67], "b")])
|
||||||
|
path = tmp_path / "index.json"
|
||||||
|
index.save(path)
|
||||||
|
|
||||||
|
restored = NgramIndex.load(path, DEFAULT)
|
||||||
|
assert restored.n_songs == index.n_songs
|
||||||
|
assert restored.n_grams() == index.n_grams()
|
||||||
|
query = _melody([60, 62, 64, 67], "q")
|
||||||
|
assert restored.score(query) == index.score(query)
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""旋律表示测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT
|
||||||
|
from qbh.melody import Melody, fuse_repeated_notes
|
||||||
|
|
||||||
|
|
||||||
|
def test_intervals_are_transposition_invariant():
|
||||||
|
mel = Melody(np.array([60, 62, 64, 67]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||||
|
shifted = mel.transpose(7)
|
||||||
|
assert np.allclose(mel.intervals(), shifted.intervals())
|
||||||
|
|
||||||
|
|
||||||
|
def test_norm_durs_are_tempo_invariant():
|
||||||
|
mel = Melody(np.array([60, 62, 64]), np.array([0.0, 0.5, 1.0]), np.array([0.5, 0.25, 0.25]))
|
||||||
|
scaled = mel.scaled(1.7)
|
||||||
|
assert np.allclose(mel.norm_durs(), scaled.norm_durs())
|
||||||
|
|
||||||
|
|
||||||
|
def test_contour_direction():
|
||||||
|
mel = Melody(np.array([60, 64, 64, 62]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||||
|
assert mel.contour() == "URD"
|
||||||
|
|
||||||
|
|
||||||
|
def test_contour_transposition_invariant():
|
||||||
|
mel = Melody(np.array([60, 64, 64, 62]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||||
|
assert mel.contour() == mel.transpose(-5).contour()
|
||||||
|
|
||||||
|
|
||||||
|
def test_slice_rebases_time():
|
||||||
|
mel = Melody(np.array([60, 62, 64, 65]), np.arange(4) * 0.5, np.full(4, 0.4))
|
||||||
|
part = mel.slice(1, 3)
|
||||||
|
assert part.n_notes == 2
|
||||||
|
assert part.starts[0] == pytest.approx(0.0)
|
||||||
|
assert np.allclose(part.midis, [62, 64])
|
||||||
|
|
||||||
|
|
||||||
|
def test_slice_out_of_range_is_empty():
|
||||||
|
mel = Melody(np.array([60, 62]), np.array([0.0, 0.5]), np.array([0.4, 0.4]))
|
||||||
|
assert mel.slice(5, 9).is_empty
|
||||||
|
assert mel.slice(1, 1).is_empty
|
||||||
|
|
||||||
|
|
||||||
|
def test_intervals_clipped():
|
||||||
|
mel = Melody(np.array([40, 100]), np.array([0.0, 1.0]), np.array([1.0, 1.0]))
|
||||||
|
assert mel.intervals(clip=12.0)[0] == 12.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_fuse_repeated_notes_merges_same_pitch():
|
||||||
|
mel = Melody(
|
||||||
|
np.array([60.0, 60.05, 60.02, 64.0]),
|
||||||
|
np.array([0.0, 0.5, 1.0, 1.5]),
|
||||||
|
np.array([0.5, 0.5, 0.5, 0.5]),
|
||||||
|
)
|
||||||
|
fused = fuse_repeated_notes(mel, DEFAULT)
|
||||||
|
assert fused.n_notes == 2
|
||||||
|
assert fused.durs[0] == pytest.approx(1.5, abs=1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fuse_repeated_notes_keeps_distinct_pitches():
|
||||||
|
mel = Melody(
|
||||||
|
np.array([60.0, 62.0, 64.0]),
|
||||||
|
np.array([0.0, 0.5, 1.0]),
|
||||||
|
np.array([0.5, 0.5, 0.5]),
|
||||||
|
)
|
||||||
|
assert fuse_repeated_notes(mel, DEFAULT).n_notes == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_fuse_repeated_notes_respects_gap():
|
||||||
|
mel = Melody(
|
||||||
|
np.array([60.0, 60.0]),
|
||||||
|
np.array([0.0, 2.0]), # 间隔 1.5s,远大于阈值
|
||||||
|
np.array([0.5, 0.5]),
|
||||||
|
)
|
||||||
|
assert fuse_repeated_notes(mel, DEFAULT).n_notes == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_json_roundtrip():
|
||||||
|
mel = Melody(np.array([60.5, 62.25]), np.array([0.0, 0.5]), np.array([0.5, 0.5]), "s", "t")
|
||||||
|
restored = Melody.from_json(mel.to_json())
|
||||||
|
assert np.allclose(restored.midis, mel.midis)
|
||||||
|
assert restored.song_id == "s"
|
||||||
|
|
||||||
|
|
||||||
|
def test_from_events_sorts_by_onset():
|
||||||
|
mel = Melody.from_events([(1.0, 0.5, 64.0), (0.0, 0.5, 60.0), (2.0, 0.5, 67.0)])
|
||||||
|
assert np.allclose(mel.midis, [60, 64, 67])
|
||||||
|
assert np.allclose(mel.starts, [0.0, 1.0, 2.0])
|
||||||
|
|
||||||
|
|
||||||
|
def test_mismatched_lengths_raise():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
Melody(np.array([60, 62]), np.array([0.0]), np.array([0.5, 0.5]))
|
||||||
|
|
||||||
|
|
||||||
|
def test_semitone_histogram_counts():
|
||||||
|
mel = Melody(np.array([60.0, 60.4, 62.0]), np.arange(3) * 0.5, np.full(3, 0.4))
|
||||||
|
hist = mel.semitone_histogram()
|
||||||
|
assert hist.sum() == 3
|
||||||
|
assert hist[0] == 2 # 60 和 60.4 都取整到 60
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""MIDI 读写测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.melody import Melody
|
||||||
|
from qbh.midiio import read_midi, read_midi_melody, write_midi
|
||||||
|
|
||||||
|
|
||||||
|
def _melody() -> Melody:
|
||||||
|
midis = np.array([60.0, 62.0, 64.0, 67.0, 69.0])
|
||||||
|
starts = np.array([0.0, 0.5, 1.0, 1.5, 2.0])
|
||||||
|
durs = np.array([0.5, 0.5, 0.5, 0.5, 0.9])
|
||||||
|
return Melody(midis, starts, durs, "roundtrip", "回环测试")
|
||||||
|
|
||||||
|
|
||||||
|
def test_write_read_roundtrip(tmp_path):
|
||||||
|
path = tmp_path / "mel.mid"
|
||||||
|
original = _melody()
|
||||||
|
write_midi(path, original, bpm=120.0)
|
||||||
|
|
||||||
|
midi = read_midi(path)
|
||||||
|
assert midi.tracks
|
||||||
|
melody = read_midi_melody(path)
|
||||||
|
|
||||||
|
assert melody.n_notes == original.n_notes
|
||||||
|
assert np.allclose(melody.midis, original.midis)
|
||||||
|
# 时间分辨率受 PPQ 限制,允许 1/480 拍的误差
|
||||||
|
assert np.max(np.abs(melody.starts - original.starts)) < 0.02
|
||||||
|
assert np.max(np.abs(melody.durs - original.durs)) < 0.02
|
||||||
|
|
||||||
|
|
||||||
|
def test_bpm_is_recovered(tmp_path):
|
||||||
|
path = tmp_path / "fast.mid"
|
||||||
|
write_midi(path, _melody(), bpm=150.0)
|
||||||
|
assert read_midi(path).bpm == pytest.approx(150.0, abs=0.5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_rejects_non_midi(tmp_path):
|
||||||
|
path = tmp_path / "not.mid"
|
||||||
|
path.write_bytes(b"this is not midi at all")
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
read_midi(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_reads_project_midi_library():
|
||||||
|
"""真实 MIDI 曲库应能全部解析出合理旋律。"""
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
midi_dir = Path(__file__).resolve().parent.parent / "data" / "midi"
|
||||||
|
files = sorted(midi_dir.glob("*.mid"))
|
||||||
|
if not files:
|
||||||
|
pytest.skip("未找到 data/midi 曲库")
|
||||||
|
|
||||||
|
for path in files:
|
||||||
|
melody = read_midi_melody(path)
|
||||||
|
assert melody.n_notes >= 4, path.name
|
||||||
|
assert melody.duration > 0.5, path.name
|
||||||
|
# 单声部化之后音高应落在合理音区
|
||||||
|
assert 30.0 < melody.median_pitch < 100.0, path.name
|
||||||
|
|
||||||
|
|
||||||
|
def test_monophonize_keeps_highest_on_overlap():
|
||||||
|
from qbh.midiio import MidiNote, _monophonize
|
||||||
|
|
||||||
|
notes = [
|
||||||
|
MidiNote(60, 0.0, 1.0),
|
||||||
|
MidiNote(67, 0.5, 1.0), # 与前者重叠且更高
|
||||||
|
]
|
||||||
|
reduced = _monophonize(notes)
|
||||||
|
pitches = [n.pitch for n in reduced]
|
||||||
|
assert 67 in pitches
|
||||||
|
assert sum(1 for n in reduced if n.pitch == 60) <= 1
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""音符切分测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.audio import preprocess
|
||||||
|
from qbh.melody import Melody
|
||||||
|
from qbh.notes import segment_notes, smooth_midi
|
||||||
|
from qbh.pitch import extract_pitch
|
||||||
|
from qbh.synth import render_melody
|
||||||
|
|
||||||
|
|
||||||
|
def _melody(midis, note_s=0.5) -> Melody:
|
||||||
|
midis = np.asarray(midis, dtype=float)
|
||||||
|
return Melody(midis, np.arange(midis.size) * note_s, np.full(midis.size, note_s * 0.9))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("timbre", ["song", "hum"])
|
||||||
|
def test_segment_recovers_scale(timbre):
|
||||||
|
truth = _melody([60, 62, 64, 67, 69, 67, 64, 60])
|
||||||
|
audio = render_melody(truth, 16000, timbre=timbre, seed=3)
|
||||||
|
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||||
|
got = segment_notes(track)
|
||||||
|
|
||||||
|
assert got.n_notes == truth.n_notes
|
||||||
|
# 音高逐音对齐(允许 0.3 半音误差)
|
||||||
|
assert np.max(np.abs(got.midis - truth.midis)) < 0.3
|
||||||
|
|
||||||
|
|
||||||
|
def test_segment_fuses_repeated_notes():
|
||||||
|
truth = _melody([60, 60, 60, 62, 64])
|
||||||
|
audio = render_melody(truth, 16000, timbre="hum", seed=5)
|
||||||
|
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||||
|
got = segment_notes(track)
|
||||||
|
# 三个连续同音会被融合成一个(时长累加)
|
||||||
|
assert got.n_notes == 3
|
||||||
|
assert got.midis[0] == pytest.approx(60.0, abs=0.3)
|
||||||
|
assert got.durs[0] > truth.durs[0] * 1.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_segment_empty_audio():
|
||||||
|
track = extract_pitch(np.zeros(16000, dtype=np.float32), 16000)
|
||||||
|
got = segment_notes(track)
|
||||||
|
assert got.is_empty
|
||||||
|
|
||||||
|
|
||||||
|
def test_segment_drops_very_short_notes():
|
||||||
|
truth = _melody([60, 62, 64, 65, 67])
|
||||||
|
truth.durs[2] = 0.02 # 20ms,低于 min_note_ms
|
||||||
|
audio = render_melody(truth, 16000, timbre="song", seed=11)
|
||||||
|
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||||
|
got = segment_notes(track)
|
||||||
|
assert got.n_notes < truth.n_notes
|
||||||
|
|
||||||
|
|
||||||
|
def test_smooth_midi_keeps_nan():
|
||||||
|
values = np.array([60.0, np.nan, 62.0, np.nan, 64.0])
|
||||||
|
out = smooth_midi(values, 3)
|
||||||
|
assert np.isnan(out[1]) and np.isnan(out[3])
|
||||||
|
assert not np.isnan(out[0]) and not np.isnan(out[4])
|
||||||
|
|
||||||
|
|
||||||
|
def test_segment_onset_is_monotonic():
|
||||||
|
truth = _melody([60, 64, 67, 72, 67, 64], note_s=0.6)
|
||||||
|
audio = render_melody(truth, 16000, timbre="hum", seed=13)
|
||||||
|
track = extract_pitch(preprocess(audio, 16000), 16000)
|
||||||
|
got = segment_notes(track)
|
||||||
|
assert np.all(np.diff(got.starts) > 0)
|
||||||
|
assert got.starts[0] == pytest.approx(0.0, abs=1e-6)
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""YIN 基频提取测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.pitch import extract_pitch, hz_to_midi, midi_to_hz
|
||||||
|
|
||||||
|
|
||||||
|
def _tone(freq: float, seconds: float, sr: int = 16000, amp: float = 0.5) -> np.ndarray:
|
||||||
|
t = np.arange(int(sr * seconds)) / sr
|
||||||
|
return (amp * np.sin(2 * np.pi * freq * t)).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def test_midi_hz_roundtrip():
|
||||||
|
for midi in (40.0, 60.0, 69.0, 72.5):
|
||||||
|
assert abs(hz_to_midi(midi_to_hz(np.array([midi])))[0] - midi) < 1e-9
|
||||||
|
assert abs(midi_to_hz(np.array([69.0]))[0] - 440.0) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("freq", [80.0, 110.0, 220.0, 440.0, 660.0, 880.0])
|
||||||
|
def test_pure_tone_pitch_accuracy(freq):
|
||||||
|
track = extract_pitch(_tone(freq, 0.8), 16000)
|
||||||
|
voiced = track.midi[track.voiced]
|
||||||
|
assert voiced.size > 0
|
||||||
|
expected = 69.0 + 12.0 * np.log2(freq / 440.0)
|
||||||
|
# 允许 0.1 半音误差(含抛物线插值残差)
|
||||||
|
assert abs(float(np.median(voiced)) - expected) < 0.1
|
||||||
|
|
||||||
|
|
||||||
|
def test_silence_is_unvoiced():
|
||||||
|
track = extract_pitch(np.zeros(16000, dtype=np.float32), 16000)
|
||||||
|
assert track.voiced.mean() == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_low_level_noise_is_unvoiced():
|
||||||
|
rng = np.random.default_rng(1)
|
||||||
|
track = extract_pitch(rng.normal(0, 1e-6, 16000).astype(np.float32), 16000)
|
||||||
|
assert track.voiced.mean() == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_harmonic_rich_signal_tracks_fundamental():
|
||||||
|
sr = 16000
|
||||||
|
t = np.arange(sr) / sr
|
||||||
|
signal = np.zeros_like(t)
|
||||||
|
for harmonic, amp in ((1, 1.0), (2, 0.4), (3, 0.2), (4, 0.1)):
|
||||||
|
signal += amp * np.sin(2 * np.pi * 110.0 * harmonic * t)
|
||||||
|
signal = (0.4 * signal / np.abs(signal).max()).astype(np.float32)
|
||||||
|
|
||||||
|
track = extract_pitch(signal, sr)
|
||||||
|
voiced = track.midi[track.voiced]
|
||||||
|
assert abs(float(np.median(voiced)) - 45.0) < 0.15 # A2 = MIDI 45
|
||||||
|
|
||||||
|
|
||||||
|
def test_vibrato_tracked_within_reasonable_band():
|
||||||
|
sr = 16000
|
||||||
|
t = np.arange(sr) / sr
|
||||||
|
f0 = 440.0 * 2 ** ((0.3 * np.sin(2 * np.pi * 5 * t)) / 12.0)
|
||||||
|
phase = 2 * np.pi * np.cumsum(f0) / sr
|
||||||
|
track = extract_pitch((0.5 * np.sin(phase)).astype(np.float32), sr)
|
||||||
|
voiced = track.midi[track.voiced]
|
||||||
|
assert abs(float(np.median(voiced)) - 69.0) < 0.1
|
||||||
|
assert 0.05 < float(np.std(voiced)) < 0.5 # 确实跟踪到了颤音
|
||||||
|
|
||||||
|
|
||||||
|
def test_confidence_high_for_clean_tone():
|
||||||
|
track = extract_pitch(_tone(440.0, 0.5), 16000)
|
||||||
|
assert float(np.median(track.conf[track.voiced])) > 0.9
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_and_short_input():
|
||||||
|
track = extract_pitch(np.zeros(0, dtype=np.float32), 16000)
|
||||||
|
assert track.n_frames == 0
|
||||||
|
short = extract_pitch(np.zeros(100, dtype=np.float32), 16000)
|
||||||
|
assert short.voiced.size == 0
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""检索引擎端到端测试(合成曲库 + 合成哼唱)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.config import DEFAULT
|
||||||
|
from qbh.search import SearchEngine
|
||||||
|
from qbh.synth import render_melody
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def engine(tiny_library):
|
||||||
|
return SearchEngine(tiny_library, DEFAULT)
|
||||||
|
|
||||||
|
|
||||||
|
def test_index_built_from_library(engine, tiny_library):
|
||||||
|
assert engine.index.n_songs == tiny_library.count() == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_melody_retrieves_itself(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_a")
|
||||||
|
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||||
|
assert result.hits[0].song_id == "m_a"
|
||||||
|
assert result.hits[0].score > 0.9
|
||||||
|
|
||||||
|
|
||||||
|
def test_transposed_melody_still_retrieved(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_b").transpose(7)
|
||||||
|
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||||
|
assert result.hits[0].song_id == "m_b"
|
||||||
|
|
||||||
|
|
||||||
|
def test_fragment_retrieval(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_a").slice(1, 7).transpose(-3)
|
||||||
|
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||||
|
assert result.hits[0].song_id == "m_a"
|
||||||
|
|
||||||
|
|
||||||
|
def test_audio_pipeline_retrieves_rendered_hum(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_a")
|
||||||
|
audio = render_melody(melody.transpose(4), 16000, timbre="hum", seed=21)
|
||||||
|
result, track = engine.search_audio(audio, 16000, top_k=3)
|
||||||
|
assert track.voiced_ratio() > 0.5
|
||||||
|
assert result.hits[0].song_id == "m_a"
|
||||||
|
|
||||||
|
|
||||||
|
def test_result_serialization(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_a")
|
||||||
|
result = engine.search_melody(melody, top_k=2, with_path=True)
|
||||||
|
payload = result.to_dict()
|
||||||
|
assert payload["n_songs"] == 3
|
||||||
|
assert payload["hits"]
|
||||||
|
assert "query" in payload
|
||||||
|
hit = payload["hits"][0]
|
||||||
|
for key in ("song_id", "title", "score", "dtw_sim", "index_sim", "shift", "path"):
|
||||||
|
assert key in hit
|
||||||
|
assert payload["query"]["contour"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_hit_exposes_matched_segment(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_a")
|
||||||
|
result = engine.search_melody(melody, top_k=1, with_path=True)
|
||||||
|
hit = result.hits[0]
|
||||||
|
assert hit.target_end_s >= hit.target_start_s
|
||||||
|
assert hit.target_note_end >= hit.target_note_start
|
||||||
|
|
||||||
|
|
||||||
|
def test_coarse_candidates_include_answer(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_c").transpose(5)
|
||||||
|
candidates = [sid for sid, _ in engine.coarse_candidates(melody)]
|
||||||
|
assert "m_c" in candidates
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_melody_returns_no_hits(engine):
|
||||||
|
from qbh.melody import Melody
|
||||||
|
|
||||||
|
result = engine.search_melody(Melody.empty(), top_k=3)
|
||||||
|
assert result.hits == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_elapsed_ms_is_reported(engine, tiny_library):
|
||||||
|
melody = tiny_library.get_melody("m_a")
|
||||||
|
result = engine.search_melody(melody, top_k=3, with_path=False)
|
||||||
|
assert result.elapsed_ms >= 0.0
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""SQLite 持久化层测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from qbh.melody import Melody
|
||||||
|
from qbh.store import SongRecord, Store, hash_password, verify_password
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def store(tmp_path):
|
||||||
|
s = Store(tmp_path / "test.db")
|
||||||
|
yield s
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_song_crud(store):
|
||||||
|
record = SongRecord(id="s1", title="测试曲", origin="测试", tags=("a", "b"),
|
||||||
|
source="test", n_notes=10, duration=5.0, median_pitch=60.0)
|
||||||
|
store.upsert_song(record)
|
||||||
|
assert store.count_songs() == 1
|
||||||
|
|
||||||
|
loaded = store.get_song("s1")
|
||||||
|
assert loaded is not None
|
||||||
|
assert loaded.title == "测试曲"
|
||||||
|
assert loaded.tags == ("a", "b")
|
||||||
|
|
||||||
|
record.title = "改名"
|
||||||
|
store.upsert_song(record)
|
||||||
|
assert store.get_song("s1").title == "改名"
|
||||||
|
|
||||||
|
assert store.delete_song("s1") is True
|
||||||
|
assert store.count_songs() == 0
|
||||||
|
assert store.get_song("s1") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_melody_storage(store):
|
||||||
|
mel = Melody(np.array([60.0, 62.0]), np.array([0.0, 0.5]), np.array([0.5, 0.5]), "s1", "曲")
|
||||||
|
store.set_melody(mel)
|
||||||
|
loaded = store.get_melody("s1")
|
||||||
|
assert loaded is not None
|
||||||
|
assert np.allclose(loaded.midis, mel.midis)
|
||||||
|
|
||||||
|
store.set_melodies([mel])
|
||||||
|
assert len(store.all_melodies()) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_password_hashing():
|
||||||
|
salt, digest = hash_password("secret123")
|
||||||
|
assert verify_password("secret123", salt, digest)
|
||||||
|
assert not verify_password("wrong", salt, digest)
|
||||||
|
# 相同密码、不同盐 → 不同哈希
|
||||||
|
salt2, digest2 = hash_password("secret123")
|
||||||
|
assert digest != digest2
|
||||||
|
|
||||||
|
|
||||||
|
def test_user_lifecycle(store):
|
||||||
|
ok, message = store.create_user("alice", "password1", "a@example.com")
|
||||||
|
assert ok, message
|
||||||
|
|
||||||
|
# 重复注册
|
||||||
|
ok, message = store.create_user("alice", "password2")
|
||||||
|
assert not ok and "已存在" in message
|
||||||
|
|
||||||
|
# 密码太短
|
||||||
|
ok, message = store.create_user("bob", "123")
|
||||||
|
assert not ok and "密码" in message
|
||||||
|
|
||||||
|
user_id = store.verify_user("alice", "password1")
|
||||||
|
assert user_id is not None
|
||||||
|
assert store.verify_user("alice", "wrong") is None
|
||||||
|
assert store.verify_user("nobody", "password1") is None
|
||||||
|
|
||||||
|
info = store.get_user(user_id)
|
||||||
|
assert info["username"] == "alice"
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_lifecycle(store):
|
||||||
|
ok, _ = store.create_user("carol", "password1")
|
||||||
|
assert ok
|
||||||
|
user_id = store.verify_user("carol", "password1")
|
||||||
|
|
||||||
|
store.add_history(
|
||||||
|
user_id=user_id, source="mic", query_notes=12, query_melody="{}",
|
||||||
|
top_song="s1", top_title="曲一", top_score=0.9, elapsed_ms=50.0,
|
||||||
|
results=[{"song_id": "s1", "score": 0.9}],
|
||||||
|
)
|
||||||
|
store.add_history(
|
||||||
|
user_id=None, source="demo", query_notes=8, query_melody="{}",
|
||||||
|
top_song="s2", top_title="曲二", top_score=0.8, elapsed_ms=40.0, results=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(store.list_history()) == 2
|
||||||
|
mine = store.list_history(user_id=user_id)
|
||||||
|
assert len(mine) == 1
|
||||||
|
assert mine[0]["top_song"] == "s1"
|
||||||
|
assert mine[0]["results"][0]["song_id"] == "s1"
|
||||||
|
|
||||||
|
assert store.clear_history(user_id=user_id) == 1
|
||||||
|
assert len(store.list_history()) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_meta_roundtrip(store):
|
||||||
|
store.set_meta("k", {"a": 1})
|
||||||
|
assert store.get_meta("k") == {"a": 1}
|
||||||
|
assert store.get_meta("missing", default=42) == 42
|
||||||
|
|
||||||
|
|
||||||
|
def test_persistence_across_connections(tmp_path):
|
||||||
|
path = tmp_path / "persist.db"
|
||||||
|
with Store(path) as first:
|
||||||
|
first.upsert_song(SongRecord(id="x", title="持久化"))
|
||||||
|
with Store(path) as second:
|
||||||
|
assert second.get_song("x").title == "持久化"
|
||||||
Reference in New Issue
Block a user