forked from tuffy/python-audio-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmusicbrainz.py
340 lines (282 loc) · 11.9 KB
/
musicbrainz.py
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
#!/usr/bin/python
# Audio Tools, a module and set of tools for manipulating audio data
# Copyright (C) 2007-2014 Brian Langenberger
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
class DiscID(object):
def __init__(self, first_track_number, last_track_number,
lead_out_offset, offsets):
"""first_track_number and last_track_number are ints
typically starting from 1
lead_out_offset is an integer number of CD frames
offsets is a list of track offsets, in CD frames"""
assert((last_track_number - first_track_number + 1) == len(offsets))
self.first_track_number = first_track_number
self.last_track_number = last_track_number
self.lead_out_offset = lead_out_offset
self.offsets = offsets
@classmethod
def from_cddareader(cls, cddareader):
"""given a CDDAReader object, returns a DiscID for that object"""
offsets = cddareader.track_offsets
return cls(first_track_number=min(offsets.keys()),
last_track_number=max(offsets.keys()),
lead_out_offset=cddareader.last_sector + 150 + 1,
offsets=[(offsets[k] // 588) + 150 for k in
sorted(offsets.keys())])
@classmethod
def from_tracks(cls, tracks):
"""given a sorted list of tracks,
returns DiscID for those tracks as if they were a CD"""
offsets = [150]
for track in tracks[0:-1]:
offsets.append(offsets[-1] + track.cd_frames())
return cls(first_track_number=1,
last_track_number=len(tracks),
lead_out_offset=sum([t.cd_frames() for t in tracks]) + 150,
offsets=offsets)
@classmethod
def from_sheet(cls, sheet, total_pcm_frames, sample_rate):
"""given a Sheet object
length of the album in PCM frames
and sample rate of the disc,
returns a DiscID for that CD"""
return cls(
first_track_number=1,
last_track_number=len(sheet),
lead_out_offset=(total_pcm_frames * 75 // sample_rate) + 150,
offsets=[int(t.index(1).offset() * 75 + 150) for t in sheet])
def __repr__(self):
return "DiscID(%s)" % \
", ".join(["%s=%s" % (attr, getattr(self, attr))
for attr in ["first_track_number",
"last_track_number",
"lead_out_offset",
"offsets"]])
def __str__(self):
from hashlib import sha1
from base64 import b64encode
return b64encode(
sha1("%2.2X%2.2X%s" %
(self.first_track_number,
self.last_track_number,
"".join(["%8.8X" % (offset) for offset in
[self.lead_out_offset] +
self.offsets +
[0] * (99 - len(self.offsets))
]))).digest(),
"._").replace("=", "-")
def __unicode__(self):
return str(self).decode('ascii')
def perform_lookup(disc_id, musicbrainz_server, musicbrainz_port):
"""performs a web-based lookup using the given DiscID
iterates over a list of MetaData objects per successful match, like:
[track1, track2, ...], [track1, track2, ...], ...
may raise urllib2.HTTPError if an error occurs querying the server
or xml.parsers.expat.ExpatError if there's an error parsing the data
"""
from urllib2 import urlopen
from urllib import urlencode
import xml.dom.minidom
from itertools import izip
# query MusicBrainz web service (version 2) for <metadata>
m = urlopen("http://%s:%d/ws/2/discid/%s?%s" %
(musicbrainz_server,
musicbrainz_port,
disc_id,
urlencode({"inc": "artists labels recordings"})))
xml = xml.dom.minidom.parse(m)
# for each <release>s in <release-list>
# yield a list of MetaData objects
try:
release_list = get_node(xml, u"metadata", u"disc", u"release-list")
for release in get_nodes(release_list, u"release"):
yield list(parse_release(release, disc_id))
except KeyError:
# no releases found, so return nothing
return
def get_node(parent, *nodes):
"""given a minidom tree element and a list of node unicode strings
indicating a path, returns the node at the end of that path
or raises KeyError if any node in the path cannot be found"""
if (len(nodes) == 0):
return parent
else:
for child in parent.childNodes:
if (hasattr(child, "tagName") and (child.tagName == nodes[0])):
return get_node(child, *nodes[1:])
else:
raise KeyError(nodes[0])
def get_nodes(parent, node):
"""given a minidom tree element and a tag name unicode string,
returns all the child nodes with that name"""
return [child for child in parent.childNodes
if (hasattr(child, "tagName") and (child.tagName == node))]
def text(node):
"""given a minidom leaf node element,
returns its data as a unicode string"""
if (node.firstChild is not None):
return node.firstChild.data
else:
return u""
def artist(artist_credit):
"""given an <artist-credit> DOM element,
returns the artist as a unicode string"""
artists = []
# <artist-credit> must contain at least one <name-credit>
for name_credit in get_nodes(artist_credit, u"name-credit"):
try:
# <name-credit> must contain <artist>
# but <artist> need not contain <name>
artists.append(text(get_node(name_credit, u"artist", u"name")))
except KeyError:
artists.append(u"")
# <name-credit> may contain a "joinphrase" attribute
if (name_credit.hasAttribute(u"joinphrase")):
artists.append(name_credit.getAttribute(u"joinphrase"))
return u"".join(artists)
def parse_release(release, disc_id):
"""given a <release> Element node and DiscID object
yields a populated MetaData object per track
may raise KeyError if the given DiscID is not found in the <release>"""
# <release> may contain <title>
try:
album_name = text(get_node(release, u"title"))
except KeyError:
album_name = None
# <release> may contain <artist-credit>
try:
album_artist = artist(get_node(release, u"artist-credit"))
except KeyError:
album_artist = None
# <release> may contain <label-info-list>
try:
# <label-info-list> contains 0 or more <label-info>s
for label_info in get_nodes(get_node(release, u"label-info-list"),
u"label-info"):
# <label-info> may contain <catalog-number>
try:
catalog = text(get_node(label_info, u"catalog-number"))
except KeyError:
catalog = None
# <label-info> may contain <label>
# and <label> may contain <name>
try:
publisher = text(get_node(label_info, u"label", u"name"))
except KeyError:
publisher = None
# we'll use the first result found
break
else:
# <label-info-list> with no <label-info> tags
catalog = None
publisher = None
except KeyError:
catalog = None
publisher = None
# <release> may contain <date>
try:
year = text(get_node(release, u"date"))[0:4]
except:
year = None
# find exact disc in <medium-list> tag
# depending on disc_id value
try:
medium_list = get_node(release, u"medium-list")
except KeyError:
# no media found for disc ID
raise KeyError(disc_id)
for medium in get_nodes(medium_list, u"medium"):
try:
if (unicode(disc_id) in
[disc.getAttribute(u"id")
for disc in get_nodes(get_node(medium, u"disc-list"),
u"disc")]):
# found requested disc_id in <medium>'s list of <disc>s
# so use that medium node to find additional info
break
except KeyError:
# no <disc-list> tag found in <medium>
continue
else:
# our disc_id wasn't found in any of the <release>'s <medium>s
raise KeyError(disc_id)
# if multiple discs in <medium-list>,
# populate album number and album total
if ((medium_list.hasAttribute(u"count") and
(int(medium_list.getAttribute(u"count")) > 1))):
album_total = int(medium_list.getAttribute(u"count"))
try:
album_number = int(text(get_node(medium, u"position")))
except KeyError:
album_number = None
else:
album_total = album_number = None
# <medium> must contain <track-list>
tracks = get_nodes(get_node(medium, u"track-list"), u"track")
track_total = len(tracks)
# and <track-list> contains 0 or more <track>s
for (i, track) in enumerate(tracks):
# if <track> contains title use that for track_name
try:
track_name = text(get_node(track, u"title"))
except KeyError:
track_name = None
# if <track> contains <artist-credit> use that for track_artist
try:
track_artist = artist(get_node(release, u"artist-credit"))
except KeyError:
track_artist = None
# if <track> contains a <recording>
# use that for track_name and track artist
try:
recording = get_node(track, u"recording")
# <recording> may contain a <title>
if (track_name is None):
try:
track_name = text(get_node(recording, u"title"))
except KeyError:
track_name = None
# <recording> may contain <artist-credit>
if (track_artist is None):
try:
track_artist = artist(get_node(recording,
u"artist-credit"))
except KeyError:
track_artist = album_artist
except KeyError:
# no <recording> in <track>
if (track_artist is None):
track_artist = album_artist
# <track> may contain a <position>
try:
track_number = int(text(get_node(track, u"position")))
except KeyError:
track_number = i + 1
# yield complete MetaData object
from audiotools import MetaData
yield MetaData(track_name=track_name,
track_number=track_number,
track_total=track_total,
album_name=album_name,
artist_name=track_artist,
performer_name=None,
composer_name=None,
conductor_name=None,
ISRC=None,
catalog=catalog,
copyright=None,
publisher=publisher,
year=year,
album_number=album_number,
album_total=album_total,
comment=None)