Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
+394
@@ -0,0 +1,394 @@
|
||||
"""SQLite 持久化层:曲库、旋律特征、用户账号、检索历史。
|
||||
|
||||
用数据库而不是裸 JSON,是为了让曲库能真正做增删改查,并让「谁在什么时候
|
||||
哼了什么、返回了什么」可追溯。密码用标准库 ``hashlib.scrypt`` 加盐派生,
|
||||
不引入额外依赖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .melody import Melody
|
||||
|
||||
__all__ = ["SongRecord", "Store", "hash_password", "verify_password"]
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS songs (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
origin TEXT DEFAULT '',
|
||||
tags TEXT DEFAULT '',
|
||||
source TEXT DEFAULT '',
|
||||
midi_file TEXT DEFAULT '',
|
||||
audio_file TEXT DEFAULT '',
|
||||
n_notes INTEGER DEFAULT 0,
|
||||
duration REAL DEFAULT 0,
|
||||
median_pitch REAL DEFAULT 0,
|
||||
added_at TEXT DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS melodies (
|
||||
song_id TEXT PRIMARY KEY,
|
||||
payload TEXT NOT NULL,
|
||||
updated_at TEXT DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_salt TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
email TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'active'
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS search_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
created_at TEXT DEFAULT '',
|
||||
source TEXT DEFAULT '',
|
||||
query_notes INTEGER DEFAULT 0,
|
||||
query_melody TEXT DEFAULT '',
|
||||
top_song TEXT DEFAULT '',
|
||||
top_title TEXT DEFAULT '',
|
||||
top_score REAL DEFAULT 0,
|
||||
elapsed_ms REAL DEFAULT 0,
|
||||
results TEXT DEFAULT '',
|
||||
FOREIGN KEY (user_id) REFERENCES users (user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_history_user ON search_history(user_id, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_history_time ON search_history(id DESC);
|
||||
"""
|
||||
|
||||
_SCRYPT_N = 2**14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_DKLEN = 32
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def hash_password(password: str, salt: bytes | None = None) -> tuple[str, str]:
|
||||
"""返回 (salt_hex, hash_hex)。"""
|
||||
if salt is None:
|
||||
salt = os.urandom(16)
|
||||
derived = hashlib.scrypt(
|
||||
password.encode("utf-8"), salt=salt, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_DKLEN
|
||||
)
|
||||
return salt.hex(), derived.hex()
|
||||
|
||||
|
||||
def verify_password(password: str, salt_hex: str, hash_hex: str) -> bool:
|
||||
try:
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
except ValueError:
|
||||
return False
|
||||
_, derived = hash_password(password, salt)
|
||||
return hmac.compare_digest(derived, hash_hex)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SongRecord:
|
||||
"""曲库中的一首曲目。"""
|
||||
|
||||
id: str
|
||||
title: str
|
||||
origin: str = ""
|
||||
tags: tuple[str, ...] = ()
|
||||
source: str = ""
|
||||
midi_file: str = ""
|
||||
audio_file: str = ""
|
||||
n_notes: int = 0
|
||||
duration: float = 0.0
|
||||
median_pitch: float = 0.0
|
||||
added_at: str = field(default_factory=_now)
|
||||
|
||||
def to_row(self) -> dict[str, Any]:
|
||||
row = asdict(self)
|
||||
row["tags"] = ",".join(self.tags)
|
||||
return row
|
||||
|
||||
@classmethod
|
||||
def from_row(cls, row: sqlite3.Row) -> "SongRecord":
|
||||
tags = tuple(t for t in (row["tags"] or "").split(",") if t)
|
||||
return cls(
|
||||
id=row["id"],
|
||||
title=row["title"],
|
||||
origin=row["origin"] or "",
|
||||
tags=tags,
|
||||
source=row["source"] or "",
|
||||
midi_file=row["midi_file"] or "",
|
||||
audio_file=row["audio_file"] or "",
|
||||
n_notes=int(row["n_notes"] or 0),
|
||||
duration=float(row["duration"] or 0.0),
|
||||
median_pitch=float(row["median_pitch"] or 0.0),
|
||||
added_at=row["added_at"] or "",
|
||||
)
|
||||
|
||||
|
||||
class Store:
|
||||
"""轻量 SQLite 封装;写操作串行化,读操作可并发。"""
|
||||
|
||||
def __init__(self, path: str | Path):
|
||||
self.path = Path(path)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._lock = threading.RLock()
|
||||
self._conn = sqlite3.connect(str(self.path), check_same_thread=False)
|
||||
self._conn.row_factory = sqlite3.Row
|
||||
self._conn.execute("PRAGMA journal_mode=WAL")
|
||||
self._conn.execute("PRAGMA foreign_keys=ON")
|
||||
with self._lock:
|
||||
self._conn.executescript(_SCHEMA)
|
||||
self._conn.commit()
|
||||
|
||||
# ---------------- 连接 ---------------- #
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._conn.close()
|
||||
|
||||
def __enter__(self) -> "Store":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
# ---------------- 曲库 ---------------- #
|
||||
def upsert_song(self, record: SongRecord) -> None:
|
||||
row = record.to_row()
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"""
|
||||
INSERT INTO songs (id, title, origin, tags, source, midi_file, audio_file,
|
||||
n_notes, duration, median_pitch, added_at)
|
||||
VALUES (:id, :title, :origin, :tags, :source, :midi_file, :audio_file,
|
||||
:n_notes, :duration, :median_pitch, :added_at)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
title=excluded.title, origin=excluded.origin, tags=excluded.tags,
|
||||
source=excluded.source, midi_file=excluded.midi_file,
|
||||
audio_file=excluded.audio_file, n_notes=excluded.n_notes,
|
||||
duration=excluded.duration, median_pitch=excluded.median_pitch
|
||||
""",
|
||||
row,
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
def get_song(self, song_id: str) -> SongRecord | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT * FROM songs WHERE id = ?", (song_id,))
|
||||
row = cur.fetchone()
|
||||
return SongRecord.from_row(row) if row else None
|
||||
|
||||
def list_songs(self) -> list[SongRecord]:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT * FROM songs ORDER BY id")
|
||||
rows = cur.fetchall()
|
||||
return [SongRecord.from_row(r) for r in rows]
|
||||
|
||||
def count_songs(self) -> int:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT COUNT(*) AS c FROM songs")
|
||||
return int(cur.fetchone()["c"])
|
||||
|
||||
def delete_song(self, song_id: str) -> bool:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("DELETE FROM songs WHERE id = ?", (song_id,))
|
||||
self._conn.execute("DELETE FROM melodies WHERE song_id = ?", (song_id,))
|
||||
self._conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
def clear_library(self) -> None:
|
||||
with self._lock:
|
||||
self._conn.execute("DELETE FROM songs")
|
||||
self._conn.execute("DELETE FROM melodies")
|
||||
self._conn.commit()
|
||||
|
||||
# ---------------- 旋律特征 ---------------- #
|
||||
def set_melody(self, mel: Melody) -> None:
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"INSERT INTO melodies (song_id, payload, updated_at) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(song_id) DO UPDATE SET payload=excluded.payload, "
|
||||
"updated_at=excluded.updated_at",
|
||||
(mel.song_id, mel.to_json(), _now()),
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
def set_melodies(self, melodies: Iterable[Melody]) -> int:
|
||||
rows = [(m.song_id, m.to_json(), _now()) for m in melodies]
|
||||
with self._lock:
|
||||
self._conn.executemany(
|
||||
"INSERT INTO melodies (song_id, payload, updated_at) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(song_id) DO UPDATE SET payload=excluded.payload, "
|
||||
"updated_at=excluded.updated_at",
|
||||
rows,
|
||||
)
|
||||
self._conn.commit()
|
||||
return len(rows)
|
||||
|
||||
def get_melody(self, song_id: str) -> Melody | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"SELECT payload FROM melodies WHERE song_id = ?", (song_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return Melody.from_json(row["payload"]) if row else None
|
||||
|
||||
def all_melodies(self) -> list[Melody]:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT payload FROM melodies ORDER BY song_id")
|
||||
rows = cur.fetchall()
|
||||
return [Melody.from_json(r["payload"]) for r in rows]
|
||||
|
||||
# ---------------- 用户 ---------------- #
|
||||
def create_user(
|
||||
self, username: str, password: str, email: str = ""
|
||||
) -> tuple[bool, str]:
|
||||
username = username.strip()
|
||||
if len(username) < 3:
|
||||
return False, "用户名至少 3 个字符"
|
||||
if len(password) < 6:
|
||||
return False, "密码至少 6 个字符"
|
||||
salt_hex, hash_hex = hash_password(password)
|
||||
try:
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"INSERT INTO users (username, password_salt, password_hash, email, "
|
||||
"created_at, status) VALUES (?, ?, ?, ?, ?, 'active')",
|
||||
(username, salt_hex, hash_hex, email, _now()),
|
||||
)
|
||||
self._conn.commit()
|
||||
except sqlite3.IntegrityError:
|
||||
return False, "用户名已存在"
|
||||
return True, "注册成功"
|
||||
|
||||
def verify_user(self, username: str, password: str) -> int | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"SELECT user_id, password_salt, password_hash, status FROM users "
|
||||
"WHERE username = ?",
|
||||
(username.strip(),),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row or row["status"] != "active":
|
||||
return None
|
||||
if not verify_password(password, row["password_salt"], row["password_hash"]):
|
||||
return None
|
||||
return int(row["user_id"])
|
||||
|
||||
def get_user(self, user_id: int) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"SELECT user_id, username, email, created_at, status FROM users "
|
||||
"WHERE user_id = ?",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
# ---------------- 检索历史 ---------------- #
|
||||
def add_history(
|
||||
self,
|
||||
*,
|
||||
user_id: int | None,
|
||||
source: str,
|
||||
query_notes: int,
|
||||
query_melody: str,
|
||||
top_song: str,
|
||||
top_title: str,
|
||||
top_score: float,
|
||||
elapsed_ms: float,
|
||||
results: list[dict[str, Any]],
|
||||
) -> int:
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"INSERT INTO search_history (user_id, created_at, source, query_notes, "
|
||||
"query_melody, top_song, top_title, top_score, elapsed_ms, results) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
user_id,
|
||||
_now(),
|
||||
source,
|
||||
query_notes,
|
||||
query_melody,
|
||||
top_song,
|
||||
top_title,
|
||||
float(top_score),
|
||||
float(elapsed_ms),
|
||||
json.dumps(results, ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
self._conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
|
||||
def list_history(self, user_id: int | None = None, limit: int = 50) -> list[dict[str, Any]]:
|
||||
with self._lock:
|
||||
if user_id is None:
|
||||
cur = self._conn.execute(
|
||||
"SELECT * FROM search_history ORDER BY id DESC LIMIT ?", (limit,)
|
||||
)
|
||||
else:
|
||||
cur = self._conn.execute(
|
||||
"SELECT * FROM search_history WHERE user_id = ? ORDER BY id DESC LIMIT ?",
|
||||
(user_id, limit),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
try:
|
||||
item["results"] = json.loads(item.get("results") or "[]")
|
||||
except json.JSONDecodeError:
|
||||
item["results"] = []
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
def clear_history(self, user_id: int | None = None) -> int:
|
||||
with self._lock:
|
||||
if user_id is None:
|
||||
cur = self._conn.execute("DELETE FROM search_history")
|
||||
else:
|
||||
cur = self._conn.execute(
|
||||
"DELETE FROM search_history WHERE user_id = ?", (user_id,)
|
||||
)
|
||||
self._conn.commit()
|
||||
return cur.rowcount
|
||||
|
||||
# ---------------- 元数据 ---------------- #
|
||||
def set_meta(self, key: str, value: Any) -> None:
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"INSERT INTO meta (key, value) VALUES (?, ?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
||||
(key, json.dumps(value, ensure_ascii=False)),
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
def get_meta(self, key: str, default: Any = None) -> Any:
|
||||
with self._lock:
|
||||
cur = self._conn.execute("SELECT value FROM meta WHERE key = ?", (key,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return default
|
||||
try:
|
||||
return json.loads(row["value"])
|
||||
except json.JSONDecodeError:
|
||||
return default
|
||||
Reference in New Issue
Block a user