Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)

This commit is contained in:
2026-09-08 17:48:49 +08:00
commit 4b9766db02
83 changed files with 17965 additions and 0 deletions
+558
View File
@@ -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:]))