124 lines
6.0 KiB
Python
Raw Normal View History

#!/usr/bin/env python3.12
# pylint: disable=bare-except, broad-exception-caught, wrong-import-position
import sys
2025-01-15 20:17:49 -05:00
import time
sys.path.insert(1,'..')
import traceback
2025-01-14 11:10:13 -05:00
import logging
2025-01-14 14:17:18 -05:00
from typing import Optional
from aiohttp import ClientTimeout, ClientSession
from lyric_search_new import utils
from lyric_search_new.constructors import LyricsResult
from . import common
2025-01-15 20:17:49 -05:00
from . import cache
2025-01-14 11:10:13 -05:00
logger = logging.getLogger()
log_level = logging.getLevelName(logger.level)
class InvalidResponseException(Exception):
"""
Invalid Response Exception
"""
class LRCLib:
"""LRCLib Search Module"""
def __init__(self):
2025-01-14 14:17:18 -05:00
self.label: str = "LRCLib"
2025-01-14 18:37:49 -05:00
self.lrclib_url: str = "https://lrclib.net/api/search"
2025-01-14 14:17:18 -05:00
self.headers: dict = common.SCRAPE_HEADERS
self.timeout = ClientTimeout(connect=2, sock_read=4)
self.datautils = utils.DataUtils()
self.matcher = utils.TrackMatcher()
2025-01-15 20:17:49 -05:00
self.cache = cache.Cache()
2025-01-16 07:14:36 -05:00
async def search(self, artist: str, song: str, plain: bool = True) -> Optional[LyricsResult]:
"""
@artist: the artist to search
@song: the song to search
"""
try:
2025-01-14 14:17:18 -05:00
artist: str = artist.strip().lower()
song: str = song.strip().lower()
2025-01-15 20:17:49 -05:00
time_start: float = time.time()
2025-01-17 07:48:29 -05:00
lrc_obj: Optional[list[dict]] = None
logging.info("Searching %s - %s on %s",
2025-01-14 18:37:49 -05:00
artist, song, self.label)
input_track: str = f"{artist} - {song}"
2025-01-14 14:17:18 -05:00
returned_lyrics: str = ''
async with ClientSession() as client:
async with client.get(self.lrclib_url,
params = {
'artist_name': artist,
'track_name': song,
},
timeout=self.timeout,
headers=self.headers) as request:
request.raise_for_status()
2025-01-14 14:17:18 -05:00
text: str|None = await request.text()
if len(text) < 100:
raise InvalidResponseException("Search response text was invalid (len < 100 chars.)")
2025-01-14 14:17:18 -05:00
search_data: dict|None = await request.json()
2025-01-14 18:37:49 -05:00
# logging.info("Search Data:\n%s", search_data)
2025-01-14 18:37:49 -05:00
if not isinstance(search_data, list):
raise InvalidResponseException("Invalid JSON.")
2025-01-14 18:37:49 -05:00
2025-01-17 07:48:29 -05:00
if plain:
possible_matches = [(x, f"{result.get('artistName')} - {result.get('trackName')}")
2025-01-14 18:37:49 -05:00
for x, result in enumerate(search_data)]
2025-01-17 07:48:29 -05:00
else:
2025-01-17 07:54:17 -05:00
logging.info("Limiting possible matches to only those with non-null syncedLyrics")
possible_matches = [(x, f"{result.get('artistName')} - {result.get('trackName')}")
for x, result in enumerate(search_data) if isinstance(result['syncedLyrics'], str)]
2025-01-17 07:48:29 -05:00
2025-01-14 18:37:49 -05:00
2025-01-17 07:48:29 -05:00
2025-01-14 18:37:49 -05:00
best_match = self.matcher.find_best_match(input_track,
possible_matches)[0]
if not best_match:
return
best_match_id = best_match[0]
if not isinstance(search_data[best_match_id]['artistName'], str):
raise InvalidResponseException(f"Invalid JSON: Cannot find artistName key.\n{search_data}")
2025-01-14 18:37:49 -05:00
if not isinstance(search_data[best_match_id]['trackName'], str):
raise InvalidResponseException(f"Invalid JSON: Cannot find trackName key.\n{search_data}")
2025-01-14 18:37:49 -05:00
returned_artist: str = search_data[best_match_id]['artistName']
returned_song: str = search_data[best_match_id]['trackName']
2025-01-16 07:14:36 -05:00
if plain:
if not isinstance(search_data[best_match_id]['plainLyrics'], str):
raise InvalidResponseException(f"Invalid JSON: Cannot find plainLyrics key.\n{search_data}")
returned_lyrics: str = search_data[best_match_id]['plainLyrics']
returned_lyrics = self.datautils.scrub_lyrics(returned_lyrics)
else:
if not isinstance(search_data[best_match_id]['syncedLyrics'], str):
raise InvalidResponseException(f"Invalid JSON: Cannot find syncedLyrics key.\n{search_data}")
returned_lyrics: str = search_data[best_match_id]['syncedLyrics']
2025-01-17 07:48:29 -05:00
lrc_obj = self.datautils.create_lrc_object(returned_lyrics)
2025-01-14 18:37:49 -05:00
returned_track: str = f"{returned_artist} - {returned_song}"
2025-01-14 10:57:25 -05:00
(_matched, confidence) = self.matcher.find_best_match(input_track=input_track,
candidate_tracks=[(0, returned_track)])
if not confidence:
return # No suitable match found
2025-01-14 11:10:13 -05:00
logging.info("Result found on %s", self.label)
2025-01-15 20:17:49 -05:00
time_end: float = time.time()
time_diff: float = time_end - time_start
matched = LyricsResult(artist=returned_artist,
song=returned_song,
src=self.label,
2025-01-17 07:48:29 -05:00
lyrics=returned_lyrics if plain else lrc_obj,
2025-01-15 20:17:49 -05:00
confidence=confidence,
time=time_diff)
await self.cache.store(matched)
return matched
except:
2025-01-17 07:48:29 -05:00
traceback.print_exc()
2025-01-16 09:21:50 -05:00
return