76 lines
3.4 KiB
Python
76 lines
3.4 KiB
Python
#!/usr/bin/env python3.12
|
|
# pylint: disable=wrong-import-position
|
|
|
|
import os
|
|
import sys
|
|
sys.path.insert(1,'..')
|
|
sys.path.insert(1,'.')
|
|
from typing import Optional
|
|
import aiosqlite as sqlite3
|
|
from lyric_search_new import utils
|
|
from lyric_search_new.constructors import LyricsResult
|
|
|
|
class Cache:
|
|
"""Cache Search Module"""
|
|
def __init__(self):
|
|
self.cache_db = os.path.join("/", "var",
|
|
"lib", "singerdbs",
|
|
"cached_lyrics.db")
|
|
|
|
self.cache_pre_query = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory; pragma mmap_size = 30000000000;"
|
|
self.sqlite_exts = ['/usr/local/lib/python3.11/dist-packages/spellfix1.cpython-311-x86_64-linux-gnu.so']
|
|
self.label = "Cache"
|
|
|
|
def get_matched(self, sqlite_rows, matched_candidate, confidence) -> Optional[LyricsResult]:
|
|
"""Get Matched Result"""
|
|
matched_id = matched_candidate[0]
|
|
for row in sqlite_rows:
|
|
if row[0] == matched_id:
|
|
(_id, artist, song, lyrics, original_src, _confidence) = row
|
|
return LyricsResult(
|
|
artist=artist,
|
|
song=song,
|
|
lyrics=lyrics,
|
|
src=f"{original_src} (cached, id: {_id})",
|
|
confidence=confidence)
|
|
return None
|
|
|
|
async def search(self, artist: str, song: str):
|
|
"""
|
|
@artist: the artist to search
|
|
@song: the song to search
|
|
Returns:
|
|
- LyricsResult corresponding to nearest match found (if found), **None** otherwise
|
|
"""
|
|
artist = artist.strip().lower()
|
|
song = song.strip().lower()
|
|
async with sqlite3.connect(self.cache_db, timeout=2) as db_conn:
|
|
await db_conn.enable_load_extension(True)
|
|
for ext in self.sqlite_exts:
|
|
await db_conn.load_extension(ext)
|
|
async with await db_conn.executescript(self.cache_pre_query) as _db_cursor:
|
|
search_query = 'SELECT id, artist, song, lyrics, src, confidence FROM lyrics\
|
|
WHERE editdist3((artist || " " || song), (? || " " || ?))\
|
|
<= 410 ORDER BY editdist3((artist || " " || song), ?) ASC LIMIT 10'
|
|
search_params = (artist.strip(), song.strip(),
|
|
f"{artist.strip()} {song.strip()}")
|
|
async with await _db_cursor.execute(search_query, search_params) as db_cursor:
|
|
results = await db_cursor.fetchall()
|
|
result_tracks = []
|
|
for track in results:
|
|
(_id, _artist, _song, _lyrics, _src, _confidence) = track
|
|
result_tracks.append((_id, f"{_artist} - {_song}"))
|
|
input_track = f"{artist} - {song}"
|
|
matcher = utils.TrackMatcher()
|
|
best_match = matcher.find_best_match(input_track=input_track,
|
|
candidate_tracks=result_tracks)
|
|
if not best_match:
|
|
return None
|
|
(candidate, confidence) = best_match
|
|
return self.get_matched(sqlite_rows=results,
|
|
matched_candidate=candidate,
|
|
confidence=confidence)
|
|
|
|
|
|
|
|
|