"""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"))}