2025-01-18 13:26:00 -05:00
|
|
|
#!/usr/bin/env python3.12
|
|
|
|
# pylint: disable=bare-except, broad-exception-caught
|
|
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
import traceback
|
|
|
|
import json
|
|
|
|
import redis.asyncio as redis
|
2025-01-18 13:34:10 -05:00
|
|
|
from redis.commands.search.query import Query
|
2025-01-18 13:26:00 -05:00
|
|
|
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
|
2025-01-18 13:34:10 -05:00
|
|
|
from redis.commands.search.field import TextField
|
2025-01-18 13:26:00 -05:00
|
|
|
from . import private
|
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger()
|
|
|
|
log_level = logging.getLevelName(logger.level)
|
|
|
|
|
|
|
|
class RedisException(Exception):
|
|
|
|
"""
|
|
|
|
Redis Exception
|
|
|
|
"""
|
|
|
|
|
|
|
|
class RedisCache:
|
|
|
|
"""
|
|
|
|
Redis Cache Methods
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
2025-01-18 13:34:10 -05:00
|
|
|
self.redis_client = redis.Redis(password=private.REDIS_PW)
|
2025-01-18 13:26:00 -05:00
|
|
|
|
|
|
|
async def create_index(self):
|
|
|
|
"""Create Index"""
|
|
|
|
try:
|
|
|
|
schema = (
|
|
|
|
TextField("$.artist", as_name="artist"),
|
|
|
|
TextField("$.song", as_name="song"),
|
|
|
|
TextField("$.src", as_name="src"),
|
|
|
|
TextField("$.lyrics", as_name="lyrics")
|
|
|
|
)
|
2025-01-18 13:34:10 -05:00
|
|
|
result = await self.redis_client.ft().create_index(
|
|
|
|
schema, definition=IndexDefinition(prefix=["lyrics:"], index_type=IndexType.JSON))
|
2025-01-18 13:26:00 -05:00
|
|
|
if str(result) != "OK":
|
|
|
|
raise RedisException(f"Redis: Failed to create index: {result}")
|
2025-01-18 13:34:10 -05:00
|
|
|
except:
|
2025-01-18 13:26:00 -05:00
|
|
|
pass
|
|
|
|
|
|
|
|
async def search(self, **kwargs):
|
|
|
|
"""Search Redis Cache
|
|
|
|
@artist: artist to search
|
|
|
|
@song: song to search
|
|
|
|
@lyrics: lyrics to search (optional, used in place of artist/song if provided)
|
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
artist = kwargs.get('artist')
|
|
|
|
song = kwargs.get('song')
|
|
|
|
lyrics = kwargs.get('lyrics')
|
|
|
|
|
|
|
|
if lyrics:
|
|
|
|
# to code later
|
|
|
|
raise RedisException("Lyric search not yet implemented")
|
|
|
|
|
|
|
|
search_res = await self.redis_client.ft().search(
|
|
|
|
Query(f"@artist:{artist} @song:{song}"
|
|
|
|
))
|
|
|
|
search_res_out = [dict(json.loads(result['json']))
|
|
|
|
for result in search_res.docs]
|
|
|
|
|
|
|
|
return search_res_out
|
|
|
|
except:
|
|
|
|
traceback.print_exc()
|
|
|
|
|