Debian Codegraph @

beetsplug/lastgenre/client.py

raw
1 """Last.fm API client for genre lookups."""
2
3 from __future__ import annotations
4
5 import traceback
6 from typing import TYPE_CHECKING, Any, ClassVar
7
8 import pylast
9
10 from beets import plugins
11
12 from .utils import is_ignored, normalize_genre
13
14 if TYPE_CHECKING:
15 from collections.abc import Callable
16
17 from beets.library import LibModel
18 from beets.logging import BeetsLogger
19
20 from .utils import AliasPatternWithReplacement, IgnorePatternsByArtist
21
22 GenreCache = dict[str, list[str]]
23 """Cache mapping entity keys to their genre lists.
24 Keys are formatted as 'entity.arg1-arg2-...' (e.g., 'album.artist-title').
25 Values are lists of lowercase genre strings."""
26
27 LASTFM = pylast.LastFMNetwork(api_key=plugins.LASTFM_KEY)
28
29 PYLAST_EXCEPTIONS = (
30 pylast.WSError,
31 pylast.MalformedResponseError,
32 pylast.NetworkError,
33 )
34
35
36 class LastFmClient:
37 """Client for fetching genres from Last.fm."""
38
39 FETCH_METHODS: ClassVar[
40 dict[
41 str,
42 tuple[Callable[..., Any], Callable[[LibModel], tuple[str, ...]]],
43 ]
44 ] = {
45 "track": (LASTFM.get_track, lambda obj: (obj.artist, obj.title)),
46 "album": (LASTFM.get_album, lambda obj: (obj.albumartist, obj.album)),
47 "artist": (LASTFM.get_artist, lambda obj: (obj.artist,)),
48 "album_artist": (LASTFM.get_artist, lambda obj: (obj.albumartist,)),
49 }
50
51 def __init__(
52 self,
53 log: BeetsLogger,
54 min_weight: int,
55 ignore_patterns: IgnorePatternsByArtist,
56 alias_patterns: list[AliasPatternWithReplacement],
57 ) -> None:
58 """Initialize the client.
59
60 The min_weight parameter filters tags by their minimum weight.
61 The ignorelist filters forbidden genres directly after Last.fm lookup.
62 """
63 self.log = log
64 self.min_weight = min_weight
65 self.ignore_patterns: IgnorePatternsByArtist = ignore_patterns
66 self.alias_patterns: list[AliasPatternWithReplacement] = alias_patterns
67 self.genre_cache: GenreCache = {}
68
69 def fetch_genres(
70 self, obj: pylast.Album | pylast.Artist | pylast.Track
71 ) -> list[str]:
72 """Return genres for a pylast entity."""
73 try:
74 res = obj.get_top_tags()
75 except PYLAST_EXCEPTIONS as exc:
76 self.log.debug("last.fm error: {}", exc)
77 return []
78 except Exception as exc:
79 # Isolate bugs in pylast.
80 self.log.debug("{}", traceback.format_exc())
81 self.log.error("error in pylast library: {}", exc)
82 return []
83
84 # Filter by weight (optionally).
85 if min_weight := self.min_weight:
86 res = [el for el in res if (int(el.weight or 0)) >= min_weight]
87
88 # Get strings from tags.
89 return [el.item.get_name().lower() for el in res]
90
91 def _last_lookup(
92 self, entity: str, method: Callable[..., Any], *args: str
93 ) -> list[str]:
94 """Get genres based on the named entity using the callable `method`
95 whose arguments are given in the sequence `args`. The genre lookup
96 is cached based on the entity name and the arguments.
97
98 Before the lookup, each argument has the "-" Unicode character replaced
99 with its rough ASCII equivalents in order to return better results from
100 the Last.fm database.
101 """
102 # Shortcut if we're missing metadata.
103 if any(not s for s in args):
104 return []
105
106 args_replaced = [a.replace("\u2010", "-") for a in args]
107 key = f"{entity}.{'-'.join(str(a) for a in args_replaced)}"
108 if key not in self.genre_cache:
109 self.genre_cache[key] = self.fetch_genres(method(*args_replaced))
110
111 genres = self.genre_cache[key]
112 self.log.extra_debug("last.fm (unfiltered) {} tags: {}", entity, genres)
113
114 # Apply aliases and log each change.
115 # Filter forbidden genres on every call so ignorelist hits are logged.
116 # Artist is always the first element in args (album, artist, track lookups).
117 return [
118 normal
119 for g in genres
120 if (normal := normalize_genre(self.log, self.alias_patterns, g))
121 and not is_ignored(self.log, self.ignore_patterns, normal, args[0])
122 ]
123
124 def fetch(self, kind: str, obj: LibModel, *args: str) -> list[str]:
125 """Fetch Last.fm genres for the specified kind and entity.
126
127 Use ``args`` if provided, otherwise derive arguments from the object.
128 """
129 method, arg_fn = self.FETCH_METHODS[kind]
130 return self._last_lookup(kind, method, *(args or arg_fn(obj)))