| 1 |
"""Gets genres for imported music based on Last.fm tags. |
| 2 |
|
| 3 |
Uses a provided whitelist file to determine which tags are valid genres. |
| 4 |
The included (default) genre list was originally produced by scraping Wikipedia |
| 5 |
and has been edited to remove some questionable entries. |
| 6 |
The scraper script used is available here: |
| 7 |
https://gist.github.com/1241307 |
| 8 |
""" |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
import os |
| 13 |
import re |
| 14 |
from collections import defaultdict |
| 15 |
from functools import cached_property, singledispatchmethod |
| 16 |
from pathlib import Path |
| 17 |
from typing import TYPE_CHECKING, Any, Protocol |
| 18 |
|
| 19 |
import confuse |
| 20 |
import yaml |
| 21 |
|
| 22 |
from beets import config, library, plugins, ui |
| 23 |
from beets.library import Album, Item |
| 24 |
from beets.util import plurality, unique_list |
| 25 |
from beetsplug.lastgenre.utils import is_ignored, normalize_genre |
| 26 |
|
| 27 |
from .client import LastFmClient |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from collections.abc import Iterable |
| 31 |
|
| 32 |
from beets.importer import ImportSession, ImportTask |
| 33 |
from beets.library import LibModel |
| 34 |
|
| 35 |
from .utils import AliasPatternWithReplacement, IgnorePatternsByArtist |
| 36 |
|
| 37 |
Whitelist = set[str] |
| 38 |
"""Set of valid genre names (lowercase). Empty set means all genres allowed.""" |
| 39 |
|
| 40 |
CanonTree = list[list[str]] |
| 41 |
#: Genre hierarchy as list of paths from general to specific. |
| 42 |
#: Example: [['electronic', 'house'], ['electronic', 'techno']] |
| 43 |
|
| 44 |
GenresWithLabel = tuple[list[str], str] |
| 45 |
#: A pair of ``(genre list, label)`` returned by a genre resolution stage. |
| 46 |
#: The label is used for logging and describes the source and filtering applied. |
| 47 |
|
| 48 |
|
| 49 |
class LastGenreCLIOpts(Protocol): |
| 50 |
album: bool |
| 51 |
|
| 52 |
|
| 53 |
# Canonicalization tree processing. |
| 54 |
|
| 55 |
|
| 56 |
def flatten_tree( |
| 57 |
elem: dict[Any, Any] | list[Any] | str, path: list[str], branches: CanonTree |
| 58 |
) -> None: |
| 59 |
"""Flatten nested lists/dictionaries into lists of strings |
| 60 |
(branches). |
| 61 |
""" |
| 62 |
if not path: |
| 63 |
path = [] |
| 64 |
|
| 65 |
if isinstance(elem, dict): |
| 66 |
for k, v in elem.items(): |
| 67 |
flatten_tree(v, [*path, k], branches) |
| 68 |
elif isinstance(elem, list): |
| 69 |
for sub in elem: |
| 70 |
flatten_tree(sub, path, branches) |
| 71 |
else: |
| 72 |
branches.append([*path, str(elem)]) |
| 73 |
|
| 74 |
|
| 75 |
def find_parents(candidate: str, branches: CanonTree) -> list[str]: |
| 76 |
"""Find parents genre of a given genre, ordered from the closest to |
| 77 |
the further parent. |
| 78 |
""" |
| 79 |
for branch in branches: |
| 80 |
try: |
| 81 |
idx = branch.index(candidate.lower()) |
| 82 |
return list(reversed(branch[: idx + 1])) |
| 83 |
except ValueError: |
| 84 |
continue |
| 85 |
return [candidate] |
| 86 |
|
| 87 |
|
| 88 |
def get_depth(tag: str, branches: CanonTree) -> int | None: |
| 89 |
"""Find the depth of a tag in the genres tree.""" |
| 90 |
for branch in branches: |
| 91 |
if tag in branch: |
| 92 |
return branch.index(tag) |
| 93 |
return None |
| 94 |
|
| 95 |
|
| 96 |
def sort_by_depth(tags: list[str], branches: CanonTree) -> list[str]: |
| 97 |
"""Given a list of tags, sort the tags by their depths in the genre tree.""" |
| 98 |
depth_tag_pairs = [(get_depth(t, branches), t) for t in tags] |
| 99 |
depth_tag_pairs = [e for e in depth_tag_pairs if e[0] is not None] |
| 100 |
depth_tag_pairs.sort(reverse=True) |
| 101 |
return [p[1] for p in depth_tag_pairs] |
| 102 |
|
| 103 |
|
| 104 |
# Main plugin logic. |
| 105 |
|
| 106 |
WHITELIST = os.path.join(os.path.dirname(__file__), "genres.txt") |
| 107 |
C14N_TREE = os.path.join(os.path.dirname(__file__), "genres-tree.yaml") |
| 108 |
ALIASES_FILE = os.path.join(os.path.dirname(__file__), "aliases.yaml") |
| 109 |
|
| 110 |
|
| 111 |
class LastGenrePlugin(plugins.BeetsPlugin): |
| 112 |
def __init__(self) -> None: |
| 113 |
super().__init__() |
| 114 |
|
| 115 |
self.config.add( |
| 116 |
{ |
| 117 |
"whitelist": True, |
| 118 |
"min_weight": 10, |
| 119 |
"count": 1, |
| 120 |
"fallback": None, |
| 121 |
"canonical": False, |
| 122 |
"cleanup_existing": False, |
| 123 |
"source": "album", |
| 124 |
"force": False, |
| 125 |
"keep_existing": False, |
| 126 |
"auto": True, |
| 127 |
"prefer_specific": False, |
| 128 |
"title_case": True, |
| 129 |
"pretend": False, |
| 130 |
"ignorelist": {}, |
| 131 |
"aliases": True, |
| 132 |
} |
| 133 |
) |
| 134 |
self.setup() |
| 135 |
|
| 136 |
def setup(self) -> None: |
| 137 |
"""Setup plugin from config options""" |
| 138 |
if self.config["auto"]: |
| 139 |
self.import_stages = [self.imported] |
| 140 |
|
| 141 |
self.whitelist: Whitelist = self._load_whitelist() |
| 142 |
self.c14n_branches: CanonTree |
| 143 |
self.c14n_branches, self.canonicalize = self._load_c14n_tree() |
| 144 |
self.ignore_patterns: IgnorePatternsByArtist = self._load_ignorelist() |
| 145 |
self.alias_patterns: list[AliasPatternWithReplacement] = ( |
| 146 |
self._load_aliases() |
| 147 |
) |
| 148 |
self.client = LastFmClient( |
| 149 |
self._log, |
| 150 |
self.config["min_weight"].get(int), |
| 151 |
self.ignore_patterns, |
| 152 |
self.alias_patterns, |
| 153 |
) |
| 154 |
|
| 155 |
def _load_whitelist(self) -> Whitelist: |
| 156 |
"""Load the whitelist from a text file. |
| 157 |
|
| 158 |
Default whitelist is used if config is True, empty string or set to "nothing". |
| 159 |
""" |
| 160 |
whitelist = set() |
| 161 |
wl_filename = self.config["whitelist"].get() |
| 162 |
if wl_filename in (True, "", None): # Indicates the default whitelist. |
| 163 |
wl_filename = WHITELIST |
| 164 |
if wl_filename: |
| 165 |
self._log.debug("Loading whitelist {}", wl_filename) |
| 166 |
text = Path(wl_filename).expanduser().read_text(encoding="utf-8") |
| 167 |
for line in text.splitlines(): |
| 168 |
if (line := line.strip().lower()) and not line.startswith("#"): |
| 169 |
whitelist.add(line) |
| 170 |
|
| 171 |
return whitelist |
| 172 |
|
| 173 |
def _load_c14n_tree(self) -> tuple[CanonTree, bool]: |
| 174 |
"""Load the canonicalization tree from a YAML file. |
| 175 |
|
| 176 |
Default tree is used if config is True, empty string, set to "nothing" |
| 177 |
or if prefer_specific is enabled. |
| 178 |
""" |
| 179 |
c14n_branches: CanonTree = [] |
| 180 |
c14n_filename = self.config["canonical"].get() |
| 181 |
canonicalize = c14n_filename is not False |
| 182 |
# Default tree |
| 183 |
if c14n_filename in (True, "", None) or ( |
| 184 |
# prefer_specific requires a tree, load default tree |
| 185 |
not canonicalize and self.config["prefer_specific"].get() |
| 186 |
): |
| 187 |
c14n_filename = C14N_TREE |
| 188 |
# Read the tree |
| 189 |
if c14n_filename: |
| 190 |
self._log.debug("Loading canonicalization tree {}", c14n_filename) |
| 191 |
with Path(c14n_filename).expanduser().open(encoding="utf-8") as f: |
| 192 |
genres_tree = yaml.safe_load(f) |
| 193 |
flatten_tree(genres_tree, [], c14n_branches) |
| 194 |
return c14n_branches, canonicalize |
| 195 |
|
| 196 |
def _load_ignorelist(self) -> IgnorePatternsByArtist: |
| 197 |
r"""Load patterns from configuration and compile them. |
| 198 |
|
| 199 |
Mapping of artist names to regex or literal patterns. Use the |
| 200 |
quoted ``'*'`` key to define globally ignored genres:: |
| 201 |
|
| 202 |
lastgenre: |
| 203 |
ignorelist: |
| 204 |
'*': |
| 205 |
- spoken word |
| 206 |
- comedy |
| 207 |
Artist Name: |
| 208 |
- .*rock.* |
| 209 |
- .*metal.* |
| 210 |
|
| 211 |
Matching is case-insensitive and full-match. Because patterns are |
| 212 |
parsed as plain YAML scalars, backslashes (e.g. ``\w``) should |
| 213 |
not be double-escaped. Quotes are primarily needed for special |
| 214 |
YAML characters (e.g., ``*`` or ``[``); prefer single-quotes. |
| 215 |
|
| 216 |
Raises: |
| 217 |
Several confuse.ConfigError's that tell the user about the expected |
| 218 |
format when the config is invalid. |
| 219 |
""" |
| 220 |
if not self.config["ignorelist"].get(): |
| 221 |
return {} |
| 222 |
|
| 223 |
raw_ignorelist = self.config["ignorelist"].get( |
| 224 |
confuse.MappingValues(confuse.Sequence(str)) |
| 225 |
) |
| 226 |
|
| 227 |
compiled_ignorelist: IgnorePatternsByArtist = defaultdict(list) |
| 228 |
for artist, patterns in raw_ignorelist.items(): |
| 229 |
artist_patterns = [] |
| 230 |
for pattern in patterns: |
| 231 |
try: |
| 232 |
artist_patterns.append(re.compile(pattern, re.IGNORECASE)) |
| 233 |
except re.error: |
| 234 |
artist_patterns.append( |
| 235 |
re.compile(re.escape(pattern), re.IGNORECASE) |
| 236 |
) |
| 237 |
self._log.extra_debug( |
| 238 |
"ignore for {}: {}", |
| 239 |
artist, |
| 240 |
[p.pattern for p in artist_patterns], |
| 241 |
) |
| 242 |
|
| 243 |
compiled_ignorelist[artist.lower()] = artist_patterns |
| 244 |
|
| 245 |
return compiled_ignorelist |
| 246 |
|
| 247 |
def _load_aliases(self) -> list[AliasPatternWithReplacement]: |
| 248 |
"""Load the genre alias table from the beets config. |
| 249 |
|
| 250 |
``lastgenre.aliases`` is a tri-state option: |
| 251 |
|
| 252 |
- ``yes`` (default): load the built-in aliases. |
| 253 |
- ``no``: disable alias normalization entirely. |
| 254 |
- mapping: an inline dict of canonical genre names to lists of regex |
| 255 |
patterns. |
| 256 |
|
| 257 |
The key (genre name) is used as a ``re.Match.expand()`` template, |
| 258 |
so ``\\1`` / ``\\g<N>`` back-references to capture groups are supported. |
| 259 |
|
| 260 |
Raises: |
| 261 |
confuse.ConfigTypeError: when the config value is not a bool or |
| 262 |
mapping, or when a mapping value is not a list. |
| 263 |
re.error: when a pattern is not valid regex syntax. |
| 264 |
""" |
| 265 |
aliases_config = self.config["aliases"].get() |
| 266 |
if aliases_config is False: |
| 267 |
return [] |
| 268 |
|
| 269 |
# Define view with either built-in or user-configured |
| 270 |
aliases_view = confuse.Configuration( |
| 271 |
self.config["aliases"].name, read=False |
| 272 |
) |
| 273 |
if aliases_config in (True, "", None): |
| 274 |
self._log.debug("Loading built-in aliases") |
| 275 |
with Path(ALIASES_FILE).open(encoding="utf-8") as f: |
| 276 |
aliases_view.set(yaml.safe_load(f)) |
| 277 |
elif not isinstance(aliases_config, dict): |
| 278 |
raise confuse.ConfigTypeError( |
| 279 |
f"{self.config['aliases'].name} must be a dict or bool." |
| 280 |
) |
| 281 |
else: |
| 282 |
aliases_view.set(aliases_config) |
| 283 |
|
| 284 |
# Parse and compile. Raise for invalid regex! |
| 285 |
raw_aliases = aliases_view.get( |
| 286 |
confuse.MappingValues(confuse.Sequence(str)) |
| 287 |
) |
| 288 |
compiled_aliases: list[AliasPatternWithReplacement] = [] |
| 289 |
for canonical, patterns in raw_aliases.items(): |
| 290 |
lower_canonical = canonical.lower() |
| 291 |
compiled_aliases.extend( |
| 292 |
(re.compile(p, re.IGNORECASE), lower_canonical) |
| 293 |
for p in patterns |
| 294 |
) |
| 295 |
|
| 296 |
self._log.debug("Loaded {} alias entries", len(compiled_aliases)) |
| 297 |
return compiled_aliases |
| 298 |
|
| 299 |
@property |
| 300 |
def sources(self) -> tuple[str, ...]: |
| 301 |
"""A tuple of allowed genre sources. May contain 'track', |
| 302 |
'album', or 'artist.' |
| 303 |
""" |
| 304 |
return self.config["source"].as_choice( |
| 305 |
{ |
| 306 |
"track": ("track", "album", "artist"), |
| 307 |
"album": ("album", "artist"), |
| 308 |
"artist": ("artist",), |
| 309 |
} |
| 310 |
) |
| 311 |
|
| 312 |
# Genre list processing. |
| 313 |
|
| 314 |
def _resolve_genres( |
| 315 |
self, tags: list[str], artist: str | None = None |
| 316 |
) -> list[str]: |
| 317 |
"""Canonicalize, sort and filter a list of genres. |
| 318 |
|
| 319 |
- Returns an empty list if the input tags list is empty. |
| 320 |
- If aliases are configured, variant spellings are normalised first |
| 321 |
(e.g. 'hip-hop' → 'hip hop', 'dnb' → 'drum and bass'). |
| 322 |
- If canonicalization is enabled, it extends the list by incorporating |
| 323 |
parent genres from the canonicalization tree. When a whitelist is set, |
| 324 |
only parent tags that pass the whitelist filter are included; |
| 325 |
otherwise, it adds the oldest ancestor. Adding parent tags is stopped |
| 326 |
when the count of tags reaches the configured limit (count). |
| 327 |
- The tags list is then deduplicated to ensure only unique genres are |
| 328 |
retained. |
| 329 |
- If the 'prefer_specific' configuration is enabled, the list is sorted |
| 330 |
by the specificity (depth in the canonicalization tree) of the genres. |
| 331 |
- Finally applies whitelist filtering to ensure that only valid |
| 332 |
genres are kept. (This may result in no genres at all being retained). |
| 333 |
- Ignorelist is applied at each stage: ignored input tags skip ancestry |
| 334 |
entirely, ignored ancestor tags are dropped, and ignored tags are |
| 335 |
removed in the final filter. |
| 336 |
- Returns the filtered list of genres, limited to the configured count. |
| 337 |
""" |
| 338 |
if not tags: |
| 339 |
return [] |
| 340 |
|
| 341 |
# Normalize variant spellings before any other processing. |
| 342 |
if self.alias_patterns: |
| 343 |
tags = [ |
| 344 |
normalize_genre(self._log, self.alias_patterns, tag) |
| 345 |
for tag in tags |
| 346 |
] |
| 347 |
|
| 348 |
count = self.config["count"].get(int) |
| 349 |
|
| 350 |
# Canonicalization (if enabled) |
| 351 |
if self.canonicalize: |
| 352 |
# Extend the list to consider tags parents in the c14n tree |
| 353 |
tags_all = [] |
| 354 |
for tag in tags: |
| 355 |
# Skip ignored tags entirely — don't walk their ancestry. |
| 356 |
if is_ignored(self._log, self.ignore_patterns, tag, artist): |
| 357 |
continue |
| 358 |
|
| 359 |
# Add parents that pass whitelist (and are not ignored, which |
| 360 |
# is checked in _filter_valid). With whitelist, we may include |
| 361 |
# multiple parents |
| 362 |
if self.whitelist: |
| 363 |
parents = self._filter_valid( |
| 364 |
find_parents(tag, self.c14n_branches), artist=artist |
| 365 |
) |
| 366 |
else: |
| 367 |
# No whitelist: take only the oldest ancestor, skipping it |
| 368 |
# if it is in the ignorelist |
| 369 |
oldest = find_parents(tag, self.c14n_branches)[-1] |
| 370 |
parents = ( |
| 371 |
[] |
| 372 |
if is_ignored( |
| 373 |
self._log, self.ignore_patterns, oldest, artist |
| 374 |
) |
| 375 |
else [oldest] |
| 376 |
) |
| 377 |
|
| 378 |
tags_all += parents |
| 379 |
# Stop if we have enough tags already, unless we need to find |
| 380 |
# the most specific tag (instead of the most popular). |
| 381 |
if ( |
| 382 |
not self.config["prefer_specific"] |
| 383 |
and len(tags_all) >= count |
| 384 |
): |
| 385 |
break |
| 386 |
tags = tags_all |
| 387 |
|
| 388 |
tags = unique_list(tags) |
| 389 |
|
| 390 |
# Sort the tags by specificity. |
| 391 |
if self.config["prefer_specific"]: |
| 392 |
tags = sort_by_depth(tags, self.c14n_branches) |
| 393 |
|
| 394 |
# Final filter: applies when c14n is disabled, or when c14n ran without |
| 395 |
# whitelist filtering in the loop (no-whitelist path). |
| 396 |
valid_tags = self._filter_valid(tags, artist=artist) |
| 397 |
return valid_tags[:count] |
| 398 |
|
| 399 |
def _filter_valid( |
| 400 |
self, genres: Iterable[str], artist: str | None = None |
| 401 |
) -> list[str]: |
| 402 |
"""Filter genres through whitelist and ignorelist. |
| 403 |
|
| 404 |
Strips leading/trailing whitespace and drops empty strings, then |
| 405 |
applies whitelist and ignorelist checks. Whitelist is checked first |
| 406 |
for performance reasons (ignorelist regex matching is more expensive |
| 407 |
and for some call sites ignored genres were already filtered). |
| 408 |
""" |
| 409 |
non_blank = [s for g in genres if (s := g.strip())] |
| 410 |
return [ |
| 411 |
g |
| 412 |
for g in non_blank |
| 413 |
if (not self.whitelist or g.lower() in self.whitelist) |
| 414 |
and not is_ignored(self._log, self.ignore_patterns, g, artist) |
| 415 |
] |
| 416 |
|
| 417 |
# Genre resolution pipeline. |
| 418 |
|
| 419 |
def _format_genres(self, tags: list[str]) -> list[str]: |
| 420 |
"""Format to title case if configured.""" |
| 421 |
if self.config["title_case"]: |
| 422 |
return [tag.title() for tag in tags] |
| 423 |
return tags |
| 424 |
|
| 425 |
def _artist_for_filter(self, obj: LibModel) -> str | None: |
| 426 |
"""Return the representative artist for genre resolution and filtering.""" |
| 427 |
return ( |
| 428 |
obj.artist |
| 429 |
if isinstance(obj, library.Item) |
| 430 |
else obj.albumartist or obj.get("artist") |
| 431 |
) |
| 432 |
|
| 433 |
def _get_existing_genres(self, obj: LibModel) -> list[str]: |
| 434 |
"""Return a list of genres for this Item or Album.""" |
| 435 |
if isinstance(obj, library.Item): |
| 436 |
genres_list = obj.get("genres", with_album=False) |
| 437 |
else: |
| 438 |
genres_list = obj.get("genres") |
| 439 |
|
| 440 |
return genres_list |
| 441 |
|
| 442 |
def _combine_resolve_and_log( |
| 443 |
self, old: list[str], new: list[str], artist: str | None = None |
| 444 |
) -> list[str]: |
| 445 |
"""Combine old and new genres and process via _resolve_genres.""" |
| 446 |
self._log.debug("raw last.fm tags: {}", new) |
| 447 |
self._log.debug("existing genres taken into account: {}", old) |
| 448 |
combined = old + new |
| 449 |
return self._resolve_genres(combined, artist=artist) |
| 450 |
|
| 451 |
@cached_property |
| 452 |
def fallback(self) -> GenresWithLabel: |
| 453 |
"""Return the configured fallback genre and label.""" |
| 454 |
if fallback := self.config["fallback"].get(): |
| 455 |
return [fallback], "fallback" |
| 456 |
return [], "fallback unconfigured" |
| 457 |
|
| 458 |
def _try_resolve_stage( |
| 459 |
self, |
| 460 |
stage_label: str, |
| 461 |
keep_genres: list[str], |
| 462 |
new_genres: list[str], |
| 463 |
artist: str | None = None, |
| 464 |
) -> GenresWithLabel | None: |
| 465 |
"""Try to resolve genres for a given stage and log the result. |
| 466 |
|
| 467 |
If any newly fetched genres and/or existing genres are resolved, return |
| 468 |
a tuple of the resolved genres and a label describing the source and |
| 469 |
filtering applied. Otherwise, return ``None``. |
| 470 |
""" |
| 471 |
resolved_genres = self._combine_resolve_and_log( |
| 472 |
keep_genres, new_genres, artist=artist |
| 473 |
) |
| 474 |
if resolved_genres: |
| 475 |
suffix = "whitelist" if self.whitelist else "any" |
| 476 |
label = f"{stage_label}, {suffix}" |
| 477 |
if keep_genres: |
| 478 |
label = f"keep + {label}" |
| 479 |
return self._format_genres(resolved_genres), label |
| 480 |
return None |
| 481 |
|
| 482 |
def _try_resolve_existing_genres( |
| 483 |
self, obj: LibModel, genres: list[str] |
| 484 |
) -> GenresWithLabel | None: |
| 485 |
"""Handle existing genres when not forcing. |
| 486 |
|
| 487 |
Clean up existing genres if enabled, or return them unchanged. Return |
| 488 |
``None`` if cleanup is enabled but fails to resolve, leaving fallback |
| 489 |
handling to the caller. |
| 490 |
""" |
| 491 |
if self.config["cleanup_existing"]: |
| 492 |
keep_genres = [g.lower() for g in genres] |
| 493 |
return self._try_resolve_stage( |
| 494 |
"cleanup", keep_genres, [], artist=self._artist_for_filter(obj) |
| 495 |
) |
| 496 |
|
| 497 |
return genres, "keep any, no-force" # type: ignore |
| 498 |
|
| 499 |
def _try_resolve_original_fallback( |
| 500 |
self, obj: LibModel, genres: list[str], keep_genres: list[str] |
| 501 |
) -> GenresWithLabel | None: |
| 502 |
"""Attempt to fall back to existing original genres if configured. |
| 503 |
|
| 504 |
``genres`` are the original unchanged values and are checked as-is |
| 505 |
first, then ``keep_genres`` are used for a lowercased canonicalization |
| 506 |
retry. |
| 507 |
""" |
| 508 |
if genres and self.config["keep_existing"].get(): |
| 509 |
artist = self._artist_for_filter(obj) |
| 510 |
if valid_genres := self._filter_valid(genres, artist=artist): |
| 511 |
return valid_genres, "original fallback" |
| 512 |
# If the original genre doesn't match a whitelisted genre, check |
| 513 |
# if we can canonicalize it to find a matching, whitelisted genre! |
| 514 |
if resolved := self._try_resolve_stage( |
| 515 |
"original fallback", keep_genres, [], artist=artist |
| 516 |
): |
| 517 |
return resolved |
| 518 |
return None |
| 519 |
|
| 520 |
def _fetch_va_genres(self, album: Album) -> list[str]: |
| 521 |
"""Fetch the most popular track or artist genre for a Various Artists album.""" |
| 522 |
item_genres = [] |
| 523 |
for item in album.items(): |
| 524 |
item_genre = None |
| 525 |
if "track" in self.sources: |
| 526 |
item_genre = self.client.fetch("track", item) |
| 527 |
if not item_genre: |
| 528 |
item_genre = self.client.fetch("artist", item) |
| 529 |
if item_genre: |
| 530 |
item_genres += item_genre |
| 531 |
|
| 532 |
if item_genres: |
| 533 |
most_popular, rank = plurality(item_genres) |
| 534 |
self._log.debug( |
| 535 |
'Most popular track genre "{}" ({}) for VA album.', |
| 536 |
most_popular, |
| 537 |
rank, |
| 538 |
) |
| 539 |
return [most_popular] |
| 540 |
|
| 541 |
return [] |
| 542 |
|
| 543 |
def _fetch_artist_stage( |
| 544 |
self, obj: LibModel |
| 545 |
) -> tuple[str, list[str], str | None]: |
| 546 |
"""Fetch artist genres for an Item or Album object. |
| 547 |
|
| 548 |
Return a tuple of ``(stage_label, genres, stage_artist)``. |
| 549 |
""" |
| 550 |
if isinstance(obj, library.Item): |
| 551 |
return "artist", self.client.fetch("artist", obj), obj.artist |
| 552 |
|
| 553 |
if obj.albumartist != config["va_name"].as_str(): |
| 554 |
new_genres = self.client.fetch("album_artist", obj) |
| 555 |
if new_genres: |
| 556 |
return "album artist", new_genres, obj.albumartist |
| 557 |
|
| 558 |
self._log.extra_debug( |
| 559 |
'No album artist genre found for "{}", ' |
| 560 |
"trying multi-valued field...", |
| 561 |
obj.albumartist, |
| 562 |
) |
| 563 |
for albumartist in obj.albumartists: |
| 564 |
self._log.extra_debug( |
| 565 |
'Fetching artist genre for "{}"', albumartist |
| 566 |
) |
| 567 |
new_genres += self.client.fetch( |
| 568 |
"album_artist", obj, albumartist |
| 569 |
) |
| 570 |
if new_genres: |
| 571 |
# Already filtered per-artist in client |
| 572 |
return "multi-valued album artist", new_genres, None |
| 573 |
return "album artist", [], None |
| 574 |
|
| 575 |
# For "Various Artists", pick the most popular track genre. |
| 576 |
assert isinstance(obj, Album) # Type narrowing for mypy |
| 577 |
if va_genres := self._fetch_va_genres(obj): |
| 578 |
return "most popular track", va_genres, None |
| 579 |
|
| 580 |
return "most popular track", [], None |
| 581 |
|
| 582 |
def _get_genre(self, obj: LibModel) -> GenresWithLabel: |
| 583 |
"""Get the final genre list for an Album or Item object. |
| 584 |
|
| 585 |
`self.sources` specifies allowed genre sources. Starting with the first |
| 586 |
source in this tuple, the following stages run through until a genre is |
| 587 |
found or no options are left: |
| 588 |
- track (for Items only) |
| 589 |
- album |
| 590 |
- artist, albumartist or "most popular track genre" (for VA-albums) |
| 591 |
- original fallback |
| 592 |
- configured fallback |
| 593 |
- empty list |
| 594 |
|
| 595 |
A `(genres, label)` pair is returned, where `label` is a string used for |
| 596 |
logging. For example, "keep + artist, whitelist" indicates that existing |
| 597 |
genres were combined with new last.fm genres and whitelist filtering was |
| 598 |
applied, while "artist, any" means only new last.fm genres are included |
| 599 |
and the whitelist feature was disabled. |
| 600 |
""" |
| 601 |
|
| 602 |
new_genres = [] |
| 603 |
existing_genres = self._get_existing_genres(obj) |
| 604 |
|
| 605 |
if existing_genres and not self.config["force"]: |
| 606 |
if resolved := self._try_resolve_existing_genres( |
| 607 |
obj, existing_genres |
| 608 |
): |
| 609 |
return resolved |
| 610 |
return self.fallback |
| 611 |
|
| 612 |
keep_genres = ( |
| 613 |
[g.lower() for g in existing_genres] |
| 614 |
if self.config["keep_existing"] and self.config["force"] |
| 615 |
else [] |
| 616 |
) |
| 617 |
|
| 618 |
# Run through stages: track, album, artist, |
| 619 |
# album artist, or most popular track genre. |
| 620 |
if isinstance(obj, library.Item) and "track" in self.sources: |
| 621 |
if new_genres := self.client.fetch("track", obj): |
| 622 |
if resolved := self._try_resolve_stage( |
| 623 |
"track", keep_genres, new_genres, artist=obj.artist |
| 624 |
): |
| 625 |
return resolved |
| 626 |
|
| 627 |
if "album" in self.sources: |
| 628 |
if new_genres := self.client.fetch("album", obj): |
| 629 |
if resolved := self._try_resolve_stage( |
| 630 |
"album", keep_genres, new_genres, artist=obj.albumartist |
| 631 |
): |
| 632 |
return resolved |
| 633 |
|
| 634 |
if "artist" in self.sources: |
| 635 |
stage_label, new_genres, stage_artist = self._fetch_artist_stage( |
| 636 |
obj |
| 637 |
) |
| 638 |
if new_genres: |
| 639 |
if resolved := self._try_resolve_stage( |
| 640 |
stage_label, keep_genres, new_genres, artist=stage_artist |
| 641 |
): |
| 642 |
return resolved |
| 643 |
|
| 644 |
if resolved := self._try_resolve_original_fallback( |
| 645 |
obj, existing_genres, keep_genres |
| 646 |
): |
| 647 |
return resolved |
| 648 |
|
| 649 |
return self.fallback |
| 650 |
|
| 651 |
# Beets plugin hooks and CLI. |
| 652 |
|
| 653 |
def _fetch_and_log_genre(self, obj: LibModel) -> None: |
| 654 |
"""Fetch genre and log it.""" |
| 655 |
self._log.info(str(obj)) |
| 656 |
obj.genres, label = self._get_genre(obj) |
| 657 |
self._log.debug("Resolved ({}): {}", label, obj.genres) |
| 658 |
|
| 659 |
ui.show_model_changes(obj, fields=["genres"], print_obj=False) |
| 660 |
|
| 661 |
@singledispatchmethod |
| 662 |
def _process(self, obj: LibModel, write: bool) -> None: |
| 663 |
"""Process an object, dispatching to the appropriate method.""" |
| 664 |
raise NotImplementedError |
| 665 |
|
| 666 |
@_process.register |
| 667 |
def _process_track(self, obj: Item, write: bool) -> None: |
| 668 |
"""Process a single track/item.""" |
| 669 |
self._fetch_and_log_genre(obj) |
| 670 |
if not self.config["pretend"]: |
| 671 |
obj.try_sync(write=write, move=False) |
| 672 |
|
| 673 |
@_process.register |
| 674 |
def _process_album(self, obj: Album, write: bool) -> None: |
| 675 |
"""Process an entire album.""" |
| 676 |
self._fetch_and_log_genre(obj) |
| 677 |
if "track" in self.sources: |
| 678 |
for item in obj.items(): |
| 679 |
self._process(item, write) |
| 680 |
|
| 681 |
if not self.config["pretend"]: |
| 682 |
obj.try_sync( |
| 683 |
write=write, move=False, inherit="track" not in self.sources |
| 684 |
) |
| 685 |
|
| 686 |
def commands(self) -> list[ui.Subcommand]: |
| 687 |
lastgenre_cmd = ui.Subcommand("lastgenre", help="fetch genres") |
| 688 |
lastgenre_cmd.parser.add_option( |
| 689 |
"-p", |
| 690 |
"--pretend", |
| 691 |
action="store_true", |
| 692 |
help="show actions but do nothing", |
| 693 |
) |
| 694 |
lastgenre_cmd.parser.add_option( |
| 695 |
"-f", |
| 696 |
"--force", |
| 697 |
dest="force", |
| 698 |
action="store_true", |
| 699 |
help="modify existing genres", |
| 700 |
) |
| 701 |
lastgenre_cmd.parser.add_option( |
| 702 |
"-F", |
| 703 |
"--no-force", |
| 704 |
dest="force", |
| 705 |
action="store_false", |
| 706 |
help="don't modify existing genres", |
| 707 |
) |
| 708 |
lastgenre_cmd.parser.add_option( |
| 709 |
"-k", |
| 710 |
"--keep-existing", |
| 711 |
dest="keep_existing", |
| 712 |
action="store_true", |
| 713 |
help="combine with existing genres when modifying", |
| 714 |
) |
| 715 |
lastgenre_cmd.parser.add_option( |
| 716 |
"-K", |
| 717 |
"--no-keep-existing", |
| 718 |
dest="keep_existing", |
| 719 |
action="store_false", |
| 720 |
help="don't combine with existing genres when modifying", |
| 721 |
) |
| 722 |
lastgenre_cmd.parser.add_option( |
| 723 |
"-s", |
| 724 |
"--source", |
| 725 |
dest="source", |
| 726 |
type="string", |
| 727 |
help="genre source: artist, album, or track", |
| 728 |
) |
| 729 |
lastgenre_cmd.parser.add_option( |
| 730 |
"-A", |
| 731 |
"--items", |
| 732 |
action="store_false", |
| 733 |
dest="album", |
| 734 |
help="match items instead of albums", |
| 735 |
) |
| 736 |
lastgenre_cmd.parser.add_option( |
| 737 |
"-a", |
| 738 |
"--albums", |
| 739 |
action="store_true", |
| 740 |
dest="album", |
| 741 |
help="match albums instead of items (default)", |
| 742 |
) |
| 743 |
lastgenre_cmd.parser.set_defaults(album=True) |
| 744 |
|
| 745 |
def lastgenre_func( |
| 746 |
lib: library.Library, opts: LastGenreCLIOpts, args: list[str] |
| 747 |
) -> None: |
| 748 |
self.config.set_args(vars(opts)) |
| 749 |
|
| 750 |
method = lib.albums if opts.album else lib.items |
| 751 |
for obj in method(args): |
| 752 |
self._process(obj, write=ui.should_write()) |
| 753 |
|
| 754 |
lastgenre_cmd.func = lastgenre_func |
| 755 |
return [lastgenre_cmd] |
| 756 |
|
| 757 |
def imported(self, _: ImportSession, task: ImportTask) -> None: |
| 758 |
self._process(task.album if task.is_album else task.item, write=False) # type: ignore[attr-defined] |