Debian Codegraph @

beetsplug/discogs/states.py

raw
1 """Dataclasses for managing artist credits and tracklists from Discogs."""
2
3 from __future__ import annotations
4
5 import re
6 from dataclasses import asdict, dataclass, field
7 from functools import cached_property
8 from typing import TYPE_CHECKING, NamedTuple
9
10 from beets import config
11 from beets.util import unique_list
12
13 from .types import ArtistInfo
14
15 if TYPE_CHECKING:
16 from confuse import ConfigView
17
18 from beets.autotag import TrackInfo
19
20 from . import DiscogsPlugin
21 from .types import Artist, Track, TracklistInfo
22
23 DISAMBIGUATION_RE = re.compile(r" \(\d+\)")
24
25
26 @dataclass
27 class ArtistState:
28 """Represent Discogs artist credits.
29
30 This object centralizes the plugin's policy for which Discogs artist fields
31 to prefer (name vs. ANV), how to treat 'Various', how to format join
32 phrases, and how to separate featured artists. It exposes both per-artist
33 components and fully joined strings for common tag targets like 'artist' and
34 'artist_credit'.
35 """
36
37 class ValidArtist(NamedTuple):
38 """A normalized, render-ready artist entry extracted from Discogs data.
39
40 Instances represent the subset of Discogs artist information needed for
41 tagging, including the join token following the artist and the
42 lowercased Discogs role string (e.g. "featuring", "written-by", "remix")
43 """
44
45 id: str
46 name: str
47 credit: str
48 join: str
49 role: str
50
51 def __hash__(self) -> int:
52 return hash(self.id)
53
54 def __eq__(self, other: object) -> bool:
55 if isinstance(other, self.__class__):
56 return self.id == other.id
57
58 return False
59
60 def get_artist(self, property_name: str) -> str:
61 """Return the requested display field with its trailing join token.
62
63 The join token is normalized so commas become ', ' and other join
64 phrases are surrounded with spaces, producing a single fragment that
65 can be concatenated to form a full artist string.
66 """
67 join = {",": ", ", "": ""}.get(self.join, f" {self.join} ")
68 return f"{getattr(self, property_name)}{join}"
69
70 raw_artists: list[Artist]
71 use_anv: bool
72 use_credit_anv: bool
73 featured_string: str
74 should_strip_disambiguation: bool
75
76 @property
77 def info(self) -> ArtistInfo:
78 """Expose the state in the shape expected by downstream tag mapping."""
79 return {k: getattr(self, k) for k in ArtistInfo.__annotations__} # type: ignore[return-value]
80
81 def strip_disambiguation(self, text: str) -> str:
82 """Strip Discogs disambiguation suffixes from an artist or label string.
83
84 This removes Discogs-specific numeric suffixes like 'Name (5)' and can
85 be applied to multi-artist strings as well (e.g., 'A (1) & B (2)'). When
86 the feature is disabled, the input is returned unchanged.
87 """
88 if self.should_strip_disambiguation:
89 return DISAMBIGUATION_RE.sub("", text)
90 return text
91
92 @cached_property
93 def valid_artists(self) -> list[ValidArtist]:
94 """Build the ordered, filtered list of artists used for rendering.
95
96 The resulting list normalizes Discogs entries by:
97 - substituting the configured 'Various Artists' name when Discogs uses
98 'Various'
99 - choosing between name and ANV according to plugin settings
100 - capturing join tokens so the original credit formatting is preserved
101 """
102 va_name = config["va_name"].as_str()
103 return [
104 self.ValidArtist(
105 str(a["id"]),
106 self.strip_disambiguation(anv if self.use_anv else name),
107 self.strip_disambiguation(anv if self.use_credit_anv else name),
108 a["join"].strip(),
109 a["role"].lower(),
110 )
111 for a in self.raw_artists
112 if (
113 (name := va_name if a["name"] == "Various" else a["name"])
114 and (anv := a["anv"] or name)
115 )
116 ]
117
118 @property
119 def main_artists(self) -> list[ValidArtist]:
120 """Return the per-artist display names used for the 'artist' field."""
121 artists = [
122 a for a in self.valid_artists if not a.role or "featuring" in a.role
123 ]
124 return unique_list(artists)
125
126 @property
127 def artists_ids(self) -> list[str]:
128 """Return Discogs artist IDs for the main artists, preserving order."""
129 return [a.id for a in self.main_artists]
130
131 @property
132 def artist_id(self) -> str:
133 """Return the primary Discogs artist ID."""
134 return self.artists_ids[0]
135
136 @property
137 def artists(self) -> list[str]:
138 """Return the per-artist display names used for the 'artist' field."""
139 return [a.name for a in self.main_artists]
140
141 @property
142 def artists_credit(self) -> list[str]:
143 """Return the per-artist display names used for the credit field."""
144 return [a.credit for a in self.main_artists]
145
146 @property
147 def artist(self) -> str:
148 """Return the fully rendered artist string using display names."""
149 return self.join_artists("name")
150
151 @property
152 def artist_credit(self) -> str:
153 """Return the fully rendered artist credit string."""
154 return self.join_artists("credit")
155
156 @property
157 def lyricists(self) -> list[str] | None:
158 return [
159 a.name for a in self.valid_artists if "lyrics" in a.role
160 ] or None
161
162 @property
163 def arrangers(self) -> list[str] | None:
164 return [
165 a.name for a in self.valid_artists if "arrang" in a.role
166 ] or None
167
168 @property
169 def remixers(self) -> list[str] | None:
170 return [a.name for a in self.valid_artists if "remix" in a.role] or None
171
172 @property
173 def composers(self) -> list[str] | None:
174 return [
175 a.name for a in self.valid_artists if "written-by" in a.role
176 ] or None
177
178 def join_artists(self, property_name: str) -> str:
179 """Render a single artist string with join phrases and featured artists.
180
181 Non-featured artists are concatenated using their join tokens. Featured
182 artists are appended after the configured 'featured' marker, preserving
183 Discogs order while keeping featured credits separate from the main
184 artist string.
185 """
186 non_featured = [a for a in self.main_artists if not a.role]
187 featured = [a for a in self.main_artists if "featuring" in a.role]
188
189 artist = "".join(a.get_artist(property_name) for a in non_featured)
190 if featured:
191 if "feat" not in artist:
192 artist += f" {self.featured_string} "
193
194 artist += ", ".join(a.get_artist(property_name) for a in featured)
195
196 return artist
197
198 @classmethod
199 def from_config(
200 cls,
201 config: ConfigView,
202 artists: list[Artist],
203 for_album_artist: bool = False,
204 ) -> ArtistState:
205 return cls(
206 artists,
207 config["anv"]["album_artist" if for_album_artist else "artist"].get(
208 bool
209 ),
210 config["anv"]["artist_credit"].get(bool),
211 config["featured_string"].as_str(),
212 config["strip_disambiguation"].get(bool),
213 )
214
215
216 @dataclass
217 class TracklistState:
218 index: int = 0
219 index_tracks: dict[int, str] = field(default_factory=dict)
220 tracks: list[TrackInfo] = field(default_factory=list)
221 divisions: list[str] = field(default_factory=list)
222 next_divisions: list[str] = field(default_factory=list)
223 mediums: list[str | None] = field(default_factory=list)
224 medium_indices: list[str | None] = field(default_factory=list)
225
226 @property
227 def info(self) -> TracklistInfo:
228 return asdict(self) # type: ignore[return-value]
229
230 @classmethod
231 def build(
232 cls,
233 plugin: DiscogsPlugin,
234 clean_tracklist: list[Track],
235 albumartistinfo: ArtistState,
236 ) -> TracklistState:
237 state = cls()
238 for track in clean_tracklist:
239 if track["type_"] == "track":
240 state.index += 1
241 if state.next_divisions:
242 state.divisions += state.next_divisions
243 state.next_divisions.clear()
244 track_info, medium, medium_index = plugin.get_track_info(
245 track, state.index, state.divisions, albumartistinfo
246 )
247 track_info.track_alt = track["position"]
248 state.tracks.append(track_info)
249 state.mediums.append(medium or None)
250 state.medium_indices.append(medium_index or None)
251 else:
252 state.next_divisions.append(track["title"])
253 try:
254 state.divisions.pop()
255 except IndexError:
256 pass
257 state.index_tracks[state.index + 1] = track["title"]
258 return state