Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
+341
@@ -0,0 +1,341 @@
|
||||
"""曲库管理:把内置曲谱、MIDI 文件与导入的音频统一成可检索的曲库。
|
||||
|
||||
曲库构建流程::
|
||||
|
||||
内置曲谱 ─┐
|
||||
MIDI 文件 ─┼─→ 旋律特征 ─→ SQLite(melodies) ─→ 倒排索引
|
||||
外部导入 ─┘ └─→ 合成示范音频 ─→ data/audio/*.wav
|
||||
|
||||
同名曲目会去重:以真实 MIDI 为准,避免内置曲谱与 MIDI 版本互为近邻干扰检索。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
from .melody import Melody, fuse_repeated_notes
|
||||
from .midiio import read_midi_melody
|
||||
from .scores import BUILTIN_SCORES
|
||||
from .store import SongRecord, Store
|
||||
from .synth import render_melody
|
||||
|
||||
__all__ = ["Library", "BuildReport", "MIDI_TITLES"]
|
||||
|
||||
#: 27 首真实 MIDI 的中文标题(其余由文件名兜底)
|
||||
MIDI_TITLES: dict[str, str] = {
|
||||
"auld_lang_syne": "友谊地久天长",
|
||||
"fen_shua_jiang": "粉刷匠",
|
||||
"frere_jacques": "两只老虎",
|
||||
"fur_elise": "致爱丽丝",
|
||||
"greensleeves": "绿袖子",
|
||||
"haenschen_klein": "小小少年",
|
||||
"happy_birthday": "生日快乐",
|
||||
"jingle_bells": "铃儿响叮当",
|
||||
"london_bridge": "伦敦桥",
|
||||
"mary_had_little_lamb": "玛丽有只小羊羔",
|
||||
"molihua": "茉莉花",
|
||||
"ode_to_joy": "欢乐颂",
|
||||
"row_your_boat": "划船歌",
|
||||
"silent_night": "平安夜",
|
||||
"song_bie": "送别",
|
||||
"swan_lake": "天鹅湖",
|
||||
"turkish_march": "土耳其进行曲",
|
||||
"twinkle_twinkle": "小星星",
|
||||
"vivaldi_spring": "春(第一乐章)",
|
||||
"when_the_saints": "圣者行进",
|
||||
"william_tell_gallop": "威廉·退尔序曲",
|
||||
"penta_01": "五声音阶旋律 #1",
|
||||
"penta_02": "五声音阶旋律 #2",
|
||||
"penta_03": "五声音阶旋律 #3",
|
||||
"penta_04": "五声音阶旋律 #4",
|
||||
"penta_05": "五声音阶旋律 #5",
|
||||
"penta_06": "五声音阶旋律 #6",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class BuildReport:
|
||||
"""曲库构建结果摘要。"""
|
||||
|
||||
n_builtin: int = 0
|
||||
n_midi: int = 0
|
||||
n_skipped_duplicates: int = 0
|
||||
n_total: int = 0
|
||||
n_audio: int = 0
|
||||
seconds: float = 0.0
|
||||
built_at: str = ""
|
||||
errors: list[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"n_builtin": self.n_builtin,
|
||||
"n_midi": self.n_midi,
|
||||
"n_skipped_duplicates": self.n_skipped_duplicates,
|
||||
"n_total": self.n_total,
|
||||
"n_audio": self.n_audio,
|
||||
"seconds": round(self.seconds, 2),
|
||||
"built_at": self.built_at,
|
||||
"errors": self.errors,
|
||||
}
|
||||
|
||||
|
||||
class Library:
|
||||
"""曲库:负责构建、查询与示范音频管理。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: Store,
|
||||
cfg: Config = DEFAULT,
|
||||
*,
|
||||
midi_dir: str | Path = "data/midi",
|
||||
audio_dir: str | Path = "data/audio",
|
||||
):
|
||||
self.store = store
|
||||
self.cfg = cfg
|
||||
self.midi_dir = Path(midi_dir)
|
||||
self.audio_dir = Path(audio_dir)
|
||||
self.audio_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._melody_cache: list[Melody] | None = None
|
||||
|
||||
# ---------------- 构建 ---------------- #
|
||||
def build(
|
||||
self,
|
||||
*,
|
||||
include_builtin: bool = True,
|
||||
include_midi: bool = True,
|
||||
render_audio: bool = True,
|
||||
dedup: bool = True,
|
||||
force: bool = False,
|
||||
) -> BuildReport:
|
||||
"""重建曲库。``force=False`` 时若已有曲库则直接复用。"""
|
||||
started = datetime.now()
|
||||
report = BuildReport(built_at=started.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
|
||||
if not force and self.store.count_songs() > 0:
|
||||
report.n_total = self.store.count_songs()
|
||||
report.n_audio = len(list(self.audio_dir.glob("*.wav")))
|
||||
report.seconds = (datetime.now() - started).total_seconds()
|
||||
return report
|
||||
|
||||
if force:
|
||||
self.store.clear_library()
|
||||
|
||||
midi_melodies: list[Melody] = []
|
||||
if include_midi and self.midi_dir.exists():
|
||||
for path in sorted(self.midi_dir.glob("*.mid")):
|
||||
stem = path.stem
|
||||
title = MIDI_TITLES.get(stem, stem)
|
||||
try:
|
||||
mel = read_midi_melody(path, song_id=f"midi_{stem}", title=title)
|
||||
except Exception as exc: # 单文件损坏不应中断整库构建
|
||||
report.errors.append(f"{path.name}: {exc}")
|
||||
continue
|
||||
if mel.n_notes < 4:
|
||||
report.errors.append(f"{path.name}: 音符过少({mel.n_notes})")
|
||||
continue
|
||||
mel.meta["source"] = "midi"
|
||||
mel.meta["origin"] = "磁盘 MIDI 曲库"
|
||||
mel.meta["tags"] = ["真实MIDI"]
|
||||
midi_melodies.append(mel)
|
||||
|
||||
midi_stems = {m.song_id.removeprefix("midi_") for m in midi_melodies}
|
||||
|
||||
builtin_melodies: list[Melody] = []
|
||||
if include_builtin:
|
||||
for score in BUILTIN_SCORES:
|
||||
if dedup and score.id in midi_stems:
|
||||
report.n_skipped_duplicates += 1
|
||||
continue
|
||||
builtin_melodies.append(score.melody())
|
||||
|
||||
report.n_midi = len(midi_melodies)
|
||||
report.n_builtin = len(builtin_melodies)
|
||||
|
||||
# 曲库侧也要做重复音融合:查询端(声学切分)无法把一个持续音切成两半,
|
||||
# 若曲库保留乐谱里的重复音,两侧音符数就会系统性错位。
|
||||
all_melodies = [
|
||||
fuse_repeated_notes(mel, self.cfg)
|
||||
for mel in midi_melodies + builtin_melodies
|
||||
]
|
||||
|
||||
records: list[SongRecord] = []
|
||||
for mel in all_melodies:
|
||||
records.append(
|
||||
SongRecord(
|
||||
id=mel.song_id,
|
||||
title=mel.title,
|
||||
origin=str(mel.meta.get("origin", "")),
|
||||
tags=tuple(mel.meta.get("tags", [])),
|
||||
source=str(mel.meta.get("source", "")),
|
||||
midi_file=(
|
||||
f"midi/{mel.song_id.removeprefix('midi_')}.mid"
|
||||
if mel.song_id.startswith("midi_")
|
||||
else ""
|
||||
),
|
||||
audio_file=f"audio/{mel.song_id}.wav" if render_audio else "",
|
||||
n_notes=mel.n_notes,
|
||||
duration=round(mel.duration, 3),
|
||||
median_pitch=round(mel.median_pitch, 2),
|
||||
)
|
||||
)
|
||||
|
||||
for record in records:
|
||||
self.store.upsert_song(record)
|
||||
self.store.set_melodies(all_melodies)
|
||||
self.store.set_meta("library_built_at", report.built_at)
|
||||
self.store.set_meta("library_config", self.cfg.to_dict())
|
||||
|
||||
if render_audio:
|
||||
for mel in all_melodies:
|
||||
try:
|
||||
self._render_audio(mel)
|
||||
report.n_audio += 1
|
||||
except Exception as exc:
|
||||
report.errors.append(f"audio {mel.song_id}: {exc}")
|
||||
|
||||
self._melody_cache = None
|
||||
report.n_total = len(records)
|
||||
report.seconds = (datetime.now() - started).total_seconds()
|
||||
return report
|
||||
|
||||
# ---------------- 示范音频 ---------------- #
|
||||
def _render_audio(self, mel: Melody, *, force: bool = False) -> Path:
|
||||
path = self.audio_dir / f"{mel.song_id}.wav"
|
||||
if path.exists() and not force:
|
||||
return path
|
||||
from .audio import write_wav
|
||||
|
||||
wave = render_melody(mel, self.cfg.sample_rate, timbre="song", seed=hash(mel.song_id) % 2**31)
|
||||
write_wav(path, wave, self.cfg.sample_rate)
|
||||
return path
|
||||
|
||||
def audio_path(self, song_id: str) -> Path | None:
|
||||
path = self.audio_dir / f"{song_id}.wav"
|
||||
if path.exists():
|
||||
return path
|
||||
mel = self.store.get_melody(song_id)
|
||||
if mel is None:
|
||||
return None
|
||||
try:
|
||||
return self._render_audio(mel)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# ---------------- 查询 ---------------- #
|
||||
def songs(self) -> list[SongRecord]:
|
||||
return self.store.list_songs()
|
||||
|
||||
def get_song(self, song_id: str) -> SongRecord | None:
|
||||
return self.store.get_song(song_id)
|
||||
|
||||
def count(self) -> int:
|
||||
return self.store.count_songs()
|
||||
|
||||
def melodies(self, *, refresh: bool = False) -> list[Melody]:
|
||||
if self._melody_cache is None or refresh:
|
||||
self._melody_cache = self.store.all_melodies()
|
||||
return self._melody_cache
|
||||
|
||||
def get_melody(self, song_id: str) -> Melody | None:
|
||||
return self.store.get_melody(song_id)
|
||||
|
||||
def title_of(self, song_id: str) -> str:
|
||||
record = self.store.get_song(song_id)
|
||||
return record.title if record else song_id
|
||||
|
||||
# ---------------- 增删 ---------------- #
|
||||
def add_melody(
|
||||
self,
|
||||
mel: Melody,
|
||||
*,
|
||||
song_id: str,
|
||||
title: str = "",
|
||||
origin: str = "",
|
||||
tags: tuple[str, ...] = (),
|
||||
source: str = "import",
|
||||
render_audio: bool = True,
|
||||
) -> SongRecord:
|
||||
"""向曲库添加/覆盖一条旋律。"""
|
||||
mel = fuse_repeated_notes(mel, self.cfg)
|
||||
mel.song_id = song_id
|
||||
mel.title = title or song_id
|
||||
mel.meta.update({"origin": origin, "tags": list(tags), "source": source})
|
||||
record = SongRecord(
|
||||
id=song_id,
|
||||
title=mel.title,
|
||||
origin=origin,
|
||||
tags=tuple(tags),
|
||||
source=source,
|
||||
audio_file=f"audio/{song_id}.wav" if render_audio else "",
|
||||
n_notes=mel.n_notes,
|
||||
duration=round(mel.duration, 3),
|
||||
median_pitch=round(mel.median_pitch, 2),
|
||||
)
|
||||
self.store.upsert_song(record)
|
||||
self.store.set_melody(mel)
|
||||
if render_audio:
|
||||
try:
|
||||
self._render_audio(mel, force=True)
|
||||
except Exception:
|
||||
pass
|
||||
self._melody_cache = None
|
||||
return record
|
||||
|
||||
def add_midi_file(
|
||||
self, path: str | Path, *, song_id: str | None = None, title: str = ""
|
||||
) -> SongRecord:
|
||||
"""导入一个 MIDI 文件作为曲目。"""
|
||||
path = Path(path)
|
||||
sid = song_id or f"midi_{path.stem}"
|
||||
mel = read_midi_melody(path, song_id=sid, title=title or MIDI_TITLES.get(path.stem, path.stem))
|
||||
if mel.n_notes < 4:
|
||||
raise ValueError(f"MIDI 中有效音符过少({mel.n_notes})")
|
||||
return self.add_melody(
|
||||
mel,
|
||||
song_id=sid,
|
||||
title=mel.title,
|
||||
origin="导入 MIDI",
|
||||
tags=("导入",),
|
||||
source="midi",
|
||||
)
|
||||
|
||||
def delete(self, song_id: str) -> bool:
|
||||
audio = self.audio_dir / f"{song_id}.wav"
|
||||
if audio.exists():
|
||||
try:
|
||||
audio.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
self._melody_cache = None
|
||||
return self.store.delete_song(song_id)
|
||||
|
||||
# ---------------- 导出 ---------------- #
|
||||
def dump_index_payload(self) -> dict:
|
||||
return {
|
||||
"n_songs": self.count(),
|
||||
"built_at": self.store.get_meta("library_built_at"),
|
||||
"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,
|
||||
}
|
||||
for r in self.songs()
|
||||
],
|
||||
}
|
||||
|
||||
def save_index_payload(self, path: str | Path) -> None:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps(self.dump_index_payload(), ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
Reference in New Issue
Block a user