_webui.py 24.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
"""内嵌 WebUI HTML,供 GET /ui 直接返回。"""

HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>去重 API 测试</title>
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
    background: #f0f2f5;
    color: #333;
    min-height: 100vh;
    padding: 32px 16px;
  }
  h1 {
    text-align: center;
    font-size: 22px;
    font-weight: 600;
    margin-bottom: 24px;
    color: #1a1a2e;
  }
  .card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,.08);
    max-width: 740px;
    margin: 0 auto;
    overflow: hidden;
  }
  /* Tabs */
  .tabs {
    display: flex;
    border-bottom: 1px solid #e8e8e8;
    background: #fafafa;
  }
  .tab-btn {
    flex: 1;
    padding: 14px 8px;
    border: none;
    background: none;
    font-size: 14px;
    color: #888;
    cursor: pointer;
    transition: color .2s, border-bottom .2s;
    border-bottom: 3px solid transparent;
    font-weight: 500;
  }
  .tab-btn.active {
    color: #4361ee;
    border-bottom-color: #4361ee;
    background: #fff;
  }
  .tab-btn:hover:not(.active) { color: #555; }
  /* Panels */
  .panel { display: none; padding: 28px 32px 32px; }
  .panel.active { display: block; }
  /* Form */
  .field { margin-bottom: 18px; }
  label {
    display: block;
    font-size: 13px;
    font-weight: 600;
    color: #555;
    margin-bottom: 6px;
  }
  label .hint {
    font-weight: 400;
    color: #aaa;
    margin-left: 4px;
  }
  input[type=text], input[type=number] {
    width: 100%;
    padding: 9px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 7px;
    font-size: 14px;
    transition: border-color .2s;
    outline: none;
  }
  input:focus { border-color: #4361ee; box-shadow: 0 0 0 3px rgba(67,97,238,.1); }
  .upload-area {
    border: 2px dashed #d9d9d9;
    border-radius: 7px;
    text-align: center;
    padding: 22px 12px;
    cursor: pointer;
    transition: border-color .2s, background .2s;
    position: relative;
  }
  .upload-area:hover, .upload-area.dragover {
    border-color: #4361ee;
    background: #f5f7ff;
  }
  .upload-area input[type=file] {
    position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%;
  }
  .upload-icon { font-size: 28px; margin-bottom: 6px; line-height: 1; }
  .upload-area p { font-size: 13px; color: #888; }
  .upload-area .file-name { color: #4361ee; font-weight: 600; margin-top: 4px; font-size: 13px; }
  .or-divider {
    text-align: center;
    color: #bbb;
    font-size: 12px;
    margin: 10px 0;
    position: relative;
  }
  .or-divider::before, .or-divider::after {
    content: "";
    position: absolute;
    top: 50%;
    width: 42%;
    height: 1px;
    background: #e8e8e8;
  }
  .or-divider::before { left: 0; }
  .or-divider::after { right: 0; }
  .submit-btn {
    width: 100%;
    padding: 11px;
    background: #4361ee;
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 600;
    cursor: pointer;
    transition: background .2s, opacity .2s;
    margin-top: 4px;
  }
  .submit-btn:hover { background: #3451d1; }
  .submit-btn:disabled { opacity: .6; cursor: not-allowed; }
  /* Result */
  .result-box {
    margin-top: 22px;
    display: none;
  }
  .result-box.visible { display: block; }
  .result-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 12px;
  }
  .badge {
    display: inline-block;
    padding: 3px 12px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 700;
  }
  .badge.dup { background: #fff0f0; color: #d62828; }
  .badge.new { background: #f0fff4; color: #2d6a4f; }
  .badge.review { background: #fffbe6; color: #9c6a00; }
  .result-kv { background: #f8f9fc; border-radius: 8px; padding: 14px 16px; }
  .result-kv table { width: 100%; border-collapse: collapse; }
  .result-kv td { padding: 5px 0; font-size: 13px; vertical-align: top; }
  .result-kv td:first-child { color: #888; width: 110px; white-space: nowrap; }
  .result-kv td:last-child { color: #333; word-break: break-all; }
  .candidates-list { margin-top: 14px; }
  .candidates-list h4 { font-size: 13px; color: #888; margin-bottom: 8px; }
  .cand-row {
    display: flex; align-items: center; gap: 10px;
    background: #f8f9fc; border-radius: 7px;
    padding: 8px 12px; margin-bottom: 6px; font-size: 13px;
  }
  .cand-sim {
    font-weight: 700;
    color: #4361ee;
    min-width: 52px;
  }
  .cand-src {
    background: #eef0ff; color: #4361ee;
    border-radius: 4px; padding: 1px 7px;
    font-size: 11px; font-weight: 600;
  }
  .error-box {
    margin-top: 16px;
    background: #fff0f0;
    border-radius: 8px;
    padding: 12px 16px;
    color: #d62828;
    font-size: 13px;
    display: none;
  }
  .error-box.visible { display: block; }
  .spinner {
    display: inline-block;
    width: 16px; height: 16px;
    border: 2px solid #fff;
    border-top-color: transparent;
    border-radius: 50%;
    animation: spin .7s linear infinite;
    vertical-align: middle;
    margin-right: 6px;
  }
  @keyframes spin { to { transform: rotate(360deg); } }
  .conf-bar-wrap { display: flex; align-items: center; gap: 8px; }
  .conf-bar {
    flex: 1; height: 6px; background: #e8e8e8; border-radius: 3px; overflow: hidden;
  }
  .conf-bar-fill { height: 100%; background: #4361ee; border-radius: 3px; transition: width .4s; }
  /* Preview button */
  .btn-preview {
    border: 1px solid #4361ee; background: none; color: #4361ee;
    border-radius: 5px; padding: 2px 10px; font-size: 12px; cursor: pointer;
    transition: background .15s, color .15s; white-space: nowrap;
  }
  .btn-preview:hover { background: #4361ee; color: #fff; }
  .btn-preview:disabled { opacity: .5; cursor: not-allowed; }
  /* Modal */
  .modal-mask {
    display: none; position: fixed; inset: 0;
    background: rgba(0,0,0,.45); z-index: 1000;
    align-items: center; justify-content: center;
  }
  .modal-mask.open { display: flex; }
  .modal {
    background: #fff; border-radius: 14px;
    width: min(680px, 96vw); max-height: 82vh;
    display: flex; flex-direction: column;
    box-shadow: 0 8px 40px rgba(0,0,0,.22);
  }
  .modal-head {
    padding: 16px 20px 14px; border-bottom: 1px solid #f0f0f0;
    display: flex; align-items: center; gap: 10px;
  }
  .modal-head h3 { flex: 1; font-size: 15px; color: #222; }
  .modal-close {
    border: none; background: none; font-size: 22px; color: #aaa;
    cursor: pointer; line-height: 1; padding: 0 4px;
  }
  .modal-close:hover { color: #555; }
  .modal-body { padding: 18px 20px; overflow-y: auto; flex: 1; }
  .lyric-meta { font-size: 13px; color: #888; margin-bottom: 12px; }
  .lyric-meta strong { color: #333; }
  .lyric-text {
    white-space: pre-wrap; font-size: 14px; line-height: 1.8;
    color: #333; background: #f8f9fc; border-radius: 8px;
    padding: 14px 16px; max-height: 52vh; overflow-y: auto;
  }
  audio { width: 100%; margin-top: 6px; border-radius: 8px; }
  .no-url-tip { font-size: 13px; color: #aaa; text-align: center; padding: 20px 0; }
</style>
</head>
<body>
<h1>去重 API 测试</h1>
<div class="card">
  <div class="tabs">
    <button class="tab-btn active" onclick="switchTab('lyric', this)">词查重</button>
    <button class="tab-btn" onclick="switchTab('ingest', this)">曲入库</button>
    <button class="tab-btn" onclick="switchTab('check', this)">曲查重</button>
  </div>

  <!-- 歌词去重 -->
  <div id="panel-lyric" class="panel active">
    <form id="form-lyric" onsubmit="submitLyric(event)">
      <div class="field">
        <label>歌词文件 <span class="hint">(.lrc / .txt)</span></label>
        <div class="upload-area" id="drop-lyric"
             ondragover="onDragOver(event, this)" ondragleave="onDragLeave(this)" ondrop="onDrop(event, 'file-lyric', this)">
          <input type="file" id="file-lyric" accept=".lrc,.txt" onchange="showFileName('file-lyric','name-lyric')">
          <div class="upload-icon">🎵</div>
          <p>拖拽文件到此处,或点击选择</p>
          <div class="file-name" id="name-lyric"></div>
        </div>
      </div>
      <div class="or-divider">或直接填写 URL</div>
      <div class="field">
        <label>歌词文件 URL</label>
        <input type="text" id="lyric-url" placeholder="https://example.com/song.lrc">
      </div>
      <div style="display:flex;gap:12px;">
        <div class="field" style="flex:1">
          <label>歌曲标题 <span class="hint">(可选)</span></label>
          <input type="text" id="lyric-title" placeholder="夜曲">
        </div>
        <div class="field" style="flex:1">
          <label>歌手 <span class="hint">(可选)</span></label>
          <input type="text" id="lyric-artist" placeholder="周杰伦">
        </div>
      </div>
      <button type="submit" class="submit-btn" id="btn-lyric">检测歌词</button>
    </form>
    <div class="error-box" id="err-lyric"></div>
    <div class="result-box" id="res-lyric"></div>
  </div>

  <!-- 曲入库 -->
  <div id="panel-ingest" class="panel">
    <form id="form-ingest" onsubmit="submitIngest(event)">
      <div class="field">
        <label>歌曲 ID</label>
        <input type="number" id="ingest-song-id" placeholder="12345" min="1" required>
      </div>
      <div class="field">
        <label>音频文件 <span class="hint">(mp3 / wav / flac 等)</span></label>
        <div class="upload-area" id="drop-ingest"
             ondragover="onDragOver(event, this)" ondragleave="onDragLeave(this)" ondrop="onDrop(event, 'file-ingest', this)">
          <input type="file" id="file-ingest" accept=".mp3,.wav,.flac,.aac,.ogg,.m4a,.opus" onchange="showFileName('file-ingest','name-ingest')">
          <div class="upload-icon">🎶</div>
          <p>拖拽文件到此处,或点击选择</p>
          <div class="file-name" id="name-ingest"></div>
        </div>
      </div>
      <div class="or-divider">或直接填写 URL</div>
      <div class="field">
        <label>音频文件 URL</label>
        <input type="text" id="ingest-url" placeholder="https://example.com/song.mp3">
      </div>
      <button type="submit" class="submit-btn" id="btn-ingest">写入曲库</button>
    </form>
    <div class="error-box" id="err-ingest"></div>
    <div class="result-box" id="res-ingest"></div>
  </div>

  <!-- 曲查询 -->
  <div id="panel-check" class="panel">
    <form id="form-check" onsubmit="submitCheck(event)">
      <div class="field">
        <label>歌曲 ID <span class="hint">(可选,填写后若不重复将自动入库)</span></label>
        <input type="number" id="check-song-id" placeholder="12345(不填则仅查询,不入库)" min="1">
      </div>
      <div class="field">
        <label>音频文件 <span class="hint">(mp3 / wav / flac 等)</span></label>
        <div class="upload-area" id="drop-check"
             ondragover="onDragOver(event, this)" ondragleave="onDragLeave(this)" ondrop="onDrop(event, 'file-check', this)">
          <input type="file" id="file-check" accept=".mp3,.wav,.flac,.aac,.ogg,.m4a,.opus" onchange="showFileName('file-check','name-check')">
          <div class="upload-icon">🔍</div>
          <p>拖拽文件到此处,或点击选择</p>
          <div class="file-name" id="name-check"></div>
        </div>
      </div>
      <div class="or-divider">或直接填写 URL</div>
      <div class="field">
        <label>音频文件 URL</label>
        <input type="text" id="check-url" placeholder="https://example.com/query.mp3">
      </div>
      <div class="field">
        <label>召回候选数量 <span class="hint">(top_k,默认 100)</span></label>
        <input type="number" id="check-topk" value="100" min="1" max="500">
      </div>
      <button type="submit" class="submit-btn" id="btn-check">检测是否重复</button>
    </form>
    <div class="error-box" id="err-check"></div>
    <div class="result-box" id="res-check"></div>
  </div>
</div>

<!-- 歌词预览弹窗 -->
<div class="modal-mask" id="modal-lyric" onclick="closeModal('modal-lyric')">
  <div class="modal" onclick="event.stopPropagation()">
    <div class="modal-head">
      <h3 id="modal-lyric-title">歌词预览</h3>
      <button class="modal-close" onclick="closeModal('modal-lyric')">×</button>
    </div>
    <div class="modal-body">
      <div class="lyric-meta" id="modal-lyric-meta"></div>
      <div class="lyric-text" id="modal-lyric-text"></div>
    </div>
  </div>
</div>

<!-- 音频预览弹窗 -->
<div class="modal-mask" id="modal-audio" onclick="closeModal('modal-audio')">
  <div class="modal" onclick="event.stopPropagation()">
    <div class="modal-head">
      <h3 id="modal-audio-title">音频预览</h3>
      <button class="modal-close" onclick="closeModal('modal-audio')">×</button>
    </div>
    <div class="modal-body" id="modal-audio-body"></div>
  </div>
</div>

<script>
function switchTab(name, btn) {
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
  btn.classList.add('active');
  document.getElementById('panel-' + name).classList.add('active');
}

function showFileName(inputId, nameId) {
  const f = document.getElementById(inputId).files[0];
  document.getElementById(nameId).textContent = f ? f.name : '';
}

function onDragOver(e, el) { e.preventDefault(); el.classList.add('dragover'); }
function onDragLeave(el) { el.classList.remove('dragover'); }
function onDrop(e, inputId, el) {
  e.preventDefault(); el.classList.remove('dragover');
  const dt = e.dataTransfer;
  if (dt.files.length) {
    const input = document.getElementById(inputId);
    input.files = dt.files;
    input.dispatchEvent(new Event('change'));
  }
}

function setLoading(btnId, loading) {
  const btn = document.getElementById(btnId);
  if (loading) {
    btn._orig = btn.innerHTML;
    btn.innerHTML = '<span class="spinner"></span>处理中...';
    btn.disabled = true;
  } else {
    btn.innerHTML = btn._orig;
    btn.disabled = false;
  }
}

function showError(id, msg) {
  const el = document.getElementById(id);
  el.textContent = msg;
  el.classList.add('visible');
}
function clearError(id) { document.getElementById(id).classList.remove('visible'); }

// -------- 歌词去重 --------
async function submitLyric(e) {
  e.preventDefault();
  clearError('err-lyric');
  document.getElementById('res-lyric').classList.remove('visible');

  const file = document.getElementById('file-lyric').files[0];
  const url  = document.getElementById('lyric-url').value.trim();
  if (!file && !url) { showError('err-lyric', '请上传歌词文件或填写 URL'); return; }

  setLoading('btn-lyric', true);
  try {
    let data;
    if (file) {
      const fd = new FormData();
      fd.append('file', file);
      const title = document.getElementById('lyric-title').value.trim();
      const artist = document.getElementById('lyric-artist').value.trim();
      if (title)  fd.append('title', title);
      if (artist) fd.append('artist', artist);
      const resp = await fetch('/api/v1/lyric/check-upload', { method: 'POST', body: fd });
      data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || resp.statusText);
    } else {
      const body = { url, title: document.getElementById('lyric-title').value.trim() || null, artist: document.getElementById('lyric-artist').value.trim() || null };
      const resp = await fetch('/api/v1/check', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body) });
      data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || resp.statusText);
    }
    renderLyricResult(data);
  } catch(err) {
    showError('err-lyric', err.message);
  } finally {
    setLoading('btn-lyric', false);
  }
}

function renderLyricResult(d) {
  const conf = typeof d.confidence === 'number' ? d.confidence : null;
  const decisionLabel = { duplicate: '重复', new: '不重复', review: '待人工审核' };
  const badgeClass = d.duplicate ? 'dup' : (d.decision === 'review' ? 'review' : 'new');
  const confBar = conf !== null ? `
    <div class="conf-bar-wrap">
      <div class="conf-bar"><div class="conf-bar-fill" style="width:${(conf*100).toFixed(1)}%"></div></div>
      <span style="font-size:12px;color:#888;min-width:40px">${(conf*100).toFixed(1)}%</span>
    </div>` : '—';
  // record_ids:每条旁边加「查看歌词」按钮
  let idsHtml = '—';
  if (Array.isArray(d.record_ids) && d.record_ids.length) {
    idsHtml = d.record_ids.map(id => `
      <span style="display:inline-flex;align-items:center;gap:5px;margin:2px 0">
        <code style="font-size:11px;background:#f0f0f0;padding:1px 6px;border-radius:3px">${id}</code>
        <button class="btn-preview" onclick="previewLyric(this,'${id.replace(/'/g,"\\'")}')">查看歌词</button>
      </span>`).join('<br>');
  }
  const box = document.getElementById('res-lyric');
  box.innerHTML = `
    <div class="result-header">
      <span style="font-size:13px;color:#888">检测结果</span>
      <span class="badge ${badgeClass}">${decisionLabel[d.decision] || d.decision || (d.duplicate ? '重复' : '不重复')}</span>
    </div>
    <div class="result-kv">
      <table>
        <tr><td>是否重复</td><td>${d.duplicate ? '是' : '否'}</td></tr>
        <tr><td>决策</td><td>${d.decision || '—'}</td></tr>
        <tr><td>置信度</td><td>${confBar}</td></tr>
        <tr><td>原因</td><td>${d.reason || '—'}</td></tr>
        <tr><td>匹配 ID</td><td>${idsHtml}</td></tr>
      </table>
    </div>`;
  box.classList.add('visible');
}

// -------- 曲入库 --------
async function submitIngest(e) {
  e.preventDefault();
  clearError('err-ingest');
  document.getElementById('res-ingest').classList.remove('visible');

  const songId = document.getElementById('ingest-song-id').value;
  if (!songId) { showError('err-ingest', '请填写歌曲 ID'); return; }

  const file = document.getElementById('file-ingest').files[0];
  const url  = document.getElementById('ingest-url').value.trim();
  if (!file && !url) { showError('err-ingest', '请上传音频文件或填写 URL'); return; }

  setLoading('btn-ingest', true);
  try {
    let data;
    if (file) {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('song_id', songId);
      const resp = await fetch('/api/v1/rhythm/ingest-upload', { method: 'POST', body: fd });
      data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || resp.statusText);
    } else {
      const resp = await fetch('/api/v1/rhythm/ingest', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ song_id: parseInt(songId), url }) });
      data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || resp.statusText);
    }
    renderIngestResult(data);
  } catch(err) {
    showError('err-ingest', err.message);
  } finally {
    setLoading('btn-ingest', false);
  }
}

function renderIngestResult(d) {
  const box = document.getElementById('res-ingest');
  box.innerHTML = `
    <div class="result-header">
      <span style="font-size:13px;color:#888">入库结果</span>
      <span class="badge ${d.success ? 'new' : 'dup'}">${d.success ? '成功' : '失败'}</span>
    </div>
    <div class="result-kv">
      <table>
        <tr><td>歌曲 ID</td><td>${d.song_id}</td></tr>
        <tr><td>状态</td><td>${d.success ? '入库成功' : '入库失败'}</td></tr>
        <tr><td>信息</td><td>${d.message || '—'}</td></tr>
      </table>
    </div>`;
  box.classList.add('visible');
}

// -------- 曲查询 --------
async function submitCheck(e) {
  e.preventDefault();
  clearError('err-check');
  document.getElementById('res-check').classList.remove('visible');

  const file   = document.getElementById('file-check').files[0];
  const url    = document.getElementById('check-url').value.trim();
  const topk   = parseInt(document.getElementById('check-topk').value) || 100;
  const songId = document.getElementById('check-song-id').value.trim();
  if (!file && !url) { showError('err-check', '请上传音频文件或填写 URL'); return; }

  setLoading('btn-check', true);
  try {
    let data;
    if (file) {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('top_k', topk);
      if (songId) fd.append('song_id', songId);
      const resp = await fetch('/api/v1/rhythm/check-upload', { method: 'POST', body: fd });
      data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || resp.statusText);
    } else {
      const body = { url, top_k: topk };
      if (songId) body.song_id = parseInt(songId);
      const resp = await fetch('/api/v1/rhythm/check', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body) });
      data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || resp.statusText);
    }
    renderCheckResult(data);
  } catch(err) {
    showError('err-check', err.message);
  } finally {
    setLoading('btn-check', false);
  }
}

function renderCheckResult(d) {
  const candidates = d.candidates || [];
  let candHtml = '';
  if (candidates.length) {
    const rows = candidates.slice(0, 20).map((c, i) =>
      `<div class="cand-row">
        <span style="color:#aaa;min-width:20px;font-size:12px">#${i+1}</span>
        <span style="flex:1">song_id <strong>${c.song_id}</strong></span>
        <span class="cand-sim">${(c.similarity * 100).toFixed(2)}%</span>
        <span class="cand-src">${c.source}</span>
        <button class="btn-preview" onclick="previewAudio(this,${c.song_id})">▶ 播放</button>
      </div>`
    ).join('');
    const more = candidates.length > 20 ? `<div style="font-size:12px;color:#aaa;margin-top:6px">共 ${candidates.length} 条,仅展示前 20 条</div>` : '';
    candHtml = `<div class="candidates-list"><h4>候选结果</h4>${rows}${more}</div>`;
  }
  const ingestBadge = d.auto_ingested
    ? `<span class="badge new" style="margin-left:6px">已自动入库</span>` : '';
  const box = document.getElementById('res-check');
  box.innerHTML = `
    <div class="result-header">
      <span style="font-size:13px;color:#888">检测结果</span>
      <span class="badge ${d.duplicate ? 'dup' : 'new'}">${d.duplicate ? '重复' : '不重复'}</span>
      ${ingestBadge}
    </div>
    <div class="result-kv">
      <table><tr><td>是否重复</td><td>${d.duplicate ? '是' : '否'}</td></tr></table>
    </div>
    ${candHtml}`;
  box.classList.add('visible');
}

// -------- 预览弹窗 --------
function openModal(id) { document.getElementById(id).classList.add('open'); }
function closeModal(id) {
  document.getElementById(id).classList.remove('open');
  // 停止音频播放
  const audio = document.querySelector('#modal-audio audio');
  if (audio) { audio.pause(); audio.src = ''; }
}

async function previewLyric(btn, recordId) {
  btn.disabled = true;
  try {
    const resp = await fetch(`/api/v1/lyric/preview?record_id=${encodeURIComponent(recordId)}`);
    const d = await resp.json();
    if (!resp.ok) { alert(d.detail || '加载失败'); return; }
    document.getElementById('modal-lyric-title').textContent =
      (d.title ? d.title : '歌词预览') + (d.artist ? ' — ' + d.artist : '');
    document.getElementById('modal-lyric-meta').innerHTML =
      `<strong>record_id:</strong>${recordId}` +
      (d.title  ? ` <strong>标题:</strong>${d.title}`  : '') +
      (d.artist ? ` <strong>歌手:</strong>${d.artist}` : '');
    document.getElementById('modal-lyric-text').textContent = d.text || '(无内容)';
    openModal('modal-lyric');
  } catch(e) { alert('加载失败:' + e.message); }
  finally { btn.disabled = false; }
}

async function previewAudio(btn, songId) {
  btn.disabled = true;
  try {
    const resp = await fetch(`/api/v1/rhythm/preview?song_id=${songId}`);
    const d = await resp.json();
    if (!resp.ok) { alert(d.detail || '加载失败'); return; }
    document.getElementById('modal-audio-title').textContent = `song_id: ${songId}`;
    const body = document.getElementById('modal-audio-body');
    if (d.audio_url) {
      body.innerHTML = `<audio controls autoplay src="${d.audio_url}"></audio>
        <div style="font-size:12px;color:#aaa;margin-top:10px;word-break:break-all">${d.audio_url}</div>`;
    } else {
      body.innerHTML = `<div class="no-url-tip">该音频通过本地文件上传入库,无可播放的 URL</div>`;
    }
    openModal('modal-audio');
  } catch(e) { alert('加载失败:' + e.message); }
  finally { btn.disabled = false; }
}
</script>
</body>
</html>
"""