本文整理汇总了Python中musicbrainzngs.get_release_by_id函数的典型用法代码示例。如果您正苦于以下问题:Python get_release_by_id函数的具体用法?Python get_release_by_id怎么用?Python get_release_by_id使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_release_by_id函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getRelease
def getRelease(releaseid, include_artist_info=True):
"""
Deep release search to get track info
"""
with mb_lock:
release = {}
results = None
try:
if include_artist_info:
results = musicbrainzngs.get_release_by_id(releaseid, ["artists", "release-groups", "media", "recordings"]).get('release')
else:
results = musicbrainzngs.get_release_by_id(releaseid, ["media", "recordings"]).get('release')
except musicbrainzngs.WebServiceError as e:
logger.warn('Attempt to retrieve information from MusicBrainz for release "%s" failed (%s)' % (releaseid, str(e)))
time.sleep(5)
if not results:
return False
release['title'] = unicode(results['title'])
release['id'] = unicode(results['id'])
release['asin'] = unicode(results['asin']) if 'asin' in results else None
release['date'] = unicode(results['date']) if 'date' in results else None
try:
release['format'] = unicode(results['medium-list'][0]['format'])
except:
release['format'] = u'Unknown'
try:
release['country'] = unicode(results['country'])
except:
release['country'] = u'Unknown'
if include_artist_info:
if 'release-group' in results:
release['rgid'] = unicode(results['release-group']['id'])
release['rg_title'] = unicode(results['release-group']['title'])
try:
release['rg_type'] = unicode(results['release-group']['type'])
if release['rg_type'] == 'Album' and 'secondary-type-list' in results['release-group']:
secondary_type = unicode(results['release-group']['secondary-type-list'][0])
if secondary_type != release['rg_type']:
release['rg_type'] = secondary_type
except KeyError:
release['rg_type'] = u'Unknown'
else:
logger.warn("Release " + releaseid + "had no ReleaseGroup associated")
release['artist_name'] = unicode(results['artist-credit'][0]['artist']['name'])
release['artist_id'] = unicode(results['artist-credit'][0]['artist']['id'])
release['tracks'] = getTracksFromRelease(results)
return release
示例2: testGetRelease
def testGetRelease(self):
musicbrainzngs.get_release_by_id("5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b")
self.assertEqual("http://musicbrainz.org/ws/2/release/5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b", _common.opener.get_url())
# one include
musicbrainzngs.get_release_by_id("5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b", includes=["artists"])
self.assertEqual("http://musicbrainz.org/ws/2/release/5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b?inc=artists", _common.opener.get_url())
示例3: make_query
def make_query(self, params):
if params["type"] == "artist":
return musicbrainzngs.get_artist_by_id(params["mbid"])
elif params["type"] == "album":
return musicbrainzngs.get_release_by_id(params["mbid"])
elif params["type"] == "tracklist":
return musicbrainzngs.get_release_by_id(params["mbid"],
includes=["recordings"])["release"]["medium-list"][0]["track-list"]
elif params["type"] == "track":
return musicbrainzngs.get_recording_by_id(params["mbid"], includes=["artists"])
示例4: match_tracks_to_release
def match_tracks_to_release(title, tracks, mbid, name):
'''
Given a list of tracks, a candidate release mbid and name this function should return
a score (0.0-1.0) of how well this list of tracks compares to the MB release.
'''
try:
musicbrainzngs.set_useragent(config.USER_AGENT_STRING, config.USER_AGENT_VERSION, config.USER_AGENT_USER)
rel = musicbrainzngs.get_release_by_id(mbid, includes=['recordings'])
except musicbrainzngs.WebServiceError as exc:
print "Something went wrong with the request: %s" % exc
return -1
# print "--- %-40s %s" % (title.encode('utf-8'), name.encode('utf-8'))
matches = []
total = 0.0
print
for i, t in enumerate(rel["release"]["medium-list"][0]["track-list"]):
try:
d = Levenshtein.ratio(clean_string(t['recording']['title']), tracks[i]['clean'])
print "%.3f %2d %-40s | %s" % (d, i+1, clean_string(t['recording']['title']), tracks[i]['clean'])
total += d
except IndexError:
return -1
return total / len(tracks)
示例5: Fetch
def Fetch( self, options ):
if not self.valid:
return
self.fetch_attempts += 1
# Get the song metadata from MB Web Service - invalid release if this fails
try:
self.data = ws.get_release_by_id( self.id, ["artist-credits", "recordings", "labels", "release-groups", "media"] )["release"]
except ws.musicbrainz.ResponseError:
utils.safeprint ( u"Connection Error!" )
self.data = None
return
except ws.musicbrainz.NetworkError:
utils.safeprint ( u"Connection Error!" )
self.data = None
return
self.__ProcessData( options )
# Get cover art for release - no CA if this fails
try:
cover = urllib2.urlopen( "http://coverartarchive.org/release/" + self.id + "/front-500", None, 10 )
except urllib2.HTTPError:
utils.safeprint( u"No cover art in CAA for \"{}\".".format( self.processed_data["album"] ) )
self.art = None
except ( urllib2.URLError, socket.timeout ):
utils.safeprint( u"Connection Error!" )
self.art = None
else:
self.art = self.__PackageCoverArt( cover.read() )
# Successfully retrieved data
self.fetched = True
return self.id
示例6: main
def main(collectionid):
# work -> list recordings
mapping = collections.defaultdict(list)
# map from an id to a name
recordingnames = {}
worknames = {}
for i, releaseid in enumerate(compmusic.musicbrainz.get_releases_in_collection(collectionid)):
print i, releaseid
try:
rel = mb.get_release_by_id(releaseid, includes=["recordings"])
except:
continue
rel = rel["release"]
for medium in rel.get("medium-list", []):
for track in medium.get("track-list", []):
recid = track["recording"]["id"]
recordingnames[recid] = track["recording"]["title"]
recording = mb.get_recording_by_id(recid, includes=["work-rels"])
recording = recording["recording"]
for work in recording.get("work-relation-list", []):
workid = work["work"]["id"]
worknames[workid] = work["work"]["title"]
mapping[workid].append(recid)
data = []
for k, v in mapping.items():
data.append((k, v))
data = sorted(data, key=lambda x: len(x[1]), reverse=True)
all_d = {"recordingnames": recordingnames,
"worknames": worknames,
"data": data
}
json.dump(all_d, open("works_by_recording.json", "w"))
示例7: get_recordings_from_release
def get_recordings_from_release(release):
rel = mb.get_release_by_id(release, includes=["recordings"])["release"]
recordings = []
for m in rel.get("medium-list", []):
for t in m.get("track-list", []):
recordings.append(t["recording"]["id"])
return recordings
示例8: clickevt_album
def clickevt_album(evt):
window_name = mainwin['artistslist'].get_selected_items()[0]["artist"] + " - " + mainwin['albumslist'].get_selected_items()[0]["albums"];
with gui.Window(name='downwin', title=u'' + window_name, height=down_win_height, width=down_win_width, left='323', top='137', bgcolor=u'#F0F0F0', fgcolor=u'#555555', ):
gui.TextBox(name='downloadpath', value=pref.download_dir, height=form_height, left='5', top='0', width=down_input_width, parent='downwin', )
gui.Button(label=u'Download all!', name='btn_down_all', height='35px', width=down_btn_width, left=down_input_width, top='5', default=True, fgcolor=u'#EEEEEE', bgcolor=u'#C0392B', parent='downwin', )
gui.Button(label=u'Download selected!', name='button_down', height='35px', width=down_btn_width, left=down_btn_left, top='5', default=True, fgcolor=u'#EEEEEE', bgcolor=u'#C0392B', parent='downwin', )
with gui.ListView(name='downloadlist', height=down_lv_songs_height, width=down_win_width, left='0', top=form_height, item_count=10, sort_column=0, onitemselected="print ('sel %s' % event.target.get_selected_items())", ):
gui.ListColumn(name='trackposition', text='Nr.', width=50)
gui.ListColumn(name='tracks', text='Tracks', width=300)
gui.ListColumn(name='tracksfound', text='Tracks found', width=150)
gui.ListColumn(name='id', text='', width=0)
gui.Gauge(name='progressbar', height=down_gauge_height, left=0, top=down_gauge_top, width=down_win_width, value=0, )
downwin = gui.get("downwin")
downwin['btn_down_all'].onclick = download_all_songs
plr = pleer.Pleer()
# print(pleer.Pleer())
tracksList = []
(oldtracks_position, oldtracks_json) = mainwin["trackslist"].items()[0]
tracks = m.get_release_by_id(oldtracks_json["id"], includes=["artists", "recordings"])
print(tracks)
for idx, track in enumerate(tracks["release"]["medium-list"][0]["track-list"]):
print(idx)
tracksList.append(plr.search(mainwin['artistslist'].get_selected_items()[0]["artist"] + " " + track["recording"]["title"], track))
lv = downwin["downloadlist"]
lv.items = tracksList
示例9: strip_result
def strip_result(id,make_key,disc_index):
try:
result = musicbrainzngs.get_releases_by_discid(id,includes=["labels","recordings","artist-credits"])
root=result['disc']['release-list'][0]
discid=result['disc']['id']
except musicbrainzngs.ResponseError:
result = musicbrainzngs.get_release_by_id(id,includes=["labels","recordings","artist-credits"])
root=result['release']
discid=None
disc_count=root['medium-count']
track_list=root['medium-list'][disc_index]['track-list']
track_count=root['medium-list'][disc_index]['track-count']
disc_title=root['title']
release=root['id']
out=[]
for track in track_list:
title=track['recording']['title']
item=dict(artists=track['artist-credit-phrase'],
num=track['number'],
title=title,
key=make_key(track=track))
out.append(item)
out_dict=dict(title=disc_title,track_count=track_count,path=the_album,track_list=out,discid=discid,
disc_count=disc_count,release=release)
return out_dict
示例10: get_mb_data
def get_mb_data(id):
id, disc_id = re.search('^(?:http://.+/)?(.+?)(?:#disc(\d+))?$', id).groups()
try:
release = m.get_release_by_id(id, ['artists','recordings','artist-credits'])['release']
except m.MusicBrainzError, exceptions.e:
print 'Error:', exceptions.e
sys.exit(1)
示例11: _get_release
def _get_release(release_id):
"""Returns a release containing all recordings and artists or raises
MusicBrainzError
"""
assert is_mbid(release_id)
return musicbrainzngs.get_release_by_id(
release_id,
includes=["recordings", "artists", "artist-credits"])["release"]
示例12: album_for_id
def album_for_id(albumid):
"""Fetches an album by its MusicBrainz ID and returns an AlbumInfo
object or None if the album is not found.
"""
try:
res = musicbrainzngs.get_release_by_id(albumid, RELEASE_INCLUDES)
except musicbrainzngs.ResponseError:
log.debug('Album ID match failed.')
return None
return album_info(res['release'])
示例13: getReleaseFromMB
def getReleaseFromMB(releaseId):
"""Retrieves release info from MusicBrainz by releaseId."""
if not _initialised:
_initialise()
release = m.get_release_by_id(
releaseId,
includes=["recordings", "artists", "artist-credits", "artist-rels"]
)
return release
示例14: get_release_by_id
def get_release_by_id(release_id):
attempt = 0; # Set attempt number for album art
while attempt < maxAttempt:
try:
result = MB.get_release_by_id( release_id )['release']; # Get information about the relase
except:
attempt+=1; # Increment the attempt counter by one
time.sleep(2); # Sleep 10 seconds
else:
break;
if attempt == maxAttempt: return None; # If MusicBrainz search fails three times, return 2
return result;
示例15: stats_for_release
def stats_for_release(self, releaseid):
self.releases.add(releaseid)
rel = mb.get_release_by_id(releaseid, includes=["recordings", "artist-rels"])
rel = rel["release"]
for disc in rel["medium-list"]:
for track in disc["track-list"]:
recording = track["recording"]["id"]
self.stats_for_recording(recording)
for relation in rel.get("artist-relation-list", []):
artist = relation.get("artist", {}).get("id")
if artist:
self.artists.add(artist)