{{ message }}
Repository navigation
Expand file tree
/
Copy pathmissing.py
More file actions
279 lines (241 loc) · 8.77 KB
/
Copy pathmissing.py
File metadata and controls
279 lines (241 loc) · 8.77 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
"""List missing tracks."""
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING, ClassVar
import requests
from beets import config, metadata_plugins
from beets.dbcore import types
from beets.library import Album, Item
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand, print_
from ._utils.musicbrainz import MusicBrainzAPIMixin
if TYPE_CHECKING:
import optparse
from collections.abc import Iterator
from beets.autotag import AlbumInfo, TrackInfo
from beets.library import Library
# Valid MusicBrainz release types for filtering release groups
VALID_RELEASE_TYPES = [
"nat",
"album",
"single",
"ep",
"broadcast",
"other",
"compilation",
"soundtrack",
"spokenword",
"interview",
"audiobook",
"live",
"remix",
"dj-mix",
"mixtape/street",
]
MB_ARTIST_QUERY = r"mb_albumartistid::^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$"
def _missing_count(album: Album) -> bool | int:
"""Return number of missing items in `album`."""
return (album.albumtotal or 0) - len(album.items())
def _item(
track_info: TrackInfo, album_info: AlbumInfo, album_id: int | None
) -> Item:
"""Build and return `item` from `track_info` and `album info`
objects. `item` is missing what fields cannot be obtained from
MusicBrainz alone (encoder, rg_track_gain, rg_track_peak,
rg_album_gain, rg_album_peak, original_year, original_month,
original_day, length, bitrate, format, samplerate, bitdepth,
channels, mtime.)
"""
t = track_info
a = album_info
return Item(
album_id=album_id,
album=a.album,
albumartist=a.artist,
albumartist_credit=a.artist_credit,
albumartist_sort=a.artist_sort,
albumdisambig=a.albumdisambig,
albumstatus=a.albumstatus,
albumtype=a.albumtype,
artist=t.artist,
artist_credit=t.artist_credit,
artist_sort=t.artist_sort,
asin=a.asin,
catalognum=a.catalognum,
comp=a.va,
country=a.country,
day=a.day,
disc=t.medium,
disctitle=t.disctitle,
disctotal=a.mediums,
label=a.label,
language=a.language,
length=t.length,
mb_albumid=a.album_id,
mb_artistid=t.artist_id,
mb_releasegroupid=a.releasegroup_id,
mb_trackid=t.track_id,
media=t.media,
month=a.month,
script=a.script,
title=t.title,
track=t.index,
tracktotal=len(a.tracks),
year=a.year,
)
class MissingPlugin(MusicBrainzAPIMixin, BeetsPlugin):
"""List missing tracks"""
album_types: ClassVar[dict[str, types.Type]] = {"missing": types.INTEGER}
def __init__(self) -> None:
super().__init__()
self.config.add(
{
"count": False,
"total": False,
"album": False,
"release_types": ["album"],
}
)
self.album_template_fields["missing"] = lambda a: str(_missing_count(a))
self._command = Subcommand("missing", help=__doc__, aliases=["miss"])
self._command.parser.add_option(
"-c",
"--count",
dest="count",
action="store_true",
help="count missing tracks per album",
)
self._command.parser.add_option(
"-t",
"--total",
dest="total",
action="store_true",
help="count total of missing tracks",
)
self._command.parser.add_option(
"-a",
"--album",
dest="album",
action="store_true",
help=(
"show missing album releases for artist instead of tracks; "
"Defaults to only releases of type 'album'"
),
)
self._command.parser.add_option(
"--release-types",
action="append",
dest="release_types",
help=(
"comma-separated list of release types for missing albums "
f"(valid: {', '.join(VALID_RELEASE_TYPES)})"
),
)
self._command.parser.add_format_option()
self._command.parser.add_limit_option()
def commands(self) -> list[Subcommand]:
def _miss(lib: Library, opts: optparse.Values, args: list[str]) -> None:
self.config.set_args(opts)
albms = self.config["album"].get()
helper = self._missing_albums if albms else self._missing_tracks
helper(lib, args, opts.limit)
self._command.func = _miss
return [self._command]
def _missing_tracks(
self, lib: Library, query: list[str], limit: int | None
) -> None:
"""Print a listing of tracks missing from each album in the library
matching query.
"""
albums = lib.albums(query, limit=limit)
count = self.config["count"].get()
total = self.config["total"].get()
fmt = config["format_album" if count else "format_item"].get()
if total:
print(sum([_missing_count(a) for a in albums]))
return
# Default format string for count mode.
if count:
fmt += ": $missing"
for album in albums:
if count:
if _missing_count(album):
print_(format(album, fmt))
else:
for item in self._missing(album):
print_(format(item, fmt))
def _missing_albums(
self, lib: Library, query: list[str], limit: int | None
) -> None:
"""Print a listing of albums missing from each artist in the library
matching query.
"""
query.append(MB_ARTIST_QUERY)
# build dict mapping artist to set of their release group ids in library
album_ids_by_artist = defaultdict(set)
for album in lib.albums(query, limit=limit):
# TODO(@snejus): Some releases have different `albumartist` for the
# same `mb_albumartistid`. Since we're grouping by the combination
# of these two fields, we end up processing the same
# `mb_albumartistid` multiple times: calling MusicBrainz API and
# reporting the same set of missing albums. Instead, we should
# group by `mb_albumartistid` field only.
artist = (album["albumartist"], album["mb_albumartistid"])
album_ids_by_artist[artist].add(album["mb_releasegroupid"])
total_missing = 0
release_types = []
for rt in self.config["release_types"].as_str_seq():
release_types.extend(rt.split(","))
calculating_total = self.config["total"].get()
fmt = config["format_album"].get()
for (artist, artist_id), album_ids in album_ids_by_artist.items():
try:
resp = self.mb_api.browse_release_groups(
artist=artist_id, type="|".join(release_types)
)
except requests.exceptions.RequestException:
self._log.info(
"Couldn't fetch info for artist '{}' ({})",
artist,
artist_id,
exc_info=True,
)
continue
missing_albums = [
Album(
albumartist=artist,
album=rg["title"],
mb_releasegroupid=rg["id"],
albumtype=(rg.get("primary_type") or "").lower(),
)
for rg in resp
if rg["id"] not in album_ids
]
if calculating_total:
total_missing += len(missing_albums)
else:
for album in missing_albums:
print_(format(album, fmt))
if calculating_total:
print(total_missing)
def _missing(self, album: Album) -> Iterator[Item]:
"""Query MusicBrainz to determine items missing from `album`."""
if len(album.items()) == album.albumtotal:
return
# fetch missing items
# TODO: Implement caching that without breaking other stuff
data_source = album.get("data_source") or album.items()[0].get(
"data_source", "MusicBrainz"
)
if album_info := metadata_plugins.album_for_id(
album.mb_albumid, data_source
):
item_mbids = {x.mb_trackid for x in album.items()}
for track_info in album_info.tracks:
if track_info.track_id not in item_mbids:
self._log.debug(
"track {.track_id} in album {.album_id}",
track_info,
album_info,
)
yield _item(track_info, album_info, album.id)
You can’t perform that action at this time.
