73 lines
2.2 KiB
Python
73 lines
2.2 KiB
Python
|
#!/usr/bin/env python3.12
|
||
|
# pylint: disable=bare-except, broad-exception-caught
|
||
|
|
||
|
|
||
|
import logging
|
||
|
import traceback
|
||
|
import json
|
||
|
import redis.asyncio as redis
|
||
|
from redis.commands.json.path import Path
|
||
|
from redis.commands.search.query import NumericFilter, Query
|
||
|
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
|
||
|
from redis.commands.search.field import TextField, NumericField, TagField
|
||
|
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):
|
||
|
self.redis_pw = private.REDIS_PW
|
||
|
self.redis_client = redis.Redis(password=self.redis_pw)
|
||
|
|
||
|
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")
|
||
|
)
|
||
|
result = await self.redis_client.ft().create_index(schema, definition=IndexDefinition(prefix=["lyrics:"], index_type=IndexType.JSON))
|
||
|
if str(result) != "OK":
|
||
|
raise RedisException(f"Redis: Failed to create index: {result}")
|
||
|
except Exception as e:
|
||
|
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()
|
||
|
|