def find_releases(artists_set, year_month):
    good = u""
    questionable = u""

    for artist in artists_set:
        result = musicbrainzngs.search_releases(
            query=u"artist:\"{}\" AND date:{}-?? AND status:official AND primarytype:album".format(artist, year_month))

        if not result['release-list']:
            Logger.debug("no release found for artist %s", artist)

        music_brains_links = u""
        for (idx, rel) in enumerate(result['release-list'], start=1):
            log_album(artist, rel, idx)
            music_brains_links += u'<a href="http://musicbrainz.org/release/{}">{}</a> '\
                .format(rel['id'], rel.get('country', 'NONE'))
            if idx < len(result['release-list']) and rel['title'] == result['release-list'][idx]['title']:
                continue

            album_info = u"<b>{}</b>".format(artist)
            if artist != rel["artist-credit-phrase"]:
                album_info += u"({})".format(rel["artist-credit-phrase"])

            album_info += u" - {} - Released {} in {}<br/>\n".format(rel['title'], rel['date'], music_brains_links)
            music_brains_links = u""
            album_info += u'Links: <a href="https://play.google.com/music/listen#/sr/{0}">Google Music</a> ' \
                          u'<a href="http://www.emusic.com/search/music/?s={0}">eMusic</a> ' \
                          u'<br/><br/>'.format(urllib.quote_plus(rel['title'].encode('utf8')))

            if artist.lower() == rel["artist-credit-phrase"].lower():
                good += album_info
            else:
                questionable += album_info

    return good + questionable
示例#2
0
文件: mb.py 项目: artemutin/beets
def match_album(artist, album, tracks=None):
    """Searches for a single album ("release" in MusicBrainz parlance)
    and returns an iterator over AlbumInfo objects. May raise a
    MusicBrainzAPIError.

    The query consists of an artist name, an album name, and,
    optionally, a number of tracks on the album.
    """
    # Build search criteria.
    criteria = {'release': album.lower().strip()}
    if artist is not None:
        criteria['artist'] = artist.lower().strip()
    else:
        # Various Artists search.
        criteria['arid'] = VARIOUS_ARTISTS_ID
    if tracks is not None:
        criteria['tracks'] = six.text_type(tracks)

    # Abort if we have no search terms.
    if not any(criteria.values()):
        return

    try:
        res = musicbrainzngs.search_releases(
            limit=config['musicbrainz']['searchlimit'].get(int), **criteria)
    except musicbrainzngs.MusicBrainzError as exc:
        raise MusicBrainzAPIError(exc, 'release search', criteria,
                                  traceback.format_exc())
    for release in res['release-list']:
        # The search result is missing some data (namely, the tracks),
        # so we just use the ID and fetch the rest of the information.
        albuminfo = album_for_id(release['id'])
        if albuminfo is not None:
            yield albuminfo
示例#3
0
文件: mb.py 项目: jwyant/beets
def match_album(artist, album, tracks=None, limit=SEARCH_LIMIT):
    """Searches for a single album ("release" in MusicBrainz parlance)
    and returns an iterator over AlbumInfo objects. May raise a
    MusicBrainzAPIError.

    The query consists of an artist name, an album name, and,
    optionally, a number of tracks on the album.
    """
    # Build search criteria.
    criteria = {"release": album.lower()}
    if artist is not None:
        criteria["artist"] = artist.lower()
    else:
        # Various Artists search.
        criteria["arid"] = VARIOUS_ARTISTS_ID
    if tracks is not None:
        criteria["tracks"] = str(tracks)

    # Abort if we have no search terms.
    if not any(criteria.itervalues()):
        return

    try:
        res = musicbrainzngs.search_releases(limit=limit, **criteria)
    except musicbrainzngs.MusicBrainzError as exc:
        raise MusicBrainzAPIError(exc, "release search", criteria, traceback.format_exc())
    for release in res["release-list"]:
        # The search result is missing some data (namely, the tracks),
        # so we just use the ID and fetch the rest of the information.
        albuminfo = album_for_id(release["id"])
        if albuminfo is not None:
            yield albuminfo
示例#4
0
	def getNowTracks(self, albumnumber):
		rx = re.compile('\W');
		ret = []
		res = musicbrainzngs.search_releases(query='Now That\'s What I Call Music ' + str(albumnumber))
		if(not('release-list' in res)):
			return ret
		for release in res['release-list']:
			title = rx.sub('', release['title'].encode('ascii', 'ignore').lower())
			if title != 'nowthatswhaticallmusic' + str(albumnumber):
				continue
			if release['country'] != 'GB':
				continue
			format = 0
			for medium in release['medium-list']:
				if 'format' in medium:
					if medium['format'] == 'CD':
						format = 1
			if format == 1:
				ret.append(release)

		if len(ret) == 1:
			mbid = ret[0]['id']
			return self.getCompilationAlbumTracks(mbid)

		ret = []
		return ret
示例#5
0
def search_releases(artist, album, limit):
    from lxml import etree

    root = etree.XML(u'<searchreleases></searchreleases>')

    result = musicbrainzngs.search_releases(artist=artist, release=album, country="GB", limit=limit)

    if not result['release-list']:
        etree.SubElement(root, "error").text = "No Releases found"
        log(True, etree.tostring(root, encoding='UTF-8', pretty_print=True, xml_declaration=True))
        sys.exit(1)

    for (idx, release) in enumerate(result['release-list']):
        pprint.pprint(release)
        relNode = etree.SubElement(root, "release")

        etree.SubElement(relNode, "id").text = release['id']
        etree.SubElement(relNode, "ext-score").text = release['ext:score']
        etree.SubElement(relNode, "title").text = release['title']
        etree.SubElement(relNode, "artist-credit-phrase").text = release["artist-credit-phrase"]
        etree.SubElement(relNode, "country").text = release["country"]

        if 'date' in release:
            etree.SubElement(relNode, "date").text = release['date']
            etree.SubElement(relNode, "status").text = release['status']

        if 'release-group' in release:
            etree.SubElement(relNode, "releasegroup").text = release["release-group"]["id"]

    log(True, etree.tostring(root, encoding='UTF-8', pretty_print=True, xml_declaration=True))

    sys.exit(0)
示例#6
0
    def MBReleaseTitle(self):
        """Search for release on musicbrainz by title"""
        title = raw_input('Enter title: ')
        results = musicbrainzngs.search_releases(release=title,
                                                 limit=self.searchResultsLimit)

        if results:
            self.printQueryResults(results)
示例#7
0
    def MBReleaseGroup(self):
        """Search for releases on musicbrainz by group ID"""
        rgid = raw_input('Enter release group ID: ')
        results = musicbrainzngs.search_releases(rgid=rgid,
                limit=self.searchResultsLimit)

        if results:
            self.printQueryResults(results)
示例#8
0
def find_releases(name, limit=10, artist_id=None,
                  wanted_keys=('name', 'id', 'title', 'country', 'release-group', 'ext:score', 'asin')):
    with musicbrainz_lock:
        strict = True if artist_id else False
        params = {'release': name, 'arid': artist_id}
        search_results = musicbrainzngs.search_releases(limit=limit, strict=strict, **params)['release-list']
        sorted_by_score = sorted(search_results, cmp=lambda x, y: max(x, y), key=lambda d: int(d['ext:score']))
        return [{k: v for k, v in d.items() if k in wanted_keys} for d in sorted_by_score]
示例#9
0
    def MBReleaseBarcode(self):
        """Search for release on musicbrainz by barcode"""
        barcode = raw_input('Enter barcode: ')
        results = musicbrainzngs.search_releases(barcode=barcode,
                                                 limit=self.searchResultsLimit)

        if results:
            self.printQueryResults(results)
示例#10
0
    def _request(query, artist, album=None, track=None):
        results = None
        if track:
            results = musicbrainzngs.search_recordings(query=query)
        elif album:
            results = musicbrainzngs.search_releases(query=query)
        elif artist:
            results = musicbrainzngs.search_artists(query=query)

        return results
示例#11
0
def artistSearch(artist):
    if request.method == 'POST':
        artist = request.form['artist']
    if artist == '':
        return redirect(url_for('artistSearch', artist='artistSearch'))
    searched = artist
    result = musicbrainzngs.search_releases(artist=artist, limit=5)
    # relList = result['release-list']
    relList = releaseInfo(result['release-list'])
    return render_template('release_results.html', releases=relList, 
          search_by='artist', searched=searched)
示例#12
0
def catnoSearch(catno):
    if request.method == 'POST':
        catno = request.form['catno']
    if catno == '':
        return redirect(url_for('catnoSearch', catno='catnoSearch'))
    searched = catno
    result = musicbrainzngs.search_releases(catno=catno, limit=5)
    # relList = result['release-list']
    relList = releaseInfo(result['release-list'])
    return render_template('release_results.html', releases=relList, 
          search_by='catno', searched=searched)
示例#13
0
def barcodeSearch(barcode):
    if request.method == 'POST':
        barcode = request.form['barcode']
    if barcode == '':
        return redirect(url_for('barcodeSearch', barcode='barcodeSearch'))
    searched = barcode
    result = musicbrainzngs.search_releases(barcode=barcode, limit=5)
    # relList = result['release-list']
    relList = releaseInfo(result['release-list'])
    return render_template('release_results.html', releases=relList, 
          search_by='barcode', searched=searched)
示例#14
0
    def MBReleaseCatno(self):
        """Search for release on musicbrainz by catalog number"""
        catno = raw_input('Enter catalog number: ')
        if ' ' in catno:
            _log.warning('Removing whitespaces from string (workaround)')
            catno = catno.replace(' ', '')
        results = musicbrainzngs.search_releases(catno=catno,
                limit=self.searchResultsLimit)

        if results:
            self.printQueryResults(results)
示例#15
0
def searchMusicBrainzAlbumAndArtist(artist, album):
	"""searchMusicBrainzByID looks for a release ID by an album and an artist"""
	result = musicbrainzngs.search_releases(artist=artist, release=album)
	results = []
	if not result['release-list']:
		return results
	for release in result['release-list']:
		
		# If we haven't seen this id yet, add it to the return list
		if release.get('id') not in results:
			results.append(release.get('id'))
	return results
def search_releases(artist, album, quality):
  attempt = 0;
  while attempt < maxAttempt:
    try:
      result = MB.search_releases(artist=artist, release=album, quality=quality);# Attempt to get release information
    except:
      attempt+=1;                                                               # Increment the attempt counter by one
      time.sleep(2);                                                            # Sleep 2 seconds
    else:  
      break;  
  if attempt == maxAttempt: return None;                                         # If MusicBrainz search fails three times, return 2
  return result;  
示例#17
0
def get_releases(artist_id, release_group_id):

	records = dict()
	result = musicbrainzngs.search_releases(arid=artist_id,rgid=release_group_id,strict=True)

	for release in result['release-list']:

		release_name = release['title']
		release_mbid = release['id']
		records.update({release_mbid: release_name})

	return records
示例#18
0
文件: app.py 项目: scampion/pdfmp3
def MusicBrainz(release_path, query, ofile):
    try:
        r = musicbrainzngs.search_releases(query.replace('-', ''))
        id = r['release-list'][0]['id']
        img = musicbrainzngs.get_image_list(id)
        url = img['images'][0]['image']
        urllib.urlretrieve(url, ofile)
        print("OK " + ofile)
        return query, ofile
    except Exception as e:
        print("Error for %s (%s)" % (release_path, e))
        traceback.print_exc()
        return genimage(release_path, query, ofile)
示例#19
0
def fetch_album_search_results(artist, album, search_limit=5):
    """Searches MusicBrainz fora given album, and returns a generator
    yielding relevant information from the first 'search_limit' results."""

    try:
        results = musicbrainzngs.search_releases(
            artist=artist, release=album, limit=search_limit)
    except musicbrainzngs.MusicBrainzError:
        raise

    final = []
    for release in results["release-list"]:
        if "id" in release:
            info = fetch_album_from_id(release["id"])
            final.append(info)

    return final
示例#20
0
def searchMusicBrainzAlbumsByArtist(artist):
	"""searchMusicBrainzAlbumsByArtists takes an artist name as a string and returns a list of album
	titles by the given artist."""

	result = musicbrainzngs.search_releases(artist=artist, limit=15)
	
	results = []
	titleTracker = []
	if not result['release-list']:
		return results

	for release in result['release-list']:
		# Make sure this is an album, not a single
		releaseGroup = release.get('release-group', None)
		if releaseGroup != None and releaseGroup.get('primary-type', 'Album') != "Album":
			continue
		
		mediumList = release.get('medium-list', [])
		if len(mediumList) > 1:
			mediumDict = mediumList[1]
			if mediumDict.get('format', '') != "CD":
				continue
		
		# Make sure this is not a bootleg copy
		if release.get('status', '') != "Official":
			continue
		
		labelName = ""
		labelInfo = release.get('label-info-list', None)
		
		if labelInfo != None:
			labelInfo = labelInfo[0]
			label = labelInfo.get('label', None)
			
			if label != None:
				labelName = label.get('name', '')
		
				
		newDict = {'artist': release.get('artist-credit-phrase'), 'title': release.get('title'), \
			'date': release.get('date'), 'label': labelName, 'mb-id': release.get('id')}
					
		# Make sure the artist is the one we were searching for and if so, add the album title
		if newDict['artist'].lower() == artist.lower() and newDict['title'].lower() not in titleTracker:
			results.append(newDict)
			titleTracker.append(newDict['title'].lower())
	return results
示例#21
0
def searchMusicBrainzAlbumsByArtist(artist):
	"""searchMusicBrainzAlbumsByArtists takes an artist name as a string and returns a list of album
	titles by the given artist."""

	result = musicbrainzngs.search_releases(artist=artist, limit=15)
	
	results = []
	if not result['release-list']:
		return results
	for release in result['release-list']:
		# Grab just the name of the artist
		resultArtist = release['artist-credit-phrase']
		
		# Make sure the artist is the one we were searching for and if so, add the album title
		if resultArtist == artist and release['title'] not in results:
			results.append(release['title'])
	return results
示例#22
0
def getSongs(whatGroup):
  mbAlbum = mb.search_releases(
    artistname=mbquote(whatGroup['artist']),
   release= mbquote(whatGroup['groupName']), 
    limit=1)['release-list']
  return [
    (x['recording']['title'],
      int(float(
        x['recording']['length'] if 'length' in x['recording'] 
        else (x['track_or_recording_length'] if 'track_or_recording_length' in x 
        else x['length'] if 'length' in x else 0)
      )/1000.))
    for tracklist in 
      mb.get_release_by_id(
        mbAlbum[0]['id'],
        includes=['recordings'])['release']['medium-list']
    for x in tracklist['track-list']]
    def test_search_releases(self):
        musicbrainzngs.search_releases("Affordable Pop Music")
        self.assertEqual("http://musicbrainz.org/ws/2/release/?query=Affordable+Pop+Music", self.opener.get_url())

        musicbrainzngs.search_releases(release="Affordable Pop Music")
        expected_query = 'release:(affordable pop music)'
        expected = 'http://musicbrainz.org/ws/2/release/?query=%s' % musicbrainzngs.compat.quote_plus(expected_query)
        self.assertEquals(expected, self.opener.get_url())

        # Invalid query field
        with self.assertRaises(musicbrainzngs.InvalidSearchFieldError):
            musicbrainzngs.search_releases(foo="value")
示例#24
0
def getTorrentMetadata(albumGroup, albumArtistCredit = None):
  def checkArtistTypes(types):
    whatArtists = [unescape(x['name']) for x in albumGroup['group']['musicInfo'][types[0]]]
    types.pop(0)
    if len(whatArtists) == 1:
      return whatArtists
    elif len(whatArtists)>1:
      return whatArtists+[unescape(x['name']) for y in types for x in albumGroup['group']['musicInfo'][y]]
    return checkArtistTypes(types) if len(types)>0 else []
  #is this not music?
  if albumGroup['group']['categoryName'] != 'Music':
    print("Group "+albumGroup['group']['name']+" is not music")
    return {}
  #determine trueartists using musicbrainz
  whatArtists = checkArtistTypes(['artists','composers','conductor','dj'])
  if len(whatArtists) == 1:
    artists = whatArtists
  else:
    if len(whatArtists)==0:
      whatArtists = [unescape(y['name']) for x in albumGroup['group']['musicInfo'] if x not in ['artists','composers','dj'] for y in albumGroup['group']['musicInfo'][x]]
    if albumArtistCredit is None:
      albums = []
      for x in whatArtists:
        albums+=mb.search_releases(artistname=mbquote(x),release=mbquote(albumGroup['group']['name']),limit=int(50*mbMultiplier))['release-list']
      ranks = {}
      for x in albums:
        ranks[x['id']]=Levenshtein.ratio(albumGroup['group']['name'].lower(),x['title'].lower())
      albumRankMax=max(ranks.values())
      albumArtistCredit = ' '.join([ z['artist-credit-phrase'] for z in albums if ranks[z['id']]>=(albumRankMax*0.9)])
    artists = [ unescape(x) for x in whatArtists 
      if unescape(x.lower()) in albumArtistCredit.lower()] #split by what artists
    if len(artists)==0:  
      raise RuntimeError("Len of artists is zero!!")
  torrent = reduce(lambda x,y: compareTors(x,y),albumGroup["torrents"])
  print("Original artists are: "+', '.join(whatArtists))
  print("Final artists are: "+', '.join(artists))
  metadata = {
    'whatid' : torrent['id'],
    'album':unescape(albumGroup['group']['name']),
    'path_to_album':'',
    'artists':sorted(artists),
    #Songs need to be gotten by their levienshtein ratio to filenames and closeness of duration
    'format':torrent['format'].lower()#fix this like path
  }
  return metadata
示例#25
0
def searchMusicBrainzAlbum(album):
	""" searchMusicBrainzAlbum takes an album name as a string and returns a list of dictionaries,
	with each dictionary holding information about an album: artist name, album title, and id number."""
	
	result = musicbrainzngs.search_releases(release=album, limit=5)
	# On success, result is a dictionary with a single key:
	# "release-list", which is a list of dictionaries.
	results = []
	if not result['release-list']:
		return results
	for release in result['release-list']:
		# Make a new dictionary with the artist, album, and id number
		newDict = {'artist': release['artist-credit-phrase'], 'album': release['title'], 'id': release['id']}
		
		# If we haven't already seen this one, add it to the results
		if newDict not in results:
			results.append(newDict)
	return results
 def com_mediabrainz_get_releases(self, disc_id=None, artist_name=None,
                                  artist_recording=None, return_limit=5, strict_flag=False):
     """
     # search by artist and album name
     """
     if disc_id is not None:
         result = musicbrainzngs.get_releases_by_discid(disc_id,
                                                        includes=["artists", "recordings"])
     else:
         result = musicbrainzngs.search_releases(artist=artist_name, release=artist_recording,
                                                 limit=return_limit, strict=strict_flag)
     if not result['release-list']:
         common_global.es_inst.com_elastic_index('error', {'stuff': "no release found"})
         return None
     else:
         for (idx, release) in enumerate(result['release-list']):
             common_global.es_inst.com_elastic_index('info', {"match #{}:".format(idx + 1)})
             self.show_release_details(release)
         return release['id']
示例#27
0
    def find_covers(self, track, limit=-1):
        """
            Performs the search
        """
        try:
            artist = track.get_tag_raw('artist')[0]
            album = track.get_tag_raw('album')[0]
        except (AttributeError, TypeError):
            return []

        result = musicbrainzngs.search_releases(
            release=album,
            artistname=artist,
            format='CD',
            limit=3 # Unlimited search is slow
        )

        if result['release-list']:
            mbids = [a['id'] for a in result['release-list']]
            
            # Check the actual availability of the covers
            for mbid in mbids[:]:
                try:
                    url = self.__caa_url.format(mbid=mbid, size=250)
                    
                    headers = {'User-Agent': self.user_agent}
                    req = urllib2.Request(url, None, headers)
                    response = urllib2.urlopen(req)
                except urllib2.HTTPError:
                    mbids.remove(mbid)
                else:
                    response.close()

            # For now, limit to small sizes
            mbids = [mbid + ':250' for mbid in mbids]

            return mbids

        return []
示例#28
0
def get_release_date(artist, album, title):

    try:
        result = musicbrainzngs.search_releases(artist=artist, release=album, limit=20, strict=True)  
    except:
        return "No date cxception (search_releases)"
    
    #release_list = result['release-list'] # can be missing
    
    if 'release-list' in result:
            release_list = result['release-list'] # can be missing
            dates = [d['date'][0:4] for d in release_list if 'date' in d and int(d['ext:score']) > 90] 
    
            if dates:
                dates.sort()
                return dates[0]  
        
    # above may not work if it's a collection album with a made up name; the below tries to address that 
    try:
        result = musicbrainzngs.search_recordings(artist=artist, recording=title, limit=20, offset=None, strict=False)
    except:
        return "No date exception (search_recordings)"
    
    recording_list = result['recording-list']
    
    dates = []
    for d in recording_list:
            if 'release-list' in d:
                dd = [x['date'][0:4]+': '+x['title'] for x in d['release-list'] if 'date' in x and int(d['ext:score']) > 90]     
                dates.extend(dd)
            
               #[item for sublist in l for item in sublist] - this should work but not sure it makes sense to modify above which works
            
    if dates:
        dates.sort()
        return dates[0]   
    else:
        return "No date" 
示例#29
0
def _get_matching_release(album: Album) -> Dict:
    """Gets a matching musicbrainz release for a given album.

    Args:
        album: Album used to search for the release.

    Returns:
        Dictionary of release information. See ``tests/resources/musicbrainz`` for
        an idea of what this contains.
    """
    if album.mb_album_id:
        return _get_release_by_id(album.mb_album_id)

    search_criteria: Dict = {}
    search_criteria["artist"] = album.artist
    search_criteria["release"] = album.title
    search_criteria["date"] = album.date.isoformat()

    releases = musicbrainzngs.search_releases(limit=1, **search_criteria)

    release = releases["release-list"][0]
    return _get_release_by_id(
        release["id"])  # searching by id provides more info
def get_release_date(artist, album, title):
    print "in get release date"
    t = "artist = {}; album = {} [used in search], title = {} [in get_release_date]".format(artist, album, title)
    print t.encode('ascii', 'ignore')

    # commented this out because I think in most circumstances where there is a legit album, there is an accompanying date
    # (like for a ripped CD, a Rhapsody song, Pandora
    # In addition, this allows you to display the first album where the song appeared 
    try:
        result = musicbrainzngs.search_releases(artist=artist, release=album, limit=20, strict=True)
    except:
        return "No date exception (search_releases)"
    
    release_list = result['release-list'] # can be missing
    
    if 'release-list' in result:
        release_list = result['release-list'] # can be missing
        dates = [d['date'][0:4] for d in release_list if 'date' in d and int(d['ext:score']) > 90] 
    
        if dates:
            dates.sort()
            return "{}".format(dates[0])  
    print "Leaving get release date"
    return ''
示例#31
0
文件: brainz.py 项目: pimoroni/pidi
def get_cover(song, size=250, retry_delay=5, retries=5):
    """Download the cover art."""
    artist = song.get('artist')
    title = song.get('title')
    album = song.get('album', title)
    try:
        data = mus.search_releases(artist=artist,
                                   release=album,
                                   limit=1)
        release_id = data["release-list"][0]["release-group"]["id"]
        print("album: Using release-id: {}".format(data['release-list'][0]['id']))

        return mus.get_release_group_image_front(release_id, size=size)

    except mus.NetworkError:
        if retries == 0:
            raise mus.NetworkError("Failure connecting to MusicBrainz.org")
        print("warning: Retrying download. {retries} retries left!".format(retires=retries))
        time.sleep(retry_delay)
        get_cover(song, size, retries=retries - 1)

    except mus.ResponseError:
        print("error: Couldn't find album art for",
              "{artist} - {album}".format(artist=artist, album=album))
示例#32
0
    def get_album(self, album_entity):
        artistname = album_entity.artists[0].name if len(album_entity.artists) > 0 else None

        try:
            result = mb.search_releases(release=album_entity.name, artistname=artistname)
        except (ResponseError, NetworkError) as error:
            return None

        if len(result['release-list']) == 0:
            return None

        release = mb.get_release_by_id(result['release-list'][0]['id'],
                                       includes=['release-rels', 'url-rels'])['release']

        translit = None

        if 'release-relation-list' in release:
            for release_rel in release['release-relation-list']:
                if release_rel['type'] == 'transl-tracklisting':
                    translit = release_rel['release']['title']
                    break

        urls = {}

        if 'url-relation-list' in release:
            for url in release['url-relation-list']:
                if url['type'] not in urls:
                    urls[url['type']] = []

                urls[url['type']].append(url['target'])

        return {
            'id': release['id'],
            'translit': translit,
            'urls': urls
        }
示例#33
0
def get_release_date(artist, album, title):

    t = "artist = {}; album = {} [used in search], title = {} [in get_release_date]".format(artist, album, title)
    print t.encode('ascii', 'ignore')

    # commented this out because I think in most circumstances where there is a legit album, there is an accompanying date
    # (like for a ripped CD, a Rhapsody song, Pandora
    # In addition, this allows you to display the first album where the song appeared 
    try:
        result = musicbrainzngs.search_releases(artist=artist, release=album, limit=20, strict=True)
    except:
        return "No date exception (search_releases)"
    
    release_list = result['release-list'] # can be missing
    
    if 'release-list' in result:
        release_list = result['release-list'] # can be missing
        dates = [d['date'][0:4] for d in release_list if 'date' in d and int(d['ext:score']) > 90] 
    
        if dates:
            dates.sort()
            return "{}".format(dates[0])  

    return ''
示例#34
0
def main():
    musicbrainzngs.set_useragent("Folder renamer", "0.1", "*****@*****.**")
    for d in (d for d in listdir(curdir) if isdir(join(curdir, d))):
        files = (f for f in listdir(join(curdir, d))
                 if isfile(join(curdir, d, f)))
        for f in files:
            if f.endswith('.mp3'):
                process_mp3_album(d, f)
                break
            for subdir in (subdir for subdir in listdir(join(curdir, d))
                           if isdir(join(curdir, d, subdir))):
                error_log.write(
                    'WARNING: Subfolders detected "{}".\n'.format(d))
                files = (f for f in listdir(join(curdir, d, subdir))
                         if isfile(join(curdir, d, subdir, f)))
                for f in files:
                    if splitext(f)[1] == '.mp3':
                        process_mp3_album(join(d, subdir), f)
                    break
                break
    cnt = 0
    f = open('preview.log', 'w+')
    for e in albums:
        f.write('Item #{}\n{}\n'.format(cnt, str(e)))
        # rename(join(curdir, e.current_path), join(curdir, e.new_path))
        cnt += 1
    results = musicbrainzngs.search_releases(query="AS", limit=3, tracks=6)
    selector = 0
    print(
        'Please select an entry that matches with the album you are trying to rename ("s" to skip, "w" to whitelist):'
    )
    for res in results['release-list']:
        print("{}. {} by {}, {} tracks, released in {}, score {}".format(
            selector, res['title'], res['artist-credit-phrase'],
            res['medium-track-count'], res['date'], res['ext:score']))
        selector += 1
示例#35
0
 def testSearchRelease(self):
     musicbrainzngs.search_releases("Affordable Pop Music")
     self.assertEqual("http://musicbrainz.org/ws/2/release/?query=Affordable+Pop+Music", self.opener.get_url())
示例#36
0
 def searchByBarcode(self, barcode):
     return mb.search_releases(barcode=barcode)
# zum Initialisieren der API
musicbrainzngs.set_useragent("radioscrape", "0.1", contact=None)
# Doku: https://python-musicbrainzngs.readthedocs.io/en/v0.6/api/
# Wir brauchen das Modul von Musicbrainzngs:
# pip install musicbrainzngs

# Datenbankoperationen
connection = sqlite3.connect('db.sqlite3')
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
sql = "SELECT * FROM bayern3"
bayern3 = cursor.execute(sql).fetchall()
for eintrag in bayern3[10000:]:
    try:
        # Jetzt wird geschaut, welche Daten MB für uns zu diesem Song parat hält
        result = musicbrainzngs.search_releases(artist=eintrag['interpret'],
                                                release=eintrag['titel'])
        release = result['release-list'][0]
        #print(release)

        # MB liefert ein dict zurück, das ich jetzt außeinanderpflüge und sortiere
        mb_score = int(release['ext:score'])
        mb_id = release['id']
        mb_interpret = release['artist-credit'][0]['artist']['name']
        mb_titel = release['title']
        mb_jahr = release['date']
        #plattenlabel=release['label-info-list'][0]['label']['name']
        mb_land = release['release-event-list'][0]['area']['name']

        print('Score: ', mb_score)
        print('ID: ', mb_id)
        print('Interpret: ', mb_interpret)
示例#38
0
import musicbrainzngs as mb
import numpy as np
import pandas as pd
import time

mb.set_useragent('robothy bottano', '1.0', '*****@*****.**')
reviews = pd.read_csv('fantano_reviews.csv', encoding="ISO-8859-1")

title = reviews['title'][0]
release = mb.search_releases(title)
print(release['release-list'][0])

frame = pd.DataFrame(columns=[
    'id',
    'ext:score',
    'title',
    'status',
    'packaging',
    'text-representation-language',
    'text-representation-script',
    'artist-credit-name',
    'artist-credit-artist-id',
    'artist-credit-artist-name',
    'artist-credit-artist',
    'sort-name',
    'release-group-id',
    'release-group-type',
    'release-group-title',
    'release-group-primary-type',
    'date',
    'country',
def getMetadata(artist, release):
    """ Data from public database Music brainz

        Parameters
        ----------
        artist : str
            Name of artists to search in database

        release : str
            Name of song=release from artist for searching

        Returns
        -------
        dict : information for table, with data about song
    """

    # variable for result of appending data
    finalList = {}

    #set name for search
    musicbrainzngs.set_useragent(
        "python-musicbrainzngs-example",
        "0.1",
        "https://github.com/alastair/python-musicbrainzngs/",
    )

    #wjson = json.loads(ss)
    #jsonnn_tree = objectpath.Tree(wjson)

    # getting data from web
    result = musicbrainzngs.search_releases(artist=artist,
                                            tracks=release,
                                            limit=1)

    # get to json format
    sorted_string = json.dumps(result, indent=4, sort_keys=True)

    #save  fro parsing
    wjson = json.loads(sorted_string)
    jsonnn_tree = objectpath.Tree(wjson['release-list'])

    #iterate for data in strings
    IDval = 0
    for (idx, release) in enumerate(result['release-list']):  #goes once
        if 'date' in release:  #check for existence
            finalList.update({"date": release['date']})
        if 'country' in release:
            finalList.update({"country": release['country']})
        if 'title' in release:
            finalList.update({"title": release['title']})
        if 'packaging' in release:
            finalList.update({"packaging": release['packaging']})
        if 'barcode' in release:
            finalList.update({"barcode": release['barcode']})
        if 'status' in release:
            finalList.update({"status": release['status']})
        if 'id' in release:
            finalList.update({"Release ID": release['id']})
            IDval = release['id']
        for (jdx, items) in enumerate(release):  #iterovanie vo vsetkych
            repre = release[items]
            if 'text-representation' == items:
                if 'language' in (repre):
                    finalList.update({"language": repre['language']})
                if 'script' in (repre):
                    finalList.update({"script": repre['script']})
            if 'artist-credit' == items:
                #print(repre)
                #a = json.dumps(release[items], indent=4, sort_keys=True)
                #print(a)
                try:
                    tree = objectpath.Tree(release[items])
                    ent = tree.execute("$.artist[0]")
                    for x in (ent):
                        keyID = "Artist " + str(x)
                        finalList.update({keyID: ent[x]})
                except Exception:
                    pass

    return finalList
示例#40
0
# Wir brauchen das Modul von Musicbrainzngs:
# pip install musicbrainzngs


# Connection zur Datenbank
db.connect()
songs = db.songs()

for eintrag in songs.laden():
    try:
        # Jetzt wird geschaut, welche Daten MB für uns zu diesem Song parat hält
        interpret = eintrag['interpret']
        titel = eintrag['titel']
        titel = re.sub(r'\([^)]*\)', '', titel) # entfernt Klammer aus dem Titel https://im-coder.com/wie-kann-ich-text-in-klammern-mit-einem-regex-entfernen.html 
        titel = re.sub(r'\[[^)]*\]', '', titel)
        result = musicbrainzngs.search_releases(artist=interpret, release=titel)
        if bool(result['release-list']): # Manchmal ist ein Ergebnis-dict leer, siehe z.B. Interpret: Fibel, Titel: Paynesgrau
            release=result['release-list'][0]
            #print(release)
            
            #for release in result['release-list']:
            
            # MB liefert ein dict zurück, das ich jetzt außeinanderpflüge und sortiere
            mb_score = int(release['ext:score'])
            mb_id = release['id']
            mb_interpret = release['artist-credit'][0]['artist']['name']
            mb_titel = release['title']
            mb_jahr = release['date']
            #
            try:
                mb_label=release['label-info-list'][0]['label']['name']
示例#41
0
文件: mb.py 项目: PDS-2014/headphones
def findRelease(name, limit=1, artist=None):

    with mb_lock:
        releaselist = []
        releaseResults = None

        # additional artist search
        if not artist and ':' in name:
            name, artist = name.rsplit(":",1)

        chars = set('!?*-')
        if any((c in chars) for c in name):
            name = '"'+name+'"'
        if artist and any((c in chars) for c in artist):
            artist = '"'+artist+'"'

        try:
            releaseResults = musicbrainzngs.search_releases(query=name,limit=limit,artist=artist)['release-list']
        except musicbrainzngs.WebServiceError as e: #need to update exceptions
            logger.warn('Attempt to query MusicBrainz for "%s" failed: %s' % (name, str(e)))
            time.sleep(5)

        if not releaseResults:
            return False

        for result in releaseResults:

            title = result['title']
            if 'disambiguation' in result:
                title += ' (' + result['disambiguation'] + ')'

            # Get formats and track counts
            format_dict = OrderedDict()
            formats = ''
            tracks = ''
            if 'medium-list' in result:
                for medium in result['medium-list']:
                    if 'format' in medium:
                        format = medium['format']
                        if format not in format_dict:
                            format_dict[format] = 0
                        format_dict[format] += 1
                    if 'track-count' in medium:
                        if tracks:
                            tracks += ' + '
                        tracks += str(medium['track-count'])
                for format, count in format_dict.items():
                    if formats:
                        formats += ' + '
                    if count > 1:
                        formats += str(count) + 'x'
                    formats += format

            rg_type = ''
            if 'type' in result['release-group']:
                rg_type = result['release-group']['type']
                if rg_type == 'Album' and 'secondary-type-list' in result['release-group']:
                    secondary_type = result['release-group']['secondary-type-list'][0]
                    if secondary_type != rg_type:
                        rg_type = secondary_type

            releaselist.append({
                        'uniquename':        unicode(result['artist-credit'][0]['artist']['name']),
                        'title':             unicode(title),
                        'id':                unicode(result['artist-credit'][0]['artist']['id']),
                        'albumid':           unicode(result['id']),
                        'url':               unicode("http://musicbrainz.org/artist/" + result['artist-credit'][0]['artist']['id']),#probably needs to be changed
                        'albumurl':          unicode("http://musicbrainz.org/release/" + result['id']),#probably needs to be changed
                        'score':             int(result['ext:score']),
                        'date':              unicode(result['date']) if 'date' in result else '',
                        'country':           unicode(result['country']) if 'country' in result else '',
                        'formats':           unicode(formats),
                        'tracks':            unicode(tracks),
                        'rgid':              unicode(result['release-group']['id']),
                        'rgtype':            unicode(rg_type)
                        })
        return releaselist
示例#42
0
from __future__ import unicode_literals
import datetime
import sys
sys.path.append('../mopidy_remote')
from library import RemoteLibrary
import musicbrainzngs

config = {}
config['remote'] = {}
config['remote']['database'] = '/var/lib/mopidy/remote.db'

lib = RemoteplayLibrary(config)
musicbrainzngs.set_useragent('mopidy-headless', '0.0.1')
result = musicbrainzngs.search_releases(release="Dandy in the Underworld",
                                        artist="T. Rex")

import pdb
pdb.set_trace()
res = musicbrainzngs.search_artists(artist='T. Rex')
[(art['name'], art['ext:score']) for art in result['artist-list']
 if int(art['ext:score']) > 30]

result = musicbrainzngs.search_recordings(recording="Crimson Moon",
                                          release="Dandy in the Underworld",
                                          artist="T. Rex")
track = [t for t in result['recording-list'] if int(t['ext:score']) == 100][0]
musicbrainz_id = track['id']

rec = musicbrainzngs.get_recording_by_id(
    '9abfbf0b-ef05-4dfc-9177-17cc42dd3feb', includes=['artists', 'releases'])
track = rec['recording']
示例#43
0
文件: mb.py 项目: somini/quodlibet
def search_releases(query):
    """Returns a list of ReleaseResult or raises MusicBrainzError"""

    musicbrainzngs.set_useragent(app.name, const.VERSION)
    return [Release(r) for r in
            musicbrainzngs.search_releases(query)["release-list"]]
示例#44
0
for i in range(5):
    songNumber.append(r[xx])
    xx += 1

print(songNumber)
musicbrainzngs.set_useragent(
    "LyricsWordCount",
    "1.0",
    "azizn03",
)

artist = input("Enter Artist Name ")

x = musicbrainzngs.search_releases(artist="" + artist,
                                   country="GB",
                                   status="Offical",
                                   format='CD')

for i in range(5):
    xx = x['release-list'][songNumber[n]]['title']
    songslist.append(xx)
    n += 1

n = 0

if i in range(5):
    song = json.dumps(songslist[n])
    request = Request('https://api.lyrics.ovh/v1/' +
                      artist.replace(" ", "%20") + '/' +
                      song.replace(" ", "%20"))
    response_body = urlopen(request).read()  # Returns byte value
示例#45
0
#Also, lowercasing, and maybe select search result from a list
if input in past_reviews['title'].values:
    old_score = past_reviews.query('title == @input')
    try:
        old_score_string = str(old_score['score']).split('\n')[0].split(' ')[4]
        print('Real Anthony has already reviewed this album. He gave it a: ' +
              old_score_string)
        done = True
    except Exception:
        #Go back and update once I support not number scores
        print(
            'Real Anthony has already reviewed this album, but did not assign it a number score.'
        )
        done = True

release = mb.search_releases(input)['release-list'][0]

dict = {}

results = sp.search(q=input, limit=1, type='album')
if results is not None:
    if results['albums']['items']:
        id = results['albums']['items'][0]['id']
    else:
        print('TODO')
        #assign neutral values here
    album = sp.album(id)

    artist_id = album['artists'][0]['href']

    artist = sp.artist(artist_id)
示例#46
0
    # "artist-credit-phrase" is a flat string of the credited artists
    # joined with " + " or whatever is given by the server.
    # You can also work with the "artist-credit" list manually.
    print("{}, by {}".format(rel['title'], rel["artist-credit-phrase"]))
    if 'date' in rel:
        print("Released {} ({})".format(rel['date'], rel['status']))
    print("MusicBrainz ID: {}".format(rel['id']))


if __name__ == '__main__':
    args = sys.argv[1:]
    if len(args) != 2:
        sys.exit("usage: {} ARTIST ALBUM".format(sys.argv[0]))
    artist, album = args

    # Keyword arguments to the "search_*" functions limit keywords to
    # specific fields. The "limit" keyword argument is special (like as
    # "offset", not shown here) and specifies the number of results to
    # return.
    result = musicbrainzngs.search_releases(artist=artist,
                                            release=album,
                                            limit=5)
    # On success, result is a dictionary with a single key:
    # "release-list", which is a list of dictionaries.
    if not result['release-list']:
        sys.exit("no release found")
    for (idx, release) in enumerate(result['release-list']):
        print("match #{}:".format(idx + 1))
        show_release_details(release)
        print()
示例#47
0
import musicbrainzngs
import pprint
import sqlite3
import ClaseDisco
import BDMusic
musicbrainzngs.set_useragent('musicbrainzngs', '2.0')

#r = musicbrainzngs.search_artists(query='area.name:Los Angeles',limit=5)

r = musicbrainzngs.search_releases(type="group",
                                   country='US',
                                   tag=['rock', 'metal'],
                                   limit=100)

for discos in r['release-list']:

    if 'status' in discos:
        stat = discos['status']

    else:
        stat = 'Unofficial'

    disc = ClaseDisco.Disc(id=discos['artist-credit'][0]['artist']['id'],
                           name=discos['artist-credit'][0]['artist']['name'],
                           country=discos['country'],
                           date=discos['date'],
                           status=stat)
    #pprint.pprint(discos['artist-credit'][0]['artist']['id'])
    #pprint.pprint(discos['artist-credit'][0]['artist']['name'])
    #pprint.pprint(discos['country'])
    #pprint.pprint(discos['date'])
示例#48
0
    )
    result = api.searach_Artist_in_Area("Los Angeles", "us", ['rock', 'metal'],
                                        100)
    artists = api.resultToArtistObj(result)
    print("\nobtenido, Limpiando base de datos.. <<<<<<<<<< \n ")
    bdd.cur.execute("DELETE FROM disk;")
    bdd.cur.execute("DELETE FROM artist;")
    bdd.con.commit()
    print("\nLimpia y almacenando.. <<<<<<<<<< \n")
    bdd.storeArtist(artists)
    print("\nAlmacenados <<<<<<<<<< \n")
    print("\nobteniendo de la base de datos e imprimiendo... <<<<<<<<<< \n")
    print(bdd.printBDD(bdd.getArtistFromDB()))
    print(
        "\nobteniendo (5) discos para cada artista (solo de eu) ... <<<<<<<<<< \n"
    )
    diskera = []
    for disks in artists:
        diskera.append(
            musicbrainzngs.search_releases(artist=disks.name,
                                           country='us',
                                           limit=5))
    print("\nobtenida, imprimiendo ... <<<<<<<<<< \n")
    disks = api.resultToDiscObj(diskera)
    print("\nguardando en base de datos ... <<<<<<<<<< \n")
    bdd.storeDisk(disks)
    print("\n>Almacenado, imprimiendo ... <<<<<<<<<< \n")
    bdd.getDiskFromDB()
    print(bdd.printBDD(bdd.getDiskFromDB()))
    print("\n>Fin ejercicio 1 ... <<<<<<<<<< \n")
示例#49
0
 def searach_Disc_in_Area_by_Artist(self, artist, country,
                                    limit):  #tag=['rock','metal']
     result = musicbrainzngs.search_releases(artist=artist,
                                             country=country,
                                             limit=limit)
     return result