api/endpoints/lyric_search.py

258 lines
9.3 KiB
Python
Raw Normal View History

2024-08-10 22:49:00 -04:00
#!/usr/bin/env python3.12
2025-01-11 20:59:10 -05:00
# pylint: disable=bare-except, broad-exception-raised, broad-exception-caught
2024-08-10 22:49:00 -04:00
import importlib
2025-01-11 20:59:10 -05:00
import traceback
import logging
2025-01-14 20:22:12 -05:00
import os
2024-08-10 22:49:00 -04:00
import urllib.parse
2025-01-19 07:01:07 -05:00
from typing import Optional
2024-08-10 22:49:00 -04:00
import regex
2024-11-29 15:33:12 -05:00
import aiohttp
2025-01-14 20:22:12 -05:00
import aiosqlite as sqlite3
2024-08-11 13:49:07 -04:00
from fastapi import FastAPI, HTTPException
2025-01-13 20:47:39 -05:00
from pydantic import BaseModel
from lyric_search.sources import aggregate
from lyric_search import notifier
2024-08-10 22:49:00 -04:00
2024-08-11 07:42:47 -04:00
class ValidLyricRequest(BaseModel):
"""
- **a**: artist
- **s**: song
- **t**: track (artist and song combined) [used only if a & s are not used]
- **extra**: include extra details in response [optional, default: false]
2024-11-29 15:33:12 -05:00
- **lrc**: Request LRCs?
2024-08-11 13:49:07 -04:00
- **sub**: text to search within lyrics, if found lyrics will begin at found verse [optional]
2024-08-11 07:42:47 -04:00
- **src**: the script/utility which initiated the request
2025-01-14 18:37:49 -05:00
- **excluded_sources**: sources to exclude (new only)
2024-08-11 07:42:47 -04:00
"""
2024-08-11 08:12:44 -04:00
2024-08-10 22:49:00 -04:00
a: str | None = None
s: str | None = None
t: str | None = None
sub: str | None = None
extra: bool | None = False
2024-11-29 15:33:12 -05:00
lrc: bool | None = False
2024-08-10 22:57:45 -04:00
src: str
2025-01-14 18:37:49 -05:00
excluded_sources: list | None = None
2024-08-10 22:49:00 -04:00
2024-08-11 13:49:07 -04:00
class Config: # pylint: disable=missing-class-docstring too-few-public-methods
2024-08-11 09:50:41 -04:00
schema_extra = {
"example": {
"a": "eminem",
"s": "rap god",
"src": "WEB",
2024-11-29 15:33:12 -05:00
"extra": True,
"lrc": False,
2024-08-11 09:50:41 -04:00
}
}
2025-01-14 20:22:12 -05:00
class ValidTypeAheadRequest(BaseModel):
"""
- **query**: query string
"""
pre_query: str|None = None
query: str
2024-08-11 09:50:41 -04:00
2024-08-13 19:50:02 -04:00
class ValidLyricSearchLogRequest(BaseModel):
"""
- **webradio**: whether or not to include requests generated automatically by the radio page on codey.lol, defaults to False
"""
webradio: bool = False
2025-01-14 20:22:12 -05:00
class CacheUtils:
"""Lyrics Cache DB Utils"""
def __init__(self):
2025-01-24 19:26:07 -05:00
self.lyrics_db_path = os.path.join("/", "usr", "local", "share",
"sqlite_dbs", "cached_lyrics.db")
2025-01-14 20:22:12 -05:00
async def check_typeahead(self, s: str, pre_query: str | None = None):
"""Check s against artists stored - for typeahead"""
async with sqlite3.connect(self.lyrics_db_path,
timeout=2) as db_conn:
db_conn.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])
if not pre_query:
query = "SELECT distinct(artist) FROM lyrics WHERE artist LIKE ? LIMIT 15"
query_params = (f"%{s}%",)
else:
query = "SELECT distinct(song) FROM lyrics WHERE artist LIKE ? AND song LIKE ? LIMIT 15"
query_params = (f"%{pre_query}%", f"%{s}%",)
2025-01-23 13:02:03 -05:00
async with await db_conn.execute(query, query_params) as db_cursor:
2025-01-14 20:22:12 -05:00
return await db_cursor.fetchall()
2024-08-10 22:49:00 -04:00
class LyricSearch(FastAPI):
2024-08-11 13:49:07 -04:00
"""Lyric Search Endpoint"""
2024-08-13 19:21:48 -04:00
def __init__(self, app: FastAPI, util, constants, glob_state): # pylint: disable=super-init-not-called
2024-08-10 22:49:00 -04:00
self.app = app
self.util = util
self.constants = constants
2024-08-13 19:21:48 -04:00
self.glob_state = glob_state
2025-01-14 20:22:12 -05:00
self.cache_utils = CacheUtils()
self.notifier = notifier.DiscordNotifier()
2024-08-10 22:49:00 -04:00
2024-08-13 10:36:53 -04:00
self.endpoints = {
2025-01-14 20:22:12 -05:00
"typeahead/artist": self.artist_typeahead_handler,
"typeahead/song": self.song_typeahead_handler,
"lyric_search": self.lyric_search_handler,
2025-01-24 19:26:07 -05:00
# "lyric_cache_list": self.lyric_cache_list_handler,
2024-08-13 10:36:53 -04:00
}
2024-08-10 22:49:00 -04:00
self.acceptable_request_sources = [
"WEB",
2024-08-17 06:01:18 -04:00
"WEB-RADIO",
2024-08-10 22:49:00 -04:00
"IRC-MS",
"IRC-FS",
"IRC-KALI",
"DISC-ACES",
"DISC-HAVOC",
2025-01-20 05:47:09 -05:00
"IRC-SHARED",
"LIMNORIA-SHARED",
2024-08-10 22:49:00 -04:00
]
2024-11-29 15:33:12 -05:00
self.lrc_regex = regex.compile(r'\[([0-9]{2}:[0-9]{2})\.[0-9]{1,3}\](\s(.*)){0,}')
2024-08-13 10:36:53 -04:00
for endpoint, handler in self.endpoints.items():
app.add_api_route(f"/{endpoint}", handler, methods=["POST", "GET"])
2024-08-11 17:04:06 -04:00
2025-01-24 19:26:07 -05:00
# async def lyric_cache_list_handler(self):
# """
# Get currently cached lyrics entries
# """
# return {
# 'err': False,
# 'data': await self.lyrics_engine.listCacheEntries()
# }
2024-08-13 19:50:02 -04:00
2025-01-14 20:22:12 -05:00
async def artist_typeahead_handler(self, data: ValidTypeAheadRequest):
"""Artist Type Ahead Handler"""
if not isinstance(data.query, str) or len(data.query) < 2:
return {
'err': True,
'errorText': 'Invalid request',
}
query = data.query
typeahead_result = await self.cache_utils.check_typeahead(query)
typeahead_list = [str(r.get('artist')) for r in typeahead_result]
return typeahead_list
async def song_typeahead_handler(self, data: ValidTypeAheadRequest):
"""Song Type Ahead Handler"""
2025-01-20 05:47:09 -05:00
if not isinstance(data.pre_query, str)\
or not isinstance(data.query, str|None):
2025-01-14 20:22:12 -05:00
return {
'err': True,
'errorText': 'Invalid request',
}
pre_query = data.pre_query
query = data.query
typeahead_result = await self.cache_utils.check_typeahead(query, pre_query)
typeahead_list = [str(r.get('song')) for r in typeahead_result]
return typeahead_list
2025-01-24 19:26:07 -05:00
# async def lyric_search_log_handler(self, data: ValidLyricSearchLogRequest):
# """Lyric Search Log Handler"""
# include_radio = data.webradio
# await self.glob_state.increment_counter('lyrichistory_requests')
# last_10k_sings = await self.lyrics_engine.getHistory(limit=10000, webradio=include_radio)
# return {
# 'err': False,
# 'history': last_10k_sings
# }
2025-01-13 20:47:39 -05:00
async def lyric_search_handler(self, data: ValidLyricRequest):
2025-01-13 20:47:39 -05:00
"""
Search for lyrics
2024-08-13 19:50:02 -04:00
2025-01-13 20:47:39 -05:00
- **a**: artist
- **s**: song
- **t**: track (artist and song combined) [used only if a & s are not used]
2025-01-13 20:47:39 -05:00
- **extra**: include extra details in response [optional, default: false] [unused]
- **lrc**: Request LRCs?
- **sub**: text to search within lyrics, if found lyrics will begin at found verse [optional, default: none]
- **src**: the script/utility which initiated the request
- **excluded_sources**: sources to exclude [optional, default: none]
2025-01-13 20:47:39 -05:00
"""
if (not data.a or not data.s) and not data.t or not data.src:
2025-01-13 20:47:39 -05:00
raise HTTPException(detail="Invalid request", status_code=500)
if data.src.upper() not in self.acceptable_request_sources:
await self.notifier.send(f"ERROR @ {__file__.rsplit("/", maxsplit=1)[-1]}",
f"Unknown request source: {data.src}")
2025-01-20 05:47:09 -05:00
return {
'err': True,
'errorText': f'Unknown request source: {data.src}',
2025-01-20 05:47:09 -05:00
}
2025-01-19 07:01:07 -05:00
if not data.t:
search_artist: str = data.a
search_song: str = data.s
else:
t_split = data.t.split(" - ", maxsplit=1)
search_artist: str = t_split[0]
search_song: str = t_split[1]
2025-01-19 07:01:07 -05:00
if search_artist and search_song:
search_artist = self.constants.DOUBLE_SPACE_REGEX.sub(" ", search_artist.strip())
search_song = self.constants.DOUBLE_SPACE_REGEX.sub(" ", search_song.strip())
search_artist = urllib.parse.unquote(search_artist)
search_song = urllib.parse.unquote(search_song)
2025-01-14 18:37:49 -05:00
excluded_sources = data.excluded_sources
aggregate_search = aggregate.Aggregate(exclude_methods=excluded_sources)
2025-01-16 07:14:36 -05:00
plain_lyrics = not data.lrc
2025-01-19 07:01:07 -05:00
result = await aggregate_search.search(search_artist, search_song, plain_lyrics)
2025-01-17 07:48:29 -05:00
if not result:
return {
'err': True,
'errorText': 'Sources exhausted, lyrics not located.',
}
2025-01-17 07:48:29 -05:00
result = result.todict()
if data.sub and not data.lrc:
2025-01-19 07:01:07 -05:00
seeked_found_line = None
2025-01-17 07:48:29 -05:00
lyric_lines = result['lyrics'].strip().split(" / ")
for i, line in enumerate(lyric_lines):
2025-01-17 07:54:17 -05:00
line = regex.sub(r'\u2064', '', line.strip())
if data.sub.strip().lower() in line.strip().lower():
seeked_found_line = i
logging.debug("Found %s at %s, match for %s!",
line, seeked_found_line, data.sub) # REMOVEME: DEBUG
break
2025-01-17 06:41:56 -05:00
2025-01-17 05:53:05 -05:00
if not seeked_found_line:
return {
'failed_seek': True,
}
result['lyrics'] = " / ".join(lyric_lines[seeked_found_line:])
2025-01-17 06:41:56 -05:00
result['confidence'] = int(result.get('confidence', 0))
2025-01-15 20:17:49 -05:00
result['time'] = f'{float(result['time']):.4f}'
2025-01-17 07:48:29 -05:00
if plain_lyrics:
result['lyrics'] = regex.sub(r'(\s/\s|\n)', '<br>', result['lyrics']).strip()
else:
# Swap lyrics key for 'lrc'
result['lrc'] = result['lyrics']
result.pop('lyrics')
2025-01-19 07:01:07 -05:00
if "cache" in result['src']:
2025-01-15 20:17:49 -05:00
result['from_cache'] = True
"""
REMOVE BELOW AFTER TESTING IS DONE
"""
# if not data.extra:
# result.pop('src')
2025-01-14 07:45:34 -05:00
return result