| 1 |
"""Moves "featured" artists to the title from the artist field.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import re |
| 6 |
from functools import cached_property, lru_cache |
| 7 |
from typing import TYPE_CHECKING |
| 8 |
|
| 9 |
from beets import config, plugins, ui |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
import optparse |
| 13 |
|
| 14 |
from beets.autotag import AlbumInfo, Info, TrackInfo |
| 15 |
from beets.importer import ImportSession, ImportTask |
| 16 |
from beets.library import Album, Item, Library |
| 17 |
|
| 18 |
DEFAULT_BRACKET_KEYWORDS: tuple[str, ...] = ( |
| 19 |
"abridged", |
| 20 |
"acapella", |
| 21 |
"club", |
| 22 |
"demo", |
| 23 |
"edit", |
| 24 |
"edition", |
| 25 |
"extended", |
| 26 |
"instrumental", |
| 27 |
"live", |
| 28 |
"mix", |
| 29 |
"radio", |
| 30 |
"release", |
| 31 |
"remaster", |
| 32 |
"remastered", |
| 33 |
"remix", |
| 34 |
"rmx", |
| 35 |
"unabridged", |
| 36 |
"unreleased", |
| 37 |
"version", |
| 38 |
"vip", |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
def _split_on_feat_token( |
| 43 |
regex: re.Pattern[str], artist: str |
| 44 |
) -> tuple[str, str] | None: |
| 45 |
match = regex.search(artist) |
| 46 |
if not match: |
| 47 |
return None |
| 48 |
|
| 49 |
left = artist[: match.start()].strip() |
| 50 |
right = artist[match.end() :].strip() |
| 51 |
opener = match.group(0)[0] |
| 52 |
|
| 53 |
if opener == "(": |
| 54 |
closing = ")" |
| 55 |
elif opener == "[": |
| 56 |
closing = "]" |
| 57 |
else: |
| 58 |
closing = None |
| 59 |
|
| 60 |
if closing: |
| 61 |
if right.endswith(closing): |
| 62 |
right = right[:-1].strip() |
| 63 |
else: |
| 64 |
left = f"{left} {opener}".strip() |
| 65 |
|
| 66 |
return left, right |
| 67 |
|
| 68 |
|
| 69 |
def split_on_feat( |
| 70 |
artist: str, for_artist: bool = True, custom_words: list[str] | None = None |
| 71 |
) -> tuple[str, str | None]: |
| 72 |
"""Given an artist string, split the "main" artist from any artist |
| 73 |
on the right-hand side of a string like "feat". Return the main |
| 74 |
artist, which is always a string, and the featuring artist, which |
| 75 |
may be a string or None if none is present. |
| 76 |
""" |
| 77 |
# Try explicit featuring tokens first (ft, feat, featuring, etc.) |
| 78 |
# to avoid splitting on generic separators like "&" when both are present |
| 79 |
regex_explicit = re.compile( |
| 80 |
plugins.feat_tokens(for_artist=False, custom_words=custom_words), |
| 81 |
re.IGNORECASE, |
| 82 |
) |
| 83 |
parts = _split_on_feat_token(regex_explicit, artist) |
| 84 |
if parts: |
| 85 |
return parts |
| 86 |
|
| 87 |
# Try comma as separator |
| 88 |
# (e.g. "Alice, Bob & Charlie" where Bob and Charlie are featuring) |
| 89 |
if for_artist and "," in artist: |
| 90 |
comma_parts = artist.split(",", 1) |
| 91 |
return comma_parts[0].strip(), comma_parts[1].strip() |
| 92 |
|
| 93 |
# Fall back to all tokens including generic separators if no explicit match |
| 94 |
if for_artist: |
| 95 |
regex = re.compile( |
| 96 |
plugins.feat_tokens(for_artist, custom_words), re.IGNORECASE |
| 97 |
) |
| 98 |
parts = _split_on_feat_token(regex, artist) |
| 99 |
if parts: |
| 100 |
return parts |
| 101 |
|
| 102 |
return artist.strip(), None |
| 103 |
|
| 104 |
|
| 105 |
def contains_feat(title: str, custom_words: list[str] | None = None) -> bool: |
| 106 |
"""Determine whether the title contains a "featured" marker.""" |
| 107 |
return bool( |
| 108 |
re.search( |
| 109 |
plugins.feat_tokens(for_artist=False, custom_words=custom_words), |
| 110 |
title, |
| 111 |
flags=re.IGNORECASE, |
| 112 |
) |
| 113 |
) |
| 114 |
|
| 115 |
|
| 116 |
def find_feat_part( |
| 117 |
artist: str, albumartist: str | None, custom_words: list[str] | None = None |
| 118 |
) -> str | None: |
| 119 |
"""Attempt to find featured artists in the item's artist fields and |
| 120 |
return the results. Returns None if no featured artist found. |
| 121 |
""" |
| 122 |
# If the album artist is featured, move the remaining artist to the title. |
| 123 |
artist_part, feat_part = split_on_feat(artist, custom_words=custom_words) |
| 124 |
if albumartist and feat_part == albumartist and artist_part: |
| 125 |
return artist_part |
| 126 |
|
| 127 |
# Handle a wider variety of extraction cases if the album artist is |
| 128 |
# contained within the track artist. |
| 129 |
if albumartist and albumartist in artist: |
| 130 |
albumartist_split = artist.split(albumartist, 1) |
| 131 |
|
| 132 |
# If the last element of the split (the right-hand side of the |
| 133 |
# album artist) is nonempty, then it probably contains the |
| 134 |
# featured artist. |
| 135 |
if albumartist_split[1] != "": |
| 136 |
# Extract the featured artist from the right-hand side. |
| 137 |
_, feat_part = split_on_feat( |
| 138 |
albumartist_split[1], custom_words=custom_words |
| 139 |
) |
| 140 |
return feat_part |
| 141 |
|
| 142 |
# Otherwise, if there's nothing on the right-hand side, |
| 143 |
# look for a featuring artist on the left-hand side. |
| 144 |
lhs, _ = split_on_feat(albumartist_split[0], custom_words=custom_words) |
| 145 |
if lhs: |
| 146 |
return lhs |
| 147 |
|
| 148 |
# Fall back to conservative handling of the track artist without relying |
| 149 |
# on albumartist, which covers compilations using a 'Various Artists' |
| 150 |
# albumartist and album tracks by a guest artist featuring a third artist. |
| 151 |
_, feat_part = split_on_feat(artist, False, custom_words) |
| 152 |
return feat_part |
| 153 |
|
| 154 |
|
| 155 |
def _album_artist_no_feat(album: Album) -> str: |
| 156 |
custom_words = config["ftintitle"]["custom_words"].as_str_seq() |
| 157 |
return split_on_feat(album["albumartist"], False, list(custom_words))[0] |
| 158 |
|
| 159 |
|
| 160 |
class FtInTitlePlugin(plugins.BeetsPlugin): |
| 161 |
@cached_property |
| 162 |
def auto(self) -> bool: |
| 163 |
return self.config["auto"].get(bool) |
| 164 |
|
| 165 |
@cached_property |
| 166 |
def drop_feat(self) -> bool: |
| 167 |
return self.config["drop"].get(bool) |
| 168 |
|
| 169 |
@cached_property |
| 170 |
def feat_format(self) -> str: |
| 171 |
return self.config["format"].as_str() |
| 172 |
|
| 173 |
@cached_property |
| 174 |
def keep_in_artist_field(self) -> bool: |
| 175 |
return self.config["keep_in_artist"].get(bool) |
| 176 |
|
| 177 |
@cached_property |
| 178 |
def preserve_album_artist(self) -> bool: |
| 179 |
return self.config["preserve_album_artist"].get(bool) |
| 180 |
|
| 181 |
@cached_property |
| 182 |
def custom_words(self) -> list[str]: |
| 183 |
return self.config["custom_words"].as_str_seq() |
| 184 |
|
| 185 |
@cached_property |
| 186 |
def bracket_keywords(self) -> list[str]: |
| 187 |
return self.config["bracket_keywords"].as_str_seq() |
| 188 |
|
| 189 |
@staticmethod |
| 190 |
@lru_cache(maxsize=256) |
| 191 |
def _bracket_position_pattern(keywords: tuple[str, ...]) -> re.Pattern[str]: |
| 192 |
""" |
| 193 |
Build a compiled regex to find the first bracketed segment that contains |
| 194 |
any of the provided keywords. |
| 195 |
|
| 196 |
Cached by keyword tuple to avoid recompiling on every track/title. |
| 197 |
""" |
| 198 |
kw_inner = "|".join(map(re.escape, keywords)) |
| 199 |
|
| 200 |
# If we have keywords, require one of them to appear in the bracket text. |
| 201 |
# If kw == "", the lookahead becomes true and we match any bracket content. |
| 202 |
kw = rf"\b(?={kw_inner})\b" if kw_inner else "" |
| 203 |
return re.compile( |
| 204 |
rf""" |
| 205 |
(?: # non-capturing group for the split |
| 206 |
\s*? # optional whitespace before brackets |
| 207 |
(?= # any bracket containing a keyword |
| 208 |
\([^)]*{kw}.*?\) |
| 209 |
| \[[^]]*{kw}.*?\] |
| 210 |
| <[^>]*{kw}.*? > |
| 211 |
| \{{[^}}]*{kw}.*?\}} |
| 212 |
| $ # or the end of the string |
| 213 |
) |
| 214 |
) |
| 215 |
""", |
| 216 |
re.IGNORECASE | re.VERBOSE, |
| 217 |
) |
| 218 |
|
| 219 |
def __init__(self) -> None: |
| 220 |
super().__init__() |
| 221 |
|
| 222 |
self.config.add( |
| 223 |
{ |
| 224 |
"auto": True, |
| 225 |
"drop": False, |
| 226 |
"format": "feat. {}", |
| 227 |
"keep_in_artist": False, |
| 228 |
"preserve_album_artist": True, |
| 229 |
"custom_words": [], |
| 230 |
"bracket_keywords": list(DEFAULT_BRACKET_KEYWORDS), |
| 231 |
} |
| 232 |
) |
| 233 |
|
| 234 |
self._command = ui.Subcommand( |
| 235 |
"ftintitle", help="move featured artists to the title field" |
| 236 |
) |
| 237 |
|
| 238 |
self._command.parser.add_option( |
| 239 |
"-d", |
| 240 |
"--drop", |
| 241 |
dest="drop", |
| 242 |
action="store_true", |
| 243 |
default=None, |
| 244 |
help="drop featuring from artists and ignore title update", |
| 245 |
) |
| 246 |
|
| 247 |
self.import_stages = [self.imported] |
| 248 |
if self.auto: |
| 249 |
self.register_listener( |
| 250 |
"trackinfo_received", self.trackinfo_received |
| 251 |
) |
| 252 |
self.register_listener( |
| 253 |
"albuminfo_received", self.albuminfo_received |
| 254 |
) |
| 255 |
|
| 256 |
self.album_template_fields["album_artist_no_feat"] = ( |
| 257 |
_album_artist_no_feat |
| 258 |
) |
| 259 |
|
| 260 |
def commands(self) -> list[ui.Subcommand]: |
| 261 |
def func(lib: Library, opts: optparse.Values, args: list[str]) -> None: |
| 262 |
self.config.set_args(opts) |
| 263 |
write = ui.should_write() |
| 264 |
|
| 265 |
for item in lib.items(args): |
| 266 |
if self.ft_in_title(item, item.get("albumartist") or ""): |
| 267 |
item.store() |
| 268 |
if write: |
| 269 |
item.try_write() |
| 270 |
|
| 271 |
self._command.func = func |
| 272 |
return [self._command] |
| 273 |
|
| 274 |
def imported(self, session: ImportSession, task: ImportTask) -> None: |
| 275 |
"""Import hook for moving featuring artist automatically.""" |
| 276 |
if not self.auto: |
| 277 |
return |
| 278 |
|
| 279 |
for item in task.imported_items(): |
| 280 |
if self.ft_in_title(item, item.get("albumartist") or ""): |
| 281 |
item.store() |
| 282 |
|
| 283 |
def update_metadata(self, metadata: Item | Info, feat_part: str) -> bool: |
| 284 |
"""Choose how to add new artists to the title and set the new |
| 285 |
metadata. Also, print out messages about any changes that are made. |
| 286 |
If `drop_feat` is set, then do not add the artist to the title; just |
| 287 |
remove it from the artist field. |
| 288 |
""" |
| 289 |
changed = False |
| 290 |
artist = metadata.get("artist") or "" |
| 291 |
# In case the artist is kept, do not update the artist fields. |
| 292 |
if self.keep_in_artist_field: |
| 293 |
self._log.info( |
| 294 |
"artist: {} (Not changing due to keep_in_artist)", artist |
| 295 |
) |
| 296 |
else: |
| 297 |
track_artist, _ = split_on_feat( |
| 298 |
artist, custom_words=self.custom_words |
| 299 |
) |
| 300 |
self._log.info("artist: {} -> {}", artist, track_artist) |
| 301 |
metadata["artist"] = track_artist |
| 302 |
changed |= artist != track_artist |
| 303 |
|
| 304 |
if artist_sort := metadata.get("artist_sort"): |
| 305 |
# Just strip the featured artist from the sort name. |
| 306 |
artist_sort_no_feat, _ = split_on_feat( |
| 307 |
artist_sort, custom_words=self.custom_words |
| 308 |
) |
| 309 |
metadata["artist_sort"] = artist_sort_no_feat |
| 310 |
changed |= artist_sort != artist_sort_no_feat |
| 311 |
|
| 312 |
# Only update the title if it does not already contain a featured |
| 313 |
# artist and if we do not drop featuring information. |
| 314 |
title = metadata.get("title") or "" |
| 315 |
if not self.drop_feat and not contains_feat(title, self.custom_words): |
| 316 |
formatted = self.feat_format.format(feat_part) |
| 317 |
new_title = self.insert_ft_into_title( |
| 318 |
title, formatted, self.bracket_keywords |
| 319 |
) |
| 320 |
self._log.info("title: {} -> {}", title, new_title) |
| 321 |
metadata["title"] = new_title |
| 322 |
changed |= title != new_title |
| 323 |
|
| 324 |
return changed |
| 325 |
|
| 326 |
def trackinfo_received(self, info: TrackInfo) -> None: |
| 327 |
"""Move featuring artists in fetched singleton metadata.""" |
| 328 |
self.ft_in_title(info, "") |
| 329 |
|
| 330 |
def albuminfo_received(self, info: AlbumInfo) -> None: |
| 331 |
"""Move featuring artists in fetched album track metadata.""" |
| 332 |
albumartist = info.get("artist") or "" |
| 333 |
for track_info in info.tracks: |
| 334 |
self.ft_in_title(track_info, albumartist) |
| 335 |
|
| 336 |
def ft_in_title(self, item: Item | Info, albumartist: str) -> bool: |
| 337 |
"""Look for featured artists in the item's artist fields and move them |
| 338 |
to the title. |
| 339 |
|
| 340 |
Returns: |
| 341 |
True if the item has been modified. False otherwise. |
| 342 |
""" |
| 343 |
artist = (item.get("artist") or "").strip() |
| 344 |
albumartist = albumartist.strip() |
| 345 |
if not self._has_feat_candidate(artist, albumartist): |
| 346 |
return False |
| 347 |
|
| 348 |
if hasattr(item, "filepath"): |
| 349 |
self._log.info("{.filepath}", item) |
| 350 |
feat_part = find_feat_part(artist, albumartist, self.custom_words) |
| 351 |
if not feat_part: |
| 352 |
self._log.info("no featuring artists found") |
| 353 |
return False |
| 354 |
|
| 355 |
return self.update_metadata(item, feat_part) |
| 356 |
|
| 357 |
def _has_feat_candidate(self, artist: str, albumartist: str | None) -> bool: |
| 358 |
albumartist = (albumartist or "").strip() |
| 359 |
if self.preserve_album_artist and albumartist and artist == albumartist: |
| 360 |
return False |
| 361 |
|
| 362 |
for_artist = not albumartist or albumartist in artist |
| 363 |
_, featured = split_on_feat( |
| 364 |
artist, for_artist=for_artist, custom_words=self.custom_words |
| 365 |
) |
| 366 |
return bool(featured) |
| 367 |
|
| 368 |
@classmethod |
| 369 |
def insert_ft_into_title( |
| 370 |
cls, title: str, feat_part: str, keywords: list[str] | None = None |
| 371 |
) -> str: |
| 372 |
"""Insert featured artist before the first bracket containing |
| 373 |
remix/edit keywords if present. |
| 374 |
""" |
| 375 |
normalized = ( |
| 376 |
DEFAULT_BRACKET_KEYWORDS if keywords is None else tuple(keywords) |
| 377 |
) |
| 378 |
pattern = cls._bracket_position_pattern(normalized) |
| 379 |
parts = pattern.split(title, maxsplit=1) |
| 380 |
return f" {feat_part} ".join(parts).strip() |