Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
+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; }
|
||||
Reference in New Issue
Block a user