/* 基于旋律的音乐哼唱检索系统 —— 前端逻辑(原生 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 =
`示范查询:${demo.answer_title} · 移调 ${demo.shift > 0 ? '+' : ''}${demo.shift} 半音 · ` +
`速度 ${demo.tempo}× · 信噪比 ${demo.snr_db} dB · 片段 ${demo.n_notes} 音
` +
(hit ? '✅ 第 1 名命中' : (demo.rank ? `⚠️ 命中排在第 ${demo.rank} 名` : '❌ 未进入 Top-K')) +
(demo.audio_url ? ` · 播放查询音频` : '');
} 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 = '
识别与检索中…
'; 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 = '生成机器哼唱并检索中…
'; 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 = '