def getReleases(self, artistResult): q = Query() offset = 0 limit = 100 releaseResults = set() while True: try: f = ReleaseFilter(artistId=artistResult.getKey( MusicbrainzSource._sourceName), offset=offset, limit=limit) results = q.getReleases(f) except WebServiceError, e: raise SourceError count = len(results) results = filter(lambda res: res.getScore() == 100, results) for r in results: rr = ReleaseResult( title=r.getRelease().getTitle(), date=r.getRelease().getEarliestReleaseDate(), tracksCount=r.getRelease().getTracksCount()) rr.setKey(MusicbrainzSource._sourceName, r.getRelease().getId()) releaseResults.add(rr) if count < limit: break offset += count
def FetchTrackListByArtistRelease(self, string_artist_name, string_release_name): musicbrainz_query = Query() try: # Search for all releases matching the given name. Limit the results # to the first best matches. string_release_id = "" string_release_title = "" musicbrainz_release_filter = ReleaseFilter(title=string_release_name, artistName=string_artist_name, limit=1) musicbrainz_release_results = musicbrainz_query.getReleases(musicbrainz_release_filter) if musicbrainz_release_results is not None: if len(musicbrainz_release_results) > 0: string_release_id = musicbrainz_release_results[0].getRelease().getId() string_release_title = musicbrainz_release_results[0].getRelease().getTitle() include_info = ReleaseIncludes(artist=True, tracks=True) release = self.__musicbrainz_query__.getReleaseById(string_release_id, include_info) track_list = [] for track in release.getTracks(): track_title = track.getTitle() for escape_char in self.__escape_list__: track_title = track_title.replace(escape_char, "") track_list.append(track_title) return string_release_title, track_list except WebServiceError, e: # print 'Error:', e return []
def getReleases(self, artistResult): q = Query() offset = 0 limit = 100 releaseResults = set() while True: try: f = ReleaseFilter(artistId = artistResult.getKey(MusicbrainzSource._sourceName), offset = offset, limit = limit) results = q.getReleases(f) except WebServiceError, e: raise SourceError count = len(results) results = filter(lambda res: res.getScore() == 100, results) for r in results: rr = ReleaseResult(title = r.getRelease().getTitle(), date = r.getRelease().getEarliestReleaseDate(), tracksCount = r.getRelease().getTracksCount()) rr.setKey(MusicbrainzSource._sourceName, r.getRelease().getId()) releaseResults.add(rr) if count < limit: break offset += count
def populate_album_set(self): """ Find and create models for all albums released by this artist. Only albums with an Amazon ASIN are imported, to try and stop the database getting clogged up with b-sides, remixes, and bonus material. """ # We can't do anything without the MusicBrainz and Last.fm libraries. try: ReleaseFilter except NameError: return False # Find any official album release held by MusicBrainz for this artist. filter = ReleaseFilter(artistName=self.name, releaseTypes=(Release.TYPE_ALBUM, Release.TYPE_OFFICIAL)) query = Query() releases = query.getReleases(filter) for release in releases: album = release.release # Only import albums with an Amazon ASIN. That allows for some # quality-control as Music Brainz lists every B-side and bonus # material you can think of. if album.asin: # First try and find an already-existing album with this ASIN # As an ASIN is unique it means we'll find it even if the fields # have been changed since creation. try: db_album = Album.objects.get(asin=album.asin) except Album.DoesNotExist: db_album = Album(artist=self, title=album.title, asin=album.asin, mbid=album.id.rsplit("/", 1)[1]) # MusicBrainz stores releases dates for as many countries as # it can. I'm only interested in Britain though, so look # for that first. As a fallback, us the world wide release # date (XE) or the US release date. release_dates = dict( (r.country, r.date) for r in album.releaseEvents) if release_dates: # GB = United Kingdom, XE = world, US = United States. for country in ('GB', 'XE', 'US'): if release_dates.has_key(country): db_album.released_in = country # The release date can be in the format "2010", # "2010-02", or "2010-02-18", so make up the # missing month and/or day so a proper release # date object can be created. release_date = release_dates[country] date_list = map(int, release_date.split('-')) try: db_album.release_date = datetime.date( *date_list + [1] * (3 - len(date_list))) except ValueError: pass # Date couldn't be parsed. break db_album.save()
def populate_album_set(self): """ Find and create models for all albums released by this artist. Only albums with an Amazon ASIN are imported, to try and stop the database getting clogged up with b-sides, remixes, and bonus material. """ # We can't do anything without the MusicBrainz and Last.fm libraries. try: ReleaseFilter except NameError: return False # Find any official album release held by MusicBrainz for this artist. filter = ReleaseFilter(artistName=self.name, releaseTypes=(Release.TYPE_ALBUM, Release.TYPE_OFFICIAL)) query = Query() releases = query.getReleases(filter) for release in releases: album = release.release # Only import albums with an Amazon ASIN. That allows for some # quality-control as Music Brainz lists every B-side and bonus # material you can think of. if album.asin: # First try and find an already-existing album with this ASIN # As an ASIN is unique it means we'll find it even if the fields # have been changed since creation. try: db_album = Album.objects.get(asin=album.asin) except Album.DoesNotExist: db_album = Album(artist=self, title=album.title, asin=album.asin, mbid=album.id.rsplit("/", 1)[1]) # MusicBrainz stores releases dates for as many countries as # it can. I'm only interested in Britain though, so look # for that first. As a fallback, us the world wide release # date (XE) or the US release date. release_dates = dict((r.country, r.date) for r in album.releaseEvents) if release_dates: # GB = United Kingdom, XE = world, US = United States. for country in ('GB', 'XE', 'US'): if release_dates.has_key(country): db_album.released_in = country # The release date can be in the format "2010", # "2010-02", or "2010-02-18", so make up the # missing month and/or day so a proper release # date object can be created. release_date = release_dates[country] date_list = map(int, release_date.split('-')) try: db_album.release_date = datetime.date( *date_list + [1] * (3 - len(date_list))) except ValueError: pass # Date couldn't be parsed. break db_album.save()
def getReleases(self,filter=filter) : p = md5.new(pickle.dumps(filter)).hexdigest() cache_file = os.path.join(CACHE_DIR,'release_q',p) if os.path.exists(cache_file) : instream = open(cache_file,"r") toret = pickle.loads(instream.read()) instream.close() return toret else : self.throttle() toret = Query.getReleases(self,filter=filter) outstream = open(cache_file,"w") outstream.write(pickle.dumps(toret)) outstream.close() return toret
def getReleases(self, filter=filter): p = md5.new(pickle.dumps(filter)).hexdigest() cache_file = os.path.join('cache', 'release_q', p) if os.path.exists(cache_file): instream = open(cache_file, "r") toret = pickle.loads(instream.read()) instream.close() return toret else: self.throttle() toret = Query.getReleases(self, filter=filter) outstream = open(cache_file, "w") outstream.write(pickle.dumps(toret)) outstream.close() return toret
class Tagger(object): def __init__(self): self.query = Query() def guess_artist_and_disc(self, files): rel = files[0] abs = os.path.normpath(os.path.join(os.getcwdu(), rel)) dir = os.path.basename(os.path.dirname(abs)) parts = re.split('\s+-\s+', dir) if len(parts) >= 2: return parts[0], parts[1] elif len(parts) == 1: return "", parts[0] else: return "", "" def find_releases(self, artist, disc_title, track_count): query_limit = 100 f = ReleaseFilter(artistName=artist, title=disc_title, limit=query_limit) results = self.query.getReleases(f) if len(results) == query_limit: print """\ Woah! the specified artist/disc names were pretty vague we weren't able to check all possible candiates. Please try to be more specific if the correct album isn't in the following list. """ releases = [] for result in results: # wrap result into our own structure release = Release(result.release, self.query) # only keep releases with correct amount of tracks if track_count < 0 or release.tracks_total == track_count: releases.append(release) releases.sort(key=lambda r: r.title) return releases def find_release_by_mbid(self, mbid, track_count): include = ReleaseIncludes(artist=True, tracks=True) try: result = self.query.getReleaseById(mbid, include) except ResourceNotFoundError: error("There is no Release with this Musicbrainz ID") release = Release(result, self.query, details_included=True) if release.tracks_total == track_count: return release else: error("Unexpected track count for '%s - %s' expected %i but was %i" % (release.artist.name, release.title, track_count, release.tracks_total)) def order_files(self, files, tracks): """Make self.files have the same order as the tracks.""" ordered_files = [] remaining_files = list(files) for track in tracks: def similarity(file): # Strip directories and extension file = os.path.splitext(os.path.basename(file))[0] file_parts = distinctive_parts(file) track_parts = distinctive_parts(track.title) + [track.number] score = 0 for part in track_parts: if part in file_parts: score += 1 file_parts.remove(part) return score most_similar = max(remaining_files, key=similarity) remaining_files.remove(most_similar) ordered_files.append(most_similar) return ordered_files def tag(self, files, release, genre=None, strip_existing_tags=False, progress=None): files_and_tracks = zip(files, release.tracks) for file, track in files_and_tracks: if strip_existing_tags: id3.delete(file) apev2.delete(file) try: tag = id3.ID3(file) except id3.ID3NoHeaderError: tag = id3.ID3() tag.add(id3.TPE1(3, track.artist.name)) tag.add(id3.TALB(3, track.release.title)) tag.add(id3.TIT2(3, track.title)) tag.add(id3.TDRC(3, track.release.earliestReleaseDate)) tag.add(id3.TRCK(3, track.number_str())) if track.release.album_artist is not None: tag.add(id3.TPE2(3, track.release.album_artist)) discset = track.release.discset if discset: disc_num = discset.number_str() tag.add(id3.TPOS(3, disc_num)) if discset.desc: tag.delall('COMM') tag.add(id3.COMM(3, text=discset.desc, desc='', lang='eng')) if genre is not None: tag.add(id3.TCON(3, genre)) tag.add(id3.UFID(owner='http://musicbrainz.org', data=track.uuid)) tag.save(file) if progress is not None: progress(file, track) def rename(self, files, release, progress=None): warnings = [] for file, track in zip(files, release.tracks): filename = "%02i. %s.mp3" % (track.number, track.title) filename = make_fs_safe(filename) new_file = os.path.join(os.path.dirname(file), filename) if new_file == file: continue if os.path.exists(new_file): w = '"%s" already exists, not overwriting.' % new_file warnings.append(w) continue os.rename(file, new_file) if progress is not None: progress(file, track) return warnings