| 1 |
"""Adds Discogs album search support to the autotagger. Requires the |
| 2 |
python3-discogs-client library. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import http.client |
| 8 |
import json |
| 9 |
import os |
| 10 |
import re |
| 11 |
import socket |
| 12 |
import time |
| 13 |
import traceback |
| 14 |
from functools import cache, cached_property |
| 15 |
from itertools import groupby |
| 16 |
from string import ascii_lowercase |
| 17 |
from typing import TYPE_CHECKING |
| 18 |
|
| 19 |
import confuse |
| 20 |
import requests |
| 21 |
from discogs_client import Client, Master, Release |
| 22 |
from discogs_client.exceptions import DiscogsAPIError |
| 23 |
|
| 24 |
import beets |
| 25 |
import beets.ui |
| 26 |
from beets import config, util |
| 27 |
from beets.autotag import AlbumInfo, TrackInfo, string_dist |
| 28 |
from beets.exceptions import UserError |
| 29 |
from beets.metadata_plugins import IDResponse, SearchApiMetadataSourcePlugin |
| 30 |
|
| 31 |
from .states import DISAMBIGUATION_RE, ArtistState, TracklistState |
| 32 |
|
| 33 |
if TYPE_CHECKING: |
| 34 |
from collections.abc import Callable, Iterator, Sequence |
| 35 |
|
| 36 |
from beets.importer import ImportSession |
| 37 |
from beets.library import Item |
| 38 |
from beets.metadata_plugins import QueryType, SearchParams |
| 39 |
|
| 40 |
from .types import AudioTrack, IndexTrack, ReleaseFormat, Track |
| 41 |
|
| 42 |
USER_AGENT = f"beets/{beets.__version__} +https://beets.io/" |
| 43 |
API_KEY = "rAzVUQYRaoFjeBjyWuWZ" |
| 44 |
API_SECRET = "plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy" |
| 45 |
|
| 46 |
|
| 47 |
# Exceptions that discogs_client should really handle but does not. |
| 48 |
CONNECTION_ERRORS = ( |
| 49 |
requests.exceptions.ConnectionError, |
| 50 |
socket.error, |
| 51 |
http.client.HTTPException, |
| 52 |
ValueError, # JSON decoding raises a ValueError. |
| 53 |
DiscogsAPIError, |
| 54 |
) |
| 55 |
|
| 56 |
TRACK_INDEX_RE = re.compile( |
| 57 |
r""" |
| 58 |
(.*?) # medium: everything before medium_index. |
| 59 |
(\d*?) # medium_index: a number at the end of |
| 60 |
# `position`, except if followed by a subtrack index. |
| 61 |
# subtrack_index: can only be matched if medium |
| 62 |
# or medium_index have been matched, and can be |
| 63 |
( |
| 64 |
(?<=\w)\.[\w]+ # a dot followed by a string (A.1, 2.A) |
| 65 |
| (?<=\d)[A-Z]+ # a string that follows a number (1A, B2a) |
| 66 |
)? |
| 67 |
""", |
| 68 |
re.VERBOSE, |
| 69 |
) |
| 70 |
|
| 71 |
RELEASE_DATE_RE = re.compile( |
| 72 |
r"(?P<year>\d{4})(?:-(?P<month>\d{1,2})(?:-(?P<day>\d{1,2}))?)?" |
| 73 |
) |
| 74 |
|
| 75 |
FIELDS_TO_DISCOGS_KEYS = { |
| 76 |
"barcode": "barcode", |
| 77 |
"catalognum": "catno", |
| 78 |
"country": "country", |
| 79 |
"label": "label", |
| 80 |
"media": "format", |
| 81 |
"year": "year", |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
def parse_release_date( |
| 86 |
released: str | None, year: int | None |
| 87 |
) -> tuple[int | None, int | None, int | None]: |
| 88 |
"""Return the ``(year, month, day)`` a release was issued on. |
| 89 |
|
| 90 |
Discogs reports the year of a release in its own field but the rest of |
| 91 |
the date only as part of `released`, which is absent or partial for many |
| 92 |
releases. `year` is therefore used for any component `released` does not |
| 93 |
provide. |
| 94 |
""" |
| 95 |
if not (m := RELEASE_DATE_RE.fullmatch((released or "").strip())): |
| 96 |
return year, None, None |
| 97 |
|
| 98 |
released_year, month, day = ( |
| 99 |
int(i) if i else 0 for i in m.group("year", "month", "day") |
| 100 |
) |
| 101 |
|
| 102 |
# A zero stands for "unknown" in Discogs' dates, as does a missing group. |
| 103 |
return released_year or year, month or None, day or None |
| 104 |
|
| 105 |
|
| 106 |
class DiscogsPlugin(SearchApiMetadataSourcePlugin[IDResponse]): |
| 107 |
def __init__(self) -> None: |
| 108 |
super().__init__() |
| 109 |
self.config.add( |
| 110 |
{ |
| 111 |
"apikey": API_KEY, |
| 112 |
"apisecret": API_SECRET, |
| 113 |
"tokenfile": "discogs_token.json", |
| 114 |
"user_token": "", |
| 115 |
"separator": ", ", |
| 116 |
"index_tracks": False, |
| 117 |
"append_style_genre": False, |
| 118 |
"strip_disambiguation": True, |
| 119 |
"featured_string": "Feat.", |
| 120 |
"extra_tags": [], |
| 121 |
"anv": { |
| 122 |
"artist_credit": True, |
| 123 |
"artist": False, |
| 124 |
"album_artist": False, |
| 125 |
}, |
| 126 |
} |
| 127 |
) |
| 128 |
self.config["apikey"].redact = True |
| 129 |
self.config["apisecret"].redact = True |
| 130 |
self.config["user_token"].redact = True |
| 131 |
self.setup() |
| 132 |
|
| 133 |
@cached_property |
| 134 |
def extra_discogs_field_by_tag(self) -> dict[str, str]: |
| 135 |
"""Map configured extra tags to Discogs API search parameters. |
| 136 |
|
| 137 |
Process user configuration to determine which additional Discogs |
| 138 |
fields should be included in search queries. |
| 139 |
""" |
| 140 |
field_by_tag = { |
| 141 |
tag: FIELDS_TO_DISCOGS_KEYS[tag] |
| 142 |
for tag in self.config["extra_tags"].as_str_seq() |
| 143 |
if tag in FIELDS_TO_DISCOGS_KEYS |
| 144 |
} |
| 145 |
if field_by_tag: |
| 146 |
self._log.debug( |
| 147 |
"Discogs additional search filters from tags: {}", field_by_tag |
| 148 |
) |
| 149 |
|
| 150 |
return field_by_tag |
| 151 |
|
| 152 |
def setup(self, session: ImportSession | None = None) -> None: |
| 153 |
"""Create the `discogs_client` field. Authenticate if necessary.""" |
| 154 |
c_key = self.config["apikey"].as_str() |
| 155 |
c_secret = self.config["apisecret"].as_str() |
| 156 |
|
| 157 |
# Try using a configured user token (bypassing OAuth login). |
| 158 |
user_token = self.config["user_token"].as_str() |
| 159 |
if user_token: |
| 160 |
# The rate limit for authenticated users goes up to 60 |
| 161 |
# requests per minute. |
| 162 |
self.discogs_client = Client(USER_AGENT, user_token=user_token) |
| 163 |
return |
| 164 |
|
| 165 |
# Get the OAuth token from a file or log in. |
| 166 |
try: |
| 167 |
with open(self._tokenfile()) as f: |
| 168 |
tokendata = json.load(f) |
| 169 |
except OSError: |
| 170 |
# No token yet. Generate one. |
| 171 |
token, secret = self.authenticate(c_key, c_secret) |
| 172 |
else: |
| 173 |
token = tokendata["token"] |
| 174 |
secret = tokendata["secret"] |
| 175 |
|
| 176 |
self.discogs_client = Client(USER_AGENT, c_key, c_secret, token, secret) |
| 177 |
|
| 178 |
def reset_auth(self) -> None: |
| 179 |
"""Delete token file & redo the auth steps.""" |
| 180 |
os.remove(self._tokenfile()) |
| 181 |
self.setup() |
| 182 |
|
| 183 |
def _tokenfile(self) -> str: |
| 184 |
"""Get the path to the JSON file for storing the OAuth token.""" |
| 185 |
return self.config["tokenfile"].get(confuse.Filename(in_app_dir=True)) |
| 186 |
|
| 187 |
def authenticate(self, c_key: str, c_secret: str) -> tuple[str, str]: |
| 188 |
# Get the link for the OAuth page. |
| 189 |
auth_client = Client(USER_AGENT, c_key, c_secret) |
| 190 |
try: |
| 191 |
_, _, url = auth_client.get_authorize_url() |
| 192 |
except CONNECTION_ERRORS as e: |
| 193 |
self._log.debug("connection error: {}", e) |
| 194 |
raise UserError("communication with Discogs failed") |
| 195 |
|
| 196 |
beets.ui.print_("To authenticate with Discogs, visit:") |
| 197 |
beets.ui.print_(url) |
| 198 |
|
| 199 |
# Ask for the code and validate it. |
| 200 |
code = beets.ui.input_("Enter the code:") |
| 201 |
try: |
| 202 |
token, secret = auth_client.get_access_token(code) |
| 203 |
except DiscogsAPIError: |
| 204 |
raise UserError("Discogs authorization failed") |
| 205 |
except CONNECTION_ERRORS as e: |
| 206 |
self._log.debug("connection error: {}", e) |
| 207 |
raise UserError("Discogs token request failed") |
| 208 |
|
| 209 |
# Save the token for later use. |
| 210 |
self._log.debug("Discogs token {}, secret {}", token, secret) |
| 211 |
with open(self._tokenfile(), "w") as f: |
| 212 |
json.dump({"token": token, "secret": secret}, f) |
| 213 |
|
| 214 |
return token, secret |
| 215 |
|
| 216 |
def get_track_from_album( |
| 217 |
self, album_info: AlbumInfo, compare: Callable[[TrackInfo], float] |
| 218 |
) -> TrackInfo | None: |
| 219 |
"""Return the best matching track of the release.""" |
| 220 |
scores_and_tracks = [(compare(t), t) for t in album_info.tracks] |
| 221 |
score, track_info = min(scores_and_tracks, key=lambda x: x[0]) |
| 222 |
if score > 0.3: |
| 223 |
return None |
| 224 |
|
| 225 |
track_info["artist"] = album_info.artist |
| 226 |
track_info["artist_id"] = album_info.artist_id |
| 227 |
track_info["album"] = album_info.album |
| 228 |
return track_info |
| 229 |
|
| 230 |
def item_candidates( |
| 231 |
self, item: Item, artist: str, title: str |
| 232 |
) -> Iterator[TrackInfo]: |
| 233 |
albums = self.candidates([item], artist, title, False) |
| 234 |
|
| 235 |
def compare_func(track_info: TrackInfo) -> float: |
| 236 |
return string_dist(track_info.title, title) |
| 237 |
|
| 238 |
tracks = (self.get_track_from_album(a, compare_func) for a in albums) |
| 239 |
return filter(None, tracks) |
| 240 |
|
| 241 |
def album_for_id(self, album_id: str) -> AlbumInfo | None: |
| 242 |
"""Fetches an album by its Discogs ID and returns an AlbumInfo object |
| 243 |
or None if the album is not found. |
| 244 |
""" |
| 245 |
discogs_id = self._extract_id(album_id) |
| 246 |
|
| 247 |
if not discogs_id: |
| 248 |
return None |
| 249 |
|
| 250 |
result = Release(self.discogs_client, {"id": discogs_id}) |
| 251 |
# Try to obtain title to verify that we indeed have a valid Release |
| 252 |
try: |
| 253 |
getattr(result, "title") |
| 254 |
except DiscogsAPIError as e: |
| 255 |
if e.status_code != 404: |
| 256 |
self._log.debug( |
| 257 |
"API Error: {} (query: {})", e, result.data["resource_url"] |
| 258 |
) |
| 259 |
if e.status_code == 401: |
| 260 |
self.reset_auth() |
| 261 |
return self.album_for_id(album_id) |
| 262 |
return None |
| 263 |
except CONNECTION_ERRORS: |
| 264 |
self._log.debug("Connection error in album lookup", exc_info=True) |
| 265 |
return None |
| 266 |
return self.get_album_info(result) |
| 267 |
|
| 268 |
def track_for_id(self, track_id: str) -> TrackInfo | None: |
| 269 |
if album := self.album_for_id(track_id): |
| 270 |
for track in album.tracks: |
| 271 |
if track.track_id == track_id: |
| 272 |
return track |
| 273 |
return None |
| 274 |
|
| 275 |
def get_search_query_with_filters( |
| 276 |
self, |
| 277 |
query_type: QueryType, |
| 278 |
items: Sequence[Item], |
| 279 |
artist: str, |
| 280 |
name: str, |
| 281 |
va_likely: bool, |
| 282 |
) -> tuple[str, dict[str, str]]: |
| 283 |
"""Build a Discogs release query and fixed release-type filter. |
| 284 |
|
| 285 |
The query is normalized to improve hit rates for punctuation-heavy album |
| 286 |
names and medium suffixes that can reduce recall. |
| 287 |
""" |
| 288 |
|
| 289 |
query = f"{artist} {name}" if va_likely else name |
| 290 |
# Strip non-word characters from query. Things like "!" and "-" can |
| 291 |
# cause a query to return no results, even if they match the artist or |
| 292 |
# album title. Use `re.UNICODE` flag to avoid stripping non-english |
| 293 |
# word characters. |
| 294 |
query = re.sub(r"(?u)\W+", " ", query) |
| 295 |
# Strip medium information from query, Things like "CD1" and "disk 1" |
| 296 |
# can also negate an otherwise positive result. |
| 297 |
query = re.sub(r"(?i)\b(CD|disc|vinyl)\s*\d+", "", query) |
| 298 |
|
| 299 |
filters: dict[str, str] = {"type": "release"} |
| 300 |
|
| 301 |
if not items: |
| 302 |
return query, filters |
| 303 |
|
| 304 |
for tag, api_field in self.extra_discogs_field_by_tag.items(): |
| 305 |
most_common, _count = util.plurality( |
| 306 |
item.get(tag) for item in items |
| 307 |
) |
| 308 |
if most_common is None: |
| 309 |
continue |
| 310 |
|
| 311 |
value = str(most_common) |
| 312 |
if tag == "catalognum": |
| 313 |
value = value.replace(" ", "") |
| 314 |
|
| 315 |
filters[api_field] = value |
| 316 |
|
| 317 |
return query, filters |
| 318 |
|
| 319 |
def get_search_response(self, params: SearchParams) -> Sequence[IDResponse]: |
| 320 |
"""Search Discogs releases and return raw result mappings with IDs.""" |
| 321 |
|
| 322 |
def search() -> list[IDResponse]: |
| 323 |
results = self.discogs_client.search(params.query, **params.filters) |
| 324 |
results.per_page = params.limit |
| 325 |
return [r.data for r in results.page(1)] |
| 326 |
|
| 327 |
try: |
| 328 |
return search() |
| 329 |
except json.JSONDecodeError: |
| 330 |
self._log.debug( |
| 331 |
"Discogs returned an invalid JSON search response; retrying" |
| 332 |
) |
| 333 |
return search() |
| 334 |
|
| 335 |
@cache |
| 336 |
def get_master_year(self, master_id: str) -> int | None: |
| 337 |
"""Fetches a master release given its Discogs ID and returns its year |
| 338 |
or None if the master release is not found. |
| 339 |
""" |
| 340 |
self._log.debug("Getting master release {}", master_id) |
| 341 |
result = Master(self.discogs_client, {"id": master_id}) |
| 342 |
|
| 343 |
try: |
| 344 |
return result.fetch("year") |
| 345 |
except DiscogsAPIError as e: |
| 346 |
if e.status_code != 404: |
| 347 |
self._log.debug( |
| 348 |
"API Error: {} (query: {})", e, result.data["resource_url"] |
| 349 |
) |
| 350 |
if e.status_code == 401: |
| 351 |
self.reset_auth() |
| 352 |
return self.get_master_year(master_id) |
| 353 |
return None |
| 354 |
except CONNECTION_ERRORS: |
| 355 |
self._log.debug( |
| 356 |
"Connection error in master release lookup", exc_info=True |
| 357 |
) |
| 358 |
return None |
| 359 |
|
| 360 |
@staticmethod |
| 361 |
def get_media_and_albumtype( |
| 362 |
formats: list[ReleaseFormat] | None, |
| 363 |
) -> tuple[str | None, str | None]: |
| 364 |
media = albumtype = None |
| 365 |
if formats and (first_format := formats[0]): |
| 366 |
if descriptions := first_format["descriptions"]: |
| 367 |
albumtype = ", ".join(descriptions) |
| 368 |
media = first_format["name"] |
| 369 |
|
| 370 |
return media, albumtype |
| 371 |
|
| 372 |
def get_album_info(self, result: Release) -> AlbumInfo | None: |
| 373 |
"""Returns an AlbumInfo object for a discogs Release object.""" |
| 374 |
# Explicitly reload the `Release` fields, as they might not be yet |
| 375 |
# present if the result is from a `discogs_client.search()`. |
| 376 |
if not result.data.get("artists"): |
| 377 |
try: |
| 378 |
result.refresh() |
| 379 |
except CONNECTION_ERRORS: |
| 380 |
self._log.debug( |
| 381 |
"Connection error in release lookup: {0}", result |
| 382 |
) |
| 383 |
return None |
| 384 |
|
| 385 |
artist_data = [a.data for a in result.artists] |
| 386 |
# Information for the album artist |
| 387 |
albumartist = ArtistState.from_config( |
| 388 |
self.config, artist_data, for_album_artist=True |
| 389 |
) |
| 390 |
|
| 391 |
album = re.sub(r" +", " ", result.title) |
| 392 |
album_id = result.data["id"] |
| 393 |
# Use `.data` to access the tracklist directly instead of the |
| 394 |
# convenient `.tracklist` property, which will strip out useful artist |
| 395 |
# information and leave us with skeleton `Artist` objects that will |
| 396 |
# each make an API call just to get the same data back. |
| 397 |
tracks = self.get_tracks( |
| 398 |
result.data["tracklist"], |
| 399 |
ArtistState.from_config(self.config, artist_data), |
| 400 |
) |
| 401 |
|
| 402 |
# Extract information for the optional AlbumInfo fields, if possible. |
| 403 |
va = albumartist.artist == config["va_name"].as_str() |
| 404 |
year, month, day = parse_release_date( |
| 405 |
result.data.get("released"), result.data.get("year") |
| 406 |
) |
| 407 |
mediums = [t["medium"] for t in tracks] |
| 408 |
country = result.data.get("country") |
| 409 |
data_url = result.data.get("uri") |
| 410 |
# we swap genre and style since discogs genres are more general and |
| 411 |
# styles more specific |
| 412 |
styles: list[str] = result.data.get("genres") or [] |
| 413 |
genres: list[str] = result.data.get("styles") or [] |
| 414 |
|
| 415 |
if self.config["append_style_genre"]: |
| 416 |
genres.extend(styles) |
| 417 |
|
| 418 |
discogs_albumid = self._extract_id(result.data.get("uri")) |
| 419 |
|
| 420 |
# Extract information for the optional AlbumInfo fields that are |
| 421 |
# contained on nested discogs fields. |
| 422 |
media, albumtype = self.get_media_and_albumtype( |
| 423 |
result.data.get("formats") |
| 424 |
) |
| 425 |
|
| 426 |
label = catalogno = labelid = None |
| 427 |
if result.data.get("labels"): |
| 428 |
label = self.strip_disambiguation( |
| 429 |
result.data["labels"][0].get("name") |
| 430 |
) |
| 431 |
catalogno = result.data["labels"][0].get("catno") |
| 432 |
labelid = result.data["labels"][0].get("id") |
| 433 |
|
| 434 |
cover_art_url = self.select_cover_art(result) |
| 435 |
|
| 436 |
# Additional cleanups |
| 437 |
# (catalog number, media, disambiguation). |
| 438 |
if catalogno == "none": |
| 439 |
catalogno = None |
| 440 |
# Explicitly set the `media` for the tracks, since it is expected by |
| 441 |
# `autotag.apply_metadata`, and set `medium_total`. |
| 442 |
for track in tracks: |
| 443 |
track.media = media |
| 444 |
track.medium_total = mediums.count(track.medium) |
| 445 |
# Discogs does not have track IDs. Invent our own IDs as proposed |
| 446 |
# in #2336. |
| 447 |
track.track_id = f"{album_id}-{track.track_alt}" |
| 448 |
track.data_url = data_url |
| 449 |
track.data_source = "Discogs" |
| 450 |
|
| 451 |
# Retrieve master release id (returns None if there isn't one). |
| 452 |
master_id = result.data.get("master_id") |
| 453 |
# Assume this release *is* the original when it has no master |
| 454 |
# release, otherwise fetch the master release. Only its year is |
| 455 |
# available, so the original month and day stay unknown there. |
| 456 |
if master_id: |
| 457 |
original_year = self.get_master_year(master_id) |
| 458 |
original_month = original_day = None |
| 459 |
else: |
| 460 |
original_year, original_month, original_day = year, month, day |
| 461 |
|
| 462 |
return AlbumInfo( |
| 463 |
album=album, |
| 464 |
album_id=album_id, |
| 465 |
**albumartist.info, # Unpacks values to satisfy the keyword arguments |
| 466 |
tracks=tracks, |
| 467 |
albumtype=albumtype, |
| 468 |
va=va, |
| 469 |
year=year, |
| 470 |
month=month, |
| 471 |
day=day, |
| 472 |
label=label, |
| 473 |
mediums=len(set(mediums)), |
| 474 |
releasegroup_id=master_id, |
| 475 |
catalognum=catalogno, |
| 476 |
country=country, |
| 477 |
style=( |
| 478 |
self.config["separator"].as_str().join(sorted(styles)) or None |
| 479 |
), |
| 480 |
genres=sorted(genres), |
| 481 |
media=media, |
| 482 |
original_year=original_year, |
| 483 |
original_month=original_month, |
| 484 |
original_day=original_day, |
| 485 |
data_source=self.data_source, |
| 486 |
data_url=data_url, |
| 487 |
discogs_albumid=discogs_albumid, |
| 488 |
discogs_labelid=labelid, |
| 489 |
discogs_artistid=albumartist.artist_id, |
| 490 |
cover_art_url=cover_art_url, |
| 491 |
) |
| 492 |
|
| 493 |
def select_cover_art(self, result: Release) -> str | None: |
| 494 |
"""Returns the best candidate image, if any, from a Discogs `Release` object.""" |
| 495 |
if result.data.get("images") and len(result.data.get("images")) > 0: |
| 496 |
# The first image in this list appears to be the one displayed first |
| 497 |
# on the release page - even if it is not flagged as `type: "primary"` - and |
| 498 |
# so it is the best candidate for the cover art. |
| 499 |
return result.data.get("images")[0].get("uri") |
| 500 |
|
| 501 |
return None |
| 502 |
|
| 503 |
def get_tracks( |
| 504 |
self, tracklist: list[Track], albumartistinfo: ArtistState |
| 505 |
) -> list[TrackInfo]: |
| 506 |
"""Returns a list of TrackInfo objects for a discogs tracklist.""" |
| 507 |
try: |
| 508 |
clean_tracklist: list[Track] = self._coalesce_tracks(tracklist) |
| 509 |
except Exception as exc: |
| 510 |
# FIXME: this is an extra precaution for making sure there are no |
| 511 |
# side effects after #2222. It should be removed after further |
| 512 |
# testing. |
| 513 |
self._log.debug("{}", traceback.format_exc()) |
| 514 |
self._log.error("uncaught exception in _coalesce_tracks: {}", exc) |
| 515 |
clean_tracklist = tracklist |
| 516 |
t = TracklistState.build(self, clean_tracklist, albumartistinfo) |
| 517 |
# Fix up medium and medium_index for each track. Discogs position is |
| 518 |
# unreliable, but tracks are in order. |
| 519 |
medium = None |
| 520 |
medium_count, index_count, side_count = 0, 0, 0 |
| 521 |
sides_per_medium = 1 |
| 522 |
|
| 523 |
# If a medium has two sides (ie. vinyl or cassette), each pair of |
| 524 |
# consecutive sides should belong to the same medium. |
| 525 |
if all([medium is not None for medium in t.mediums]): |
| 526 |
m = sorted( |
| 527 |
{medium.lower() if medium else "" for medium in t.mediums} |
| 528 |
) |
| 529 |
# If all track.medium are single consecutive letters, assume it is |
| 530 |
# a 2-sided medium. |
| 531 |
if "".join(m) in ascii_lowercase: |
| 532 |
sides_per_medium = 2 |
| 533 |
|
| 534 |
for i, track in enumerate(t.tracks): |
| 535 |
# Handle special case where a different medium does not indicate a |
| 536 |
# new disc, when there is no medium_index and the ordinal of medium |
| 537 |
# is not sequential. For example, I, II, III, IV, V. Assume these |
| 538 |
# are the track index, not the medium. |
| 539 |
# side_count is the number of mediums or medium sides (in the case |
| 540 |
# of two-sided mediums) that were seen before. |
| 541 |
medium_str = t.mediums[i] |
| 542 |
medium_index = t.medium_indices[i] |
| 543 |
medium_is_index = ( |
| 544 |
medium_str |
| 545 |
and not medium_index |
| 546 |
and ( |
| 547 |
len(medium_str) != 1 |
| 548 |
or |
| 549 |
# Not within standard incremental medium values (A, B, C, ...). |
| 550 |
ord(medium_str) - 64 != side_count + 1 |
| 551 |
) |
| 552 |
) |
| 553 |
|
| 554 |
if not medium_is_index and medium != medium_str: |
| 555 |
side_count += 1 |
| 556 |
if sides_per_medium == 2: |
| 557 |
if side_count % sides_per_medium: |
| 558 |
# Two-sided medium changed. Reset index_count. |
| 559 |
index_count = 0 |
| 560 |
medium_count += 1 |
| 561 |
else: |
| 562 |
# Medium changed. Reset index_count. |
| 563 |
medium_count += 1 |
| 564 |
index_count = 0 |
| 565 |
medium = medium_str |
| 566 |
|
| 567 |
index_count += 1 |
| 568 |
medium_count = 1 if medium_count == 0 else medium_count |
| 569 |
track.medium, track.medium_index = medium_count, index_count |
| 570 |
|
| 571 |
# Get `disctitle` from Discogs index tracks. Assume that an index track |
| 572 |
# before the first track of each medium is a disc title. |
| 573 |
for track in t.tracks: |
| 574 |
if track.medium_index == 1: |
| 575 |
if track.index in t.index_tracks: |
| 576 |
disctitle = t.index_tracks[track.index] |
| 577 |
else: |
| 578 |
disctitle = None |
| 579 |
track.disctitle = disctitle |
| 580 |
|
| 581 |
return t.tracks |
| 582 |
|
| 583 |
def _subtrack_position(self, track: Track) -> str | None: |
| 584 |
"""Identify the physical position containing a flat audio subtrack.""" |
| 585 |
if track["type_"] == "track": |
| 586 |
medium, medium_index, subindex = self.get_track_index( |
| 587 |
track["position"] |
| 588 |
) |
| 589 |
if subindex: |
| 590 |
return f"{medium or ''}{medium_index or ''}" |
| 591 |
return None |
| 592 |
|
| 593 |
def _coalesce_tracks(self, raw_tracklist: list[Track]) -> list[Track]: |
| 594 |
"""Normalize each Discogs tracklist entry by its declared kind.""" |
| 595 |
tracklist: list[Track] = [] |
| 596 |
for position, tracks in groupby( |
| 597 |
raw_tracklist, key=self._subtrack_position |
| 598 |
): |
| 599 |
if position is not None: |
| 600 |
subtracks = [ |
| 601 |
track for track in tracks if track["type_"] == "track" |
| 602 |
] |
| 603 |
tracklist.append(self._merge_subtracks(subtracks)) |
| 604 |
continue |
| 605 |
|
| 606 |
for track in tracks: |
| 607 |
if track["type_"] in {"track", "heading"}: |
| 608 |
tracklist.append(track) |
| 609 |
elif track["type_"] == "index": |
| 610 |
tracklist.extend(self._coalesce_index_track(track)) |
| 611 |
|
| 612 |
return tracklist |
| 613 |
|
| 614 |
@staticmethod |
| 615 |
def _merge_subtracks(subtracks: list[AudioTrack]) -> AudioTrack: |
| 616 |
"""Combine flat Discogs subtracks representing one physical track.""" |
| 617 |
merged_track = subtracks[0].copy() |
| 618 |
merged_track["title"] = " / ".join( |
| 619 |
subtrack["title"] for subtrack in subtracks |
| 620 |
) |
| 621 |
return merged_track |
| 622 |
|
| 623 |
def _coalesce_index_track( |
| 624 |
self, index_track: IndexTrack |
| 625 |
) -> list[AudioTrack]: |
| 626 |
"""Convert an index container into its physical audio tracks.""" |
| 627 |
subtracks = index_track["sub_tracks"] |
| 628 |
if not subtracks: |
| 629 |
raise ValueError("Discogs index track does not contain subtracks") |
| 630 |
|
| 631 |
medium, medium_index, subindex = self.get_track_index( |
| 632 |
subtracks[0]["position"] |
| 633 |
) |
| 634 |
|
| 635 |
# Subindexed children are logical pieces contained in one physical |
| 636 |
# track. Keep the index track's metadata and discard the child entries. |
| 637 |
if subindex: |
| 638 |
merged_track: AudioTrack = { |
| 639 |
"type_": "track", |
| 640 |
"position": f"{medium or ''}{medium_index or ''}", |
| 641 |
"title": index_track["title"], |
| 642 |
"duration": index_track["duration"], |
| 643 |
} |
| 644 |
if artists := index_track.get("artists"): |
| 645 |
merged_track["artists"] = artists |
| 646 |
if extraartists := index_track.get("extraartists"): |
| 647 |
merged_track["extraartists"] = extraartists |
| 648 |
return [merged_track] |
| 649 |
|
| 650 |
# Children without subindices are separate physical tracks grouped |
| 651 |
# under a musical work. Discard the index while retaining its context. |
| 652 |
artists = index_track.get("artists") |
| 653 |
title_prefix = ( |
| 654 |
f"{index_track['title']}: " if self.config["index_tracks"] else "" |
| 655 |
) |
| 656 |
tracks: list[AudioTrack] = [] |
| 657 |
for subtrack in subtracks: |
| 658 |
track = subtrack.copy() |
| 659 |
if artists and not track.get("artists"): |
| 660 |
track["artists"] = artists |
| 661 |
if title_prefix: |
| 662 |
track["title"] = f"{title_prefix}{track['title']}" |
| 663 |
tracks.append(track) |
| 664 |
return tracks |
| 665 |
|
| 666 |
def strip_disambiguation(self, text: str) -> str: |
| 667 |
"""Removes discogs specific disambiguations from a string. |
| 668 |
Turns 'Label Name (5)' to 'Label Name' or 'Artist (1) & Another Artist (2)' |
| 669 |
to 'Artist & Another Artist'. Does nothing if strip_disambiguation is False.""" |
| 670 |
if not self.config["strip_disambiguation"]: |
| 671 |
return text |
| 672 |
return DISAMBIGUATION_RE.sub("", text) |
| 673 |
|
| 674 |
def get_track_info( |
| 675 |
self, |
| 676 |
track: AudioTrack, |
| 677 |
index: int, |
| 678 |
divisions: list[str], |
| 679 |
albumartistinfo: ArtistState, |
| 680 |
) -> tuple[TrackInfo, str | None, str | None]: |
| 681 |
"""Returns a TrackInfo object for a discogs track.""" |
| 682 |
|
| 683 |
title = track["title"] |
| 684 |
if self.config["index_tracks"]: |
| 685 |
prefix = ", ".join(divisions) |
| 686 |
if prefix: |
| 687 |
title = f"{prefix}: {title}" |
| 688 |
track_id = None |
| 689 |
medium, medium_index, _ = self.get_track_index(track["position"]) |
| 690 |
|
| 691 |
length = self.get_track_length(track["duration"]) |
| 692 |
# If artists are found on the track, we will use those instead |
| 693 |
artistinfo = ArtistState.from_config( |
| 694 |
self.config, |
| 695 |
[ |
| 696 |
*(track.get("artists") or albumartistinfo.raw_artists), |
| 697 |
*track.get("extraartists", []), |
| 698 |
], |
| 699 |
) |
| 700 |
|
| 701 |
return ( |
| 702 |
TrackInfo( |
| 703 |
title=title, |
| 704 |
track_id=track_id, |
| 705 |
**artistinfo.info, |
| 706 |
length=length, |
| 707 |
index=index, |
| 708 |
), |
| 709 |
medium, |
| 710 |
medium_index, |
| 711 |
) |
| 712 |
|
| 713 |
@staticmethod |
| 714 |
def get_track_index( |
| 715 |
position: str, |
| 716 |
) -> tuple[str | None, str | None, str | None]: |
| 717 |
"""Returns the medium, medium index and subtrack index for a discogs |
| 718 |
track position.""" |
| 719 |
# Match the standard Discogs positions (12.2.9), which can have several |
| 720 |
# forms (1, 1-1, A1, A1.1, A1a, ...). |
| 721 |
medium = index = subindex = None |
| 722 |
if match := TRACK_INDEX_RE.fullmatch(position.upper()): |
| 723 |
medium, index, subindex = match.groups() |
| 724 |
|
| 725 |
if subindex and subindex.startswith("."): |
| 726 |
subindex = subindex[1:] |
| 727 |
|
| 728 |
return medium or None, index or None, subindex or None |
| 729 |
|
| 730 |
def get_track_length(self, duration: str) -> int | None: |
| 731 |
"""Returns the track length in seconds for a discogs duration.""" |
| 732 |
try: |
| 733 |
length = time.strptime(duration, "%M:%S") |
| 734 |
except ValueError: |
| 735 |
return None |
| 736 |
return length.tm_min * 60 + length.tm_sec |