233 lines
8.3 KiB
Python
233 lines
8.3 KiB
Python
"""检索引擎:两级检索 + 分数融合。
|
|
|
|
**第一级(粗召回)** 用 :mod:`qbh.index` 的多码本倒排索引,把候选从整库缩到
|
|
几十首。**第二级(精排)** 对候选逐个做子序列 DTW + 移调搜索。最终分数是两者
|
|
的加权和:
|
|
|
|
score = w_dtw · exp(−λ·平均代价) + w_index · 归一化重叠分
|
|
|
|
之所以不只用 DTW:索引分能区分「音程走向一致但细节不同」的近邻曲目;
|
|
之所以不只用索引分:索引只看局部 n-gram 统计,无法判断整体旋律是否连续对齐。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import numpy as np
|
|
|
|
from .audio import preprocess, read_audio
|
|
from .config import DEFAULT, Config
|
|
from .dtw import align
|
|
from .index import NgramIndex
|
|
from .library import Library
|
|
from .melody import Melody, fuse_repeated_notes
|
|
from .notes import segment_notes
|
|
from .pitch import extract_pitch
|
|
|
|
__all__ = ["Hit", "SearchResult", "SearchEngine"]
|
|
|
|
|
|
@dataclass
|
|
class Hit:
|
|
"""一条检索结果。"""
|
|
|
|
song_id: str
|
|
title: str
|
|
score: float
|
|
dtw_sim: float
|
|
index_sim: float
|
|
shift: float
|
|
target_start_s: float
|
|
target_end_s: float
|
|
target_note_start: int
|
|
target_note_end: int
|
|
origin: str = ""
|
|
tags: tuple[str, ...] = ()
|
|
has_audio: bool = False
|
|
path: list[tuple[int, int]] = field(default_factory=list)
|
|
|
|
def to_dict(self, *, include_path: bool = True) -> dict[str, Any]:
|
|
out = {
|
|
"song_id": self.song_id,
|
|
"title": self.title,
|
|
"score": round(self.score, 4),
|
|
"dtw_sim": round(self.dtw_sim, 4),
|
|
"index_sim": round(self.index_sim, 4),
|
|
"shift": round(self.shift, 2),
|
|
"target_start_s": round(self.target_start_s, 3),
|
|
"target_end_s": round(self.target_end_s, 3),
|
|
"target_note_start": self.target_note_start,
|
|
"target_note_end": self.target_note_end,
|
|
"origin": self.origin,
|
|
"tags": list(self.tags),
|
|
"has_audio": self.has_audio,
|
|
}
|
|
if include_path:
|
|
out["path"] = [[int(i), int(j)] for i, j in self.path]
|
|
return out
|
|
|
|
|
|
@dataclass
|
|
class SearchResult:
|
|
"""一次检索的完整结果。"""
|
|
|
|
query: Melody
|
|
hits: list[Hit]
|
|
elapsed_ms: float
|
|
n_candidates: int
|
|
n_songs: int
|
|
coarse_recall: bool = False # 是否退化为全库扫描
|
|
|
|
def top(self) -> Hit | None:
|
|
return self.hits[0] if self.hits else None
|
|
|
|
def to_dict(self, *, include_path: bool = True, include_query: bool = True) -> dict[str, Any]:
|
|
out: dict[str, Any] = {
|
|
"elapsed_ms": round(self.elapsed_ms, 2),
|
|
"n_candidates": self.n_candidates,
|
|
"n_songs": self.n_songs,
|
|
"coarse_recall": self.coarse_recall,
|
|
"hits": [h.to_dict(include_path=include_path) for h in self.hits],
|
|
}
|
|
if include_query:
|
|
out["query"] = {
|
|
"n_notes": self.query.n_notes,
|
|
"duration": round(self.query.duration, 3),
|
|
"midis": [round(float(v), 2) for v in self.query.midis],
|
|
"starts": [round(float(v), 3) for v in self.query.starts],
|
|
"durs": [round(float(v), 3) for v in self.query.durs],
|
|
"contour": self.query.contour(),
|
|
}
|
|
return out
|
|
|
|
|
|
class SearchEngine:
|
|
"""把曲库、倒排索引与 DTW 精排组装成可复用的检索引擎。"""
|
|
|
|
def __init__(self, library: Library, cfg: Config = DEFAULT):
|
|
self.library = library
|
|
self.cfg = cfg
|
|
self.index = NgramIndex(cfg=cfg)
|
|
self.rebuild_index()
|
|
|
|
# ---------------- 索引 ---------------- #
|
|
def rebuild_index(self) -> int:
|
|
melodies = self.library.melodies(refresh=True)
|
|
self.index.build(melodies)
|
|
return self.index.n_songs
|
|
|
|
def _melody_map(self) -> dict[str, Melody]:
|
|
return {m.song_id: m for m in self.library.melodies()}
|
|
|
|
# ---------------- 检索 ---------------- #
|
|
def search_melody(
|
|
self,
|
|
melody: Melody,
|
|
*,
|
|
top_k: int | None = None,
|
|
with_path: bool = True,
|
|
candidates: int | None = None,
|
|
) -> SearchResult:
|
|
"""对已提取的旋律做检索。"""
|
|
started = time.perf_counter()
|
|
top_k = top_k or self.cfg.top_k
|
|
query = fuse_repeated_notes(melody, self.cfg)
|
|
|
|
if query.n_notes < 2 or self.index.n_songs == 0:
|
|
return SearchResult(query, [], (time.perf_counter() - started) * 1000.0, 0, self.index.n_songs)
|
|
|
|
index_scores = self.index.score(query)
|
|
ranked_index = sorted(index_scores.items(), key=lambda kv: (-kv[1], kv[0]))
|
|
cand_list, _ = self.index.candidates(query, top_n=candidates)
|
|
coarse_only = False
|
|
if len(cand_list) < 5:
|
|
# 候选不足:全库扫描保证召回
|
|
cand_list = [(m.song_id, index_scores.get(m.song_id, 0.0)) for m in self.library.melodies()]
|
|
coarse_only = True
|
|
|
|
melody_map = self._melody_map()
|
|
scored: list[Hit] = []
|
|
for song_id, idx_score in cand_list:
|
|
target = melody_map.get(song_id)
|
|
if target is None or target.n_notes < 2:
|
|
continue
|
|
alignment = align(query, target, self.cfg, need_path=False)
|
|
if not np.isfinite(alignment.cost):
|
|
continue
|
|
fused = self.cfg.w_dtw * alignment.sim + self.cfg.w_index * float(idx_score)
|
|
record = self.library.get_song(song_id)
|
|
scored.append(
|
|
Hit(
|
|
song_id=song_id,
|
|
title=record.title if record else song_id,
|
|
score=fused,
|
|
dtw_sim=alignment.sim,
|
|
index_sim=float(idx_score),
|
|
shift=alignment.shift,
|
|
target_start_s=alignment.target_start_s,
|
|
target_end_s=alignment.target_end_s,
|
|
target_note_start=alignment.target_note_start,
|
|
target_note_end=alignment.target_note_end,
|
|
origin=record.origin if record else "",
|
|
tags=record.tags if record else (),
|
|
has_audio=record is not None and bool(record.audio_file),
|
|
)
|
|
)
|
|
|
|
scored.sort(key=lambda h: (-h.score, h.song_id))
|
|
hits = scored[:top_k]
|
|
|
|
# 只对最终 Top-K 重算对齐路径,用于前端画对齐图
|
|
if with_path:
|
|
for hit in hits:
|
|
target = melody_map.get(hit.song_id)
|
|
if target is None:
|
|
continue
|
|
best = align(query, target, self.cfg, need_path=True)
|
|
hit.path = best.path
|
|
hit.target_start_s = best.target_start_s
|
|
hit.target_end_s = best.target_end_s
|
|
hit.target_note_start = best.target_note_start
|
|
hit.target_note_end = best.target_note_end
|
|
|
|
elapsed = (time.perf_counter() - started) * 1000.0
|
|
return SearchResult(
|
|
query=query,
|
|
hits=hits,
|
|
elapsed_ms=elapsed,
|
|
n_candidates=len(cand_list),
|
|
n_songs=self.index.n_songs,
|
|
coarse_recall=coarse_only,
|
|
)
|
|
|
|
def search_audio(
|
|
self,
|
|
samples: np.ndarray,
|
|
sr: int,
|
|
*,
|
|
top_k: int | None = None,
|
|
cfg: Config | None = None,
|
|
**preprocess_kwargs,
|
|
) -> tuple[SearchResult, Any]:
|
|
"""对原始音频做完整检索,返回 (结果, 基频轨迹)。"""
|
|
cfg = cfg or self.cfg
|
|
y = preprocess(samples, sr, cfg, **preprocess_kwargs)
|
|
track = extract_pitch(y, cfg.sample_rate, cfg)
|
|
melody = segment_notes(track, cfg)
|
|
return self.search_melody(melody, top_k=top_k), track
|
|
|
|
def search_file(self, path: str | Path, *, top_k: int | None = None) -> SearchResult:
|
|
samples, sr = read_audio(path)
|
|
result, _ = self.search_audio(samples, sr, top_k=top_k)
|
|
return result
|
|
|
|
# ---------------- 评估辅助 ---------------- #
|
|
def coarse_candidates(self, melody: Melody) -> list[tuple[str, float]]:
|
|
"""只跑粗召回,用于度量候选召回率。"""
|
|
cand, _ = self.index.candidates(melody)
|
|
return cand
|