-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy path__init__.py
More file actions
728 lines (631 loc) · 27.2 KB
/
__init__.py
File metadata and controls
728 lines (631 loc) · 27.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Gets genres for imported music based on Last.fm tags.
Uses a provided whitelist file to determine which tags are valid genres.
The included (default) genre list was originally produced by scraping Wikipedia
and has been edited to remove some questionable entries.
The scraper script used is available here:
https://gist.github.com/1241307
"""
from __future__ import annotations
import os
import re
from collections import defaultdict
from functools import singledispatchmethod
from pathlib import Path
from typing import TYPE_CHECKING, Any
import yaml
from beets import config, library, plugins, ui
from beets.library import Album, Item
from beets.logging import extra_debug
from beets.ui import UserError
from beets.util import plurality, unique_list
from .client import LastFmClient
if TYPE_CHECKING:
import optparse
from collections.abc import Iterable
from beets.importer import ImportSession, ImportTask
from beets.library import LibModel
Whitelist = set[str]
"""Set of valid genre names (lowercase). Empty set means all genres allowed."""
CanonTree = list[list[str]]
"""Genre hierarchy as list of paths from general to specific.
Example: [['electronic', 'house'], ['electronic', 'techno']]"""
RawBlacklist = dict[str, list[str]]
"""Mapping of artist name to list of raw regex/string patterns."""
Blacklist = dict[str, list[re.Pattern[str]]]
"""Mapping of artist name to list of compiled case-insensitive patterns."""
# Canonicalization tree processing.
def flatten_tree(
elem: dict[Any, Any] | list[Any] | str,
path: list[str],
branches: CanonTree,
) -> None:
"""Flatten nested lists/dictionaries into lists of strings
(branches).
"""
if not path:
path = []
if isinstance(elem, dict):
for k, v in elem.items():
flatten_tree(v, [*path, k], branches)
elif isinstance(elem, list):
for sub in elem:
flatten_tree(sub, path, branches)
else:
branches.append([*path, str(elem)])
def find_parents(candidate: str, branches: CanonTree) -> list[str]:
"""Find parents genre of a given genre, ordered from the closest to
the further parent.
"""
for branch in branches:
try:
idx = branch.index(candidate.lower())
return list(reversed(branch[: idx + 1]))
except ValueError:
continue
return [candidate]
def get_depth(tag: str, branches: CanonTree) -> int | None:
"""Find the depth of a tag in the genres tree."""
for branch in branches:
if tag in branch:
return branch.index(tag)
return None
def sort_by_depth(tags: list[str], branches: CanonTree) -> list[str]:
"""Given a list of tags, sort the tags by their depths in the genre tree."""
depth_tag_pairs = [(get_depth(t, branches), t) for t in tags]
depth_tag_pairs = [e for e in depth_tag_pairs if e[0] is not None]
depth_tag_pairs.sort(reverse=True)
return [p[1] for p in depth_tag_pairs]
# Main plugin logic.
WHITELIST = os.path.join(os.path.dirname(__file__), "genres.txt")
C14N_TREE = os.path.join(os.path.dirname(__file__), "genres-tree.yaml")
class LastGenrePlugin(plugins.BeetsPlugin):
def __init__(self) -> None:
super().__init__()
self.config.add(
{
"whitelist": True,
"min_weight": 10,
"count": 1,
"fallback": None,
"canonical": False,
"cleanup_existing": False,
"source": "album",
"force": False,
"keep_existing": False,
"auto": True,
"prefer_specific": False,
"title_case": True,
"pretend": False,
"blacklist": False,
}
)
self.setup()
def setup(self) -> None:
"""Setup plugin from config options"""
if self.config["auto"]:
self.import_stages = [self.imported]
self.whitelist: Whitelist = self._load_whitelist()
self.c14n_branches: CanonTree
self.c14n_branches, self.canonicalize = self._load_c14n_tree()
self.blacklist: Blacklist = self._load_blacklist()
self.client = LastFmClient(
self._log, self.config["min_weight"].get(int), self.blacklist
)
def _load_whitelist(self) -> Whitelist:
"""Load the whitelist from a text file.
Default whitelist is used if config is True, empty string or set to "nothing".
"""
whitelist = set()
wl_filename = self.config["whitelist"].get()
if wl_filename in (True, "", None): # Indicates the default whitelist.
wl_filename = WHITELIST
if wl_filename:
self._log.debug("Loading whitelist {}", wl_filename)
text = Path(wl_filename).expanduser().read_text(encoding="utf-8")
for line in text.splitlines():
if (line := line.strip().lower()) and not line.startswith("#"):
whitelist.add(line)
return whitelist
def _load_c14n_tree(self) -> tuple[CanonTree, bool]:
"""Load the canonicalization tree from a YAML file.
Default tree is used if config is True, empty string, set to "nothing"
or if prefer_specific is enabled.
"""
c14n_branches: CanonTree = []
c14n_filename = self.config["canonical"].get()
canonicalize = c14n_filename is not False
# Default tree
if c14n_filename in (True, "", None) or (
# prefer_specific requires a tree, load default tree
not canonicalize and self.config["prefer_specific"].get()
):
c14n_filename = C14N_TREE
# Read the tree
if c14n_filename:
self._log.debug("Loading canonicalization tree {}", c14n_filename)
with Path(c14n_filename).expanduser().open(encoding="utf-8") as f:
genres_tree = yaml.safe_load(f)
flatten_tree(genres_tree, [], c14n_branches)
return c14n_branches, canonicalize
def _load_blacklist(self) -> Blacklist:
"""Load the blacklist from a configured file path.
For maximum compatibility with regex patterns, a custom format is used:
- Each section starts with an artist name, followed by a colon.
- Subsequent lines are indented (at least one space, typically 4 spaces)
and contain a regex pattern to match a genre.
- A '*' key for artist can be used to specify global forbidden genres.
Returns a compiled blacklist dictionary mapping artist names to lists of
case-insensitive regex patterns. Returns empty dict if not configured.
Example blacklist file format::
Artist Name:
.*rock.*
.*metal.*
Another Artist Name:
^jazz$
*:
spoken word
comedy
Raises:
UserError: if the file format is invalid.
"""
blacklist_raw: RawBlacklist = defaultdict(list)
bl_filename = self.config["blacklist"].get()
if not bl_filename:
return {}
if not isinstance(bl_filename, str):
raise UserError(
"Invalid value for lastgenre.blacklist: expected path string "
f"or 'no', got {bl_filename!r} (type {type(bl_filename).__name__})"
)
self._log.debug("Loading blacklist file {}", bl_filename)
section = None
with Path(bl_filename).expanduser().open(encoding="utf-8") as f:
for lineno, line in enumerate(f, 1):
if not line.strip() or line.lstrip().startswith("#"):
continue
if not line.startswith(" "):
# Section header
header = line.strip().lower()
if not header.endswith(":"):
raise UserError(
f"Malformed blacklist section header "
f"at line {lineno}: {line}"
)
section = header[:-1].rstrip()
if not section:
raise UserError(
f"Empty blacklist section name "
f"at line {lineno}: {line}"
)
else:
# Pattern line: must be indented (at least one space)
if section is None:
raise UserError(
f"Blacklist regex pattern line before any section header "
f"at line {lineno}: {line}"
)
blacklist_raw[section].append(line.strip())
extra_debug(self._log, "Blacklist: {}", blacklist_raw)
return self._compile_blacklist_patterns(blacklist_raw)
@staticmethod
def _compile_blacklist_patterns(
blacklist: RawBlacklist,
) -> Blacklist:
"""Compile blacklist patterns into regex objects.
Tries regex compilation first, falls back to literal string matching.
That way users can use regexes for flexible matching but also simple
strings without worrying about regex syntax. All patterns are
case-insensitive.
"""
compiled_blacklist: defaultdict[str, list[re.Pattern[str]]] = (
defaultdict(list)
)
for artist, patterns in blacklist.items():
compiled_patterns = []
for pattern in patterns:
try:
compiled_patterns.append(re.compile(pattern, re.IGNORECASE))
except re.error:
compiled_patterns.append(
re.compile(re.escape(pattern), re.IGNORECASE)
)
compiled_blacklist[artist] = compiled_patterns
return compiled_blacklist
@property
def sources(self) -> tuple[str, ...]:
"""A tuple of allowed genre sources. May contain 'track',
'album', or 'artist.'
"""
return self.config["source"].as_choice(
{
"track": ("track", "album", "artist"),
"album": ("album", "artist"),
"artist": ("artist",),
}
)
# Genre list processing.
def _resolve_genres(
self, tags: list[str], artist: str | None = None
) -> list[str]:
"""Canonicalize, sort and filter a list of genres.
- Returns an empty list if the input tags list is empty.
- If canonicalization is enabled, it extends the list by incorporating
parent genres from the canonicalization tree. When a whitelist is set,
only parent tags that pass the whitelist filter are included;
otherwise, it adds the oldest ancestor. Adding parent tags is stopped
when the count of tags reaches the configured limit (count).
- The tags list is then deduplicated to ensure only unique genres are
retained.
- If the 'prefer_specific' configuration is enabled, the list is sorted
by the specificity (depth in the canonicalization tree) of the genres.
- Finally applies whitelist filtering to ensure that only valid
genres are kept. (This may result in no genres at all being retained).
- Returns the filtered list of genres, limited to the configured count.
"""
if not tags:
return []
count = self.config["count"].get(int)
# Canonicalization (if enabled)
if self.canonicalize:
# Extend the list to consider tags parents in the c14n tree
tags_all = []
for tag in tags:
# Skip blacklisted tags entirely — don't walk their ancestry.
if self._is_blacklisted(tag, artist):
continue
# Add parents that pass whitelist/blacklist, or add the oldest
# ancestor if neither is configured
if self.whitelist or self.blacklist:
parents = self._filter_valid(
find_parents(tag, self.c14n_branches),
artist=artist,
)
else:
parents = [find_parents(tag, self.c14n_branches)[-1]]
tags_all += parents
# Stop if we have enough tags already, unless we need to find
# the most specific tag (instead of the most popular).
if (
not self.config["prefer_specific"]
and len(tags_all) >= count
):
break
tags = tags_all
tags = unique_list(tags)
# Sort the tags by specificity.
if self.config["prefer_specific"]:
tags = sort_by_depth(tags, self.c14n_branches)
# Final filter: catches forbidden genres when c14n is disabled,
# and any that survived the loop without whitelist/blacklist active.
valid_tags = self._filter_valid(tags, artist=artist)
return valid_tags[:count]
def _filter_valid(
self, genres: Iterable[str], artist: str | None = None
) -> list[str]:
"""Filter genres through whitelist and blacklist.
Drops empty/whitespace-only strings, then applies whitelist and
blacklist checks. Returns all genres if neither is configured.
Whitelist is checked first for performance reasons (blacklist regex
matching is more expensive).
"""
cleaned = [g for g in genres if g and g.strip()]
if not self.whitelist and not self.blacklist:
return cleaned
result = []
for genre in cleaned:
if self.whitelist and genre.lower() not in self.whitelist:
continue
if self._is_blacklisted(genre, artist):
continue
result.append(genre)
return result
def _is_blacklisted(self, genre: str, artist: str | None = None) -> bool:
"""Check if genre tag should be forbidden.
Returns True if:
- tag matches global blacklist, OR
- artist matches artist blacklist AND tag matches artist blacklist.
Tags pass if no blacklist match found.
KEEP DUPLICATED IN SYNC with client._is_blacklisted().
TODO: Extract to filters.py when regex genre aliases land (next PR).
"""
if not self.blacklist:
return False
genre_lower = genre.lower()
for pattern in self.blacklist.get("*") or []:
if pattern.search(genre_lower):
return True
if artist:
for pattern in self.blacklist.get(artist.lower()) or []:
if pattern.search(genre_lower):
return True
return False
# Genre resolution pipeline.
def _format_genres(self, tags: list[str]) -> list[str]:
"""Format to title case if configured."""
if self.config["title_case"]:
return [tag.title() for tag in tags]
else:
return tags
def _get_existing_genres(self, obj: LibModel) -> list[str]:
"""Return a list of genres for this Item or Album."""
if isinstance(obj, library.Item):
genres_list = obj.get("genres", with_album=False)
else:
genres_list = obj.get("genres")
return genres_list
def _combine_resolve_and_log(
self, old: list[str], new: list[str], artist: str | None = None
) -> list[str]:
"""Combine old and new genres and process via _resolve_genres."""
self._log.debug("raw last.fm tags: {}", new)
self._log.debug("existing genres taken into account: {}", old)
combined = old + new
return self._resolve_genres(combined, artist=artist)
def _get_genre(self, obj: LibModel) -> tuple[list[str], str]:
"""Get the final genre list for an Album or Item object.
`self.sources` specifies allowed genre sources. Starting with the first
source in this tuple, the following stages run through until a genre is
found or no options are left:
- track (for Items only)
- album
- artist, albumartist or "most popular track genre" (for VA-albums)
- original fallback
- configured fallback
- empty list
A `(genres, label)` pair is returned, where `label` is a string used for
logging. For example, "keep + artist, whitelist" indicates that existing
genres were combined with new last.fm genres and whitelist filtering was
applied, while "artist, any" means only new last.fm genres are included
and the whitelist feature was disabled.
"""
def _fallback_stage() -> tuple[list[str], str]:
"""Return the fallback genre and label."""
if fallback := self.config["fallback"].get():
return [fallback], "fallback"
return [], "fallback unconfigured"
def _try_resolve_stage(
stage_label: str,
keep_genres: list[str],
new_genres: list[str],
artist: str | None = None,
) -> tuple[list[str], str] | None:
"""Try to resolve genres for a given stage and log the result."""
resolved_genres = self._combine_resolve_and_log(
keep_genres, new_genres, artist=artist
)
if resolved_genres:
suffix = "whitelist" if self.whitelist else "any"
label = f"{stage_label}, {suffix}"
if keep_genres:
label = f"keep + {label}"
return self._format_genres(resolved_genres), label
return None
keep_genres = []
new_genres = []
genres = self._get_existing_genres(obj)
if genres and not self.config["force"]:
# Without force, but cleanup_existing enabled, we attempt
# to canonicalize pre-populated tags before returning them.
# If none are found, we use the fallback (if set).
if self.config["cleanup_existing"]:
keep_genres = [g.lower() for g in genres]
cleanup_artist = getattr(obj, "albumartist", None) or getattr(
obj, "artist", None
)
if result := _try_resolve_stage(
"cleanup", keep_genres, [], artist=cleanup_artist
):
return result
return _fallback_stage()
# If cleanup_existing is not set, the pre-populated tags are
# returned as-is.
return genres, "keep any, no-force"
if self.config["force"]:
# Force doesn't keep any unless keep_existing is set.
# Whitelist validation is handled in _resolve_genres.
if self.config["keep_existing"]:
keep_genres = [g.lower() for g in genres]
# Run through stages: track, album, artist,
# album artist, or most popular track genre.
if isinstance(obj, library.Item) and "track" in self.sources:
if new_genres := self.client.fetch_track_genre(
obj.artist, obj.title
):
if result := _try_resolve_stage(
"track", keep_genres, new_genres, artist=obj.artist
):
return result
if "album" in self.sources:
if new_genres := self.client.fetch_album_genre(
obj.albumartist, obj.album
):
if result := _try_resolve_stage(
"album", keep_genres, new_genres, artist=obj.albumartist
):
return result
if "artist" in self.sources:
new_genres = []
stage_artist: str | None = None
if isinstance(obj, library.Item):
new_genres = self.client.fetch_artist_genre(obj.artist)
stage_label = "artist"
stage_artist = obj.artist
elif obj.albumartist != config["va_name"].as_str():
new_genres = self.client.fetch_artist_genre(obj.albumartist)
stage_label = "album artist"
stage_artist = obj.albumartist
if not new_genres:
extra_debug(
self._log,
'No album artist genre found for "{}", '
"trying multi-valued field...",
obj.albumartist,
)
for albumartist in obj.albumartists:
extra_debug(
self._log,
'Fetching artist genre for "{}"',
albumartist,
)
new_genres += self.client.fetch_artist_genre(
albumartist
)
if new_genres:
stage_label = "multi-valued album artist"
else:
# For "Various Artists", pick the most popular track genre.
item_genres = []
assert isinstance(obj, Album) # Type narrowing for mypy
for item in obj.items():
item_genre = None
if "track" in self.sources:
item_genre = self.client.fetch_track_genre(
item.artist, item.title
)
if not item_genre:
item_genre = self.client.fetch_artist_genre(item.artist)
if item_genre:
item_genres += item_genre
if item_genres:
most_popular, rank = plurality(item_genres)
new_genres = [most_popular]
stage_label = "most popular track"
self._log.debug(
'Most popular track genre "{}" ({}) for VA album.',
most_popular,
rank,
)
if new_genres:
if result := _try_resolve_stage(
stage_label, keep_genres, new_genres, artist=stage_artist
):
return result
# Nothing found, leave original if configured and valid.
if genres and self.config["keep_existing"].get():
if isinstance(obj, library.Item):
# For track items, use track artist (important for compilations).
artist = getattr(obj, "artist", None)
else:
# For albums, prefer albumartist, fall back to artist.
artist = getattr(obj, "albumartist", None) or getattr(
obj, "artist", None
)
if valid_genres := self._filter_valid(genres, artist=artist):
return valid_genres, "original fallback"
# If the original genre doesn't match a whitelisted genre, check
# if we can canonicalize it to find a matching, whitelisted genre!
if result := _try_resolve_stage(
"original fallback", keep_genres, [], artist=artist
):
return result
return _fallback_stage()
# Beets plugin hooks and CLI.
def _fetch_and_log_genre(self, obj: LibModel) -> None:
"""Fetch genre and log it."""
self._log.info(str(obj))
obj.genres, label = self._get_genre(obj)
self._log.debug("Resolved ({}): {}", label, obj.genres)
ui.show_model_changes(obj, fields=["genres"], print_obj=False)
@singledispatchmethod
def _process(self, obj: LibModel, write: bool) -> None:
"""Process an object, dispatching to the appropriate method."""
raise NotImplementedError
@_process.register
def _process_track(self, obj: Item, write: bool) -> None:
"""Process a single track/item."""
self._fetch_and_log_genre(obj)
if not self.config["pretend"]:
obj.try_sync(write=write, move=False)
@_process.register
def _process_album(self, obj: Album, write: bool) -> None:
"""Process an entire album."""
self._fetch_and_log_genre(obj)
if "track" in self.sources:
for item in obj.items():
self._process(item, write)
if not self.config["pretend"]:
obj.try_sync(
write=write, move=False, inherit="track" not in self.sources
)
def commands(self) -> list[ui.Subcommand]:
lastgenre_cmd = ui.Subcommand("lastgenre", help="fetch genres")
lastgenre_cmd.parser.add_option(
"-p",
"--pretend",
action="store_true",
help="show actions but do nothing",
)
lastgenre_cmd.parser.add_option(
"-f",
"--force",
dest="force",
action="store_true",
help="modify existing genres",
)
lastgenre_cmd.parser.add_option(
"-F",
"--no-force",
dest="force",
action="store_false",
help="don't modify existing genres",
)
lastgenre_cmd.parser.add_option(
"-k",
"--keep-existing",
dest="keep_existing",
action="store_true",
help="combine with existing genres when modifying",
)
lastgenre_cmd.parser.add_option(
"-K",
"--no-keep-existing",
dest="keep_existing",
action="store_false",
help="don't combine with existing genres when modifying",
)
lastgenre_cmd.parser.add_option(
"-s",
"--source",
dest="source",
type="string",
help="genre source: artist, album, or track",
)
lastgenre_cmd.parser.add_option(
"-A",
"--items",
action="store_false",
dest="album",
help="match items instead of albums",
)
lastgenre_cmd.parser.add_option(
"-a",
"--albums",
action="store_true",
dest="album",
help="match albums instead of items (default)",
)
lastgenre_cmd.parser.set_defaults(album=True)
def lastgenre_func(
lib: library.Library, opts: optparse.Values, args: list[str]
) -> None:
self.config.set_args(opts)
method = lib.albums if opts.album else lib.items
for obj in method(args):
self._process(obj, write=ui.should_write())
lastgenre_cmd.func = lastgenre_func
return [lastgenre_cmd]
def imported(self, _: ImportSession, task: ImportTask) -> None:
self._process(task.album if task.is_album else task.item, write=False) # type: ignore[attr-defined]