예제 #1
0
파일: mb.py 프로젝트: PDS-2014/headphones
def findAlbumID(artist=None, album=None):

    results = None
    chars = set('!?*-')

    try:
        if album and artist:
            if any((c in chars) for c in album):
                album = '"'+album+'"'
            if any((c in chars) for c in artist):
                artist = '"'+artist+'"'
            criteria = {'release': album.lower()}
            criteria['artist'] = artist.lower()
        else:
            if any((c in chars) for c in album):
                album = '"'+album+'"'
            criteria = {'release': album.lower()}

        results = musicbrainzngs.search_release_groups(limit=1, **criteria).get('release-group-list')
    except musicbrainzngs.WebServiceError as e:
        logger.warn('Attempt to query MusicBrainz for %s - %s failed (%s)' % (artist, album, str(e)))
        time.sleep(5)

    if not results:
        return False

    if len(results) < 1:
        return False
    rgid = unicode(results[0]['id'])
    return rgid
예제 #2
0
def search(request, query_type, query):
    artist_results = []
    album_results = []

    if query_type == 'artist':
        data = musicbrainzngs.search_artists(query)

        for artist in data['artist-list']:
            artist_results.append(
                [artist['name'], artist['id'],
                 artist.get('disambiguation')])

    elif query_type == 'album':
        data = musicbrainzngs.search_release_groups(query)

        #def get_album_artists(credits):
        #if len(credits) > 1:
        #artists = []
        #for item in credits:
        #	artists.append(item['artist']['name'])

        #return artists
        #else:
        #return credits[0]['artist']['name']

        for album in data['release-group-list']:
            album_results.append([
                album['title'], album['id'],
                album['artist-credit'][0]['artist']['name']
            ])

    return render(request, 'home/home.html', {
        'artist_list': artist_results,
        'album_list': album_results
    })
예제 #3
0
def find_release_group(release_title, artist=None):
    results = musicbrainzngs.search_release_groups(
        release_title, artist=artist, limit=10)['release-group-list']
    table_data = [('Index', 'Artist', 'Title', 'Type')]
    # max_width = table.column_max_width(2)
    for i, r in enumerate(results):
        # title = '\n'.join(wrap(r['title'], max_width))
        table_data.append(
            (i, r['artist-credit-phrase'], r['title'], r.get('type', '?')))

    print(terminaltables.SingleTable(table_data).table)
    while True:
        choice = input(
            "Select the release group (or enter a different query): ")
        try:
            choice = int(choice)
        except ValueError:
            if choice != '':
                return find_release_group(choice)
            continue

        try:
            choice = results[choice]
        except IndexError:
            pass
        else:
            return musicbrainzngs.get_release_group_by_id(
                choice['id'], includes=['tags', 'artist-credits',
                                        'url-rels'])['release-group']
    def get_data(self, data):
        self.result = mbngs.search_release_groups(('%s' % data['Title']), artist=('%s'%data['Artist']), primarytype='album')

        
        x = 0
        while True:
            topResult = self.result['release-group-list'][x]
            topID = topResult['id']
            try:
                pics = mbngs.get_release_group_image_list(topID)
                self.releaseGroupID = topID
                break
            except:
                x += 1
                
        self.url = pics['images'][0]['image']

        self.filename = self.url.split('/')[-1]
        
        # Used for testing / devlopment. Save the cover art to a local directory.
        # urllib.urlretrieve(self.url, self.filename)
        
        self.returnData['Art'] = self.url
        self.releaseResult = mbngs.get_release_group_by_id(self.releaseGroupID)

        
        self.returnData['Date'] = self.releaseResult['release-group']['first-release-date']
        
        print self.returnData
        
        return self.returnData
예제 #5
0
def release_group_id(album_name,
                     artist_name) -> 'release_group_musicbrainz_id':
    """Retrieves the release-groups associated to the album

    Arguments:
        album_name {str} -- 
        artist_name {str} -- 

    Returns:
        str -- release group id
    """
    releases = musicbrainzngs.search_release_groups(
        album_name['value'], strict=True,
        artist=artist_name['value'])['release-group-list']
    filtered_releases = []
    for r in releases:
        try:
            if r['primary-type'] in ['Album', 'Single', 'EP']:
                filtered_releases.append(r)
        except KeyError:
            pass

    if len(filtered_releases) > 0:
        r = filtered_releases[0]['id']
        return {'value': r}
    else:
        logging.getLogger('root.features').warning(
            f"No release-group associate with album {album_name} by {artist_name}"
        )
        return None
예제 #6
0
    def MBRelGroupTitle(self):
        """Search for release groups on musicbrainz by title"""

        title = raw_input('Enter title: ')
        results = musicbrainzngs.search_release_groups(
            releasegroup=title, limit=self.searchResultsLimit)

        if results:
            self.printGroupQueryResults(results)
예제 #7
0
    def MBRelGroupTitle(self):
        """Search for release groups on musicbrainz by title"""

        title = raw_input('Enter title: ')
        results = musicbrainzngs.search_release_groups(
                releasegroup=title,
                limit=self.searchResultsLimit)

        if results:
            self.printGroupQueryResults(results)
예제 #8
0
def find_albums(name, limit=10, artist_id=None,
                wanted_keys=(
                        'name', 'id', 'title', 'country', 'release-group', 'ext:score', 'asin', 'artist-credit',
                        'type')):
    with musicbrainz_lock:
        strict = True if artist_id else False
        params = {'releasegroup': name, 'arid': artist_id}
        search_results = musicbrainzngs.search_release_groups(limit=limit, strict=strict, **params)[
            'release-group-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 get_release_group_by_name(artist_id, album):

    records = dict()
    result = musicbrainzngs.search_release_groups(arid=artist_id,release=album,strict=True)

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

        release_group_name = release_group['title']
        release_group_mbid = release_group['id']
        records.update({release_group_name: release_group_mbid})

    return records
예제 #10
0
def _get_mb_album(query: str) -> dict:
    musicbrainzngs.set_useragent("Kinobot Search", "0.0.1")

    results = musicbrainzngs.search_release_groups(query, limit=1, strict=True)
    try:
        album = results["release-group-list"][0]
    except (KeyError, IndexError):
        raise exceptions.NothingFound from None

    images = musicbrainzngs.get_release_group_image_list(album["id"])
    album.update(images)

    return album
예제 #11
0
def find_musicbrainz_art(artist, album):
    data = musicbrainzngs.search_artists(
        artist=artist,
        type="group",
    )
    # print("Search_artist")
    # print_data(data)
    print("search_release_groups")
    data = musicbrainzngs.search_release_groups(artist + ' ' + album)
    print_data(data)

    # imagebin = musicbrainzngs.get_image_front(id)
    print("")
예제 #12
0
def search_release_groups(query='',
                          artist='',
                          release_group='',
                          limit=None,
                          offset=None):
    """Search for release groups."""
    api_resp = musicbrainzngs.search_release_groups(query=query,
                                                    artistname=artist,
                                                    releasegroup=release_group,
                                                    limit=limit,
                                                    offset=offset)
    return api_resp.get('release-group-count'), api_resp.get(
        'release-group-list')
예제 #13
0
def getMusicBrainzId(artist, album="", track=""):
    albumid = ""
    artistid = ""
    album = album.replace(" (single)","")
    track = track.replace(" (edit)","").replace(" (radio edit)","")
    logMsg("getMusicBrainzId -- artist:  -  %s  - album:  %s  - track:  %s" %(artist,album,track))
    try:
        if not WINDOW.getProperty("SkinHelper.TempDisableMusicBrainz"):
            MBalbum = None
            if artist and album:
                MBalbums = m.search_release_groups(query=single_urlencode(try_encode(album)),limit=1,offset=None, strict=False, artist=single_urlencode(try_encode(artist)))
                if MBalbums and MBalbums.get("release-group-list"): MBalbum = MBalbums.get("release-group-list")[0]
            if not MBalbum and artist and track:
                MBalbums = m.search_recordings(query=single_urlencode(try_encode(track)),limit=1,offset=None, strict=False, artist=single_urlencode(try_encode(artist)))
                if MBalbums and MBalbums.get("recording-list"): MBalbum = MBalbums.get("recording-list")[0]
            if MBalbum:
                albumid = MBalbum.get("id","")
                MBartist = MBalbum.get("artist-credit")[0]
                artistid = MBartist.get("artist").get("id")
    except Exception as e:
        logMsg("MusicBrainz ERROR (servers busy?) - temporary disabling musicbrainz lookups (fallback to theaudiodb)", 0)
        WINDOW.setProperty("SkinHelper.TempDisableMusicBrainz","disable")
    
    #use theaudiodb as fallback
    try:
        if not artistid and artist and album:
            audiodb_url = 'http://www.theaudiodb.com/api/v1/json/193621276b2d731671156g/searchalbum.php'
            params = {'s' : artist, 'a': album}
            response = requests.get(audiodb_url, params=params)
            if response and response.content:
                data = json.loads(response.content.decode('utf-8','replace'))
                if data and data.get("album") and len(data.get("album")) > 0:
                    adbdetails = data["album"][0]
                    albumid = adbdetails.get("strMusicBrainzID")
                    artistid = adbdetails.get("strMusicBrainzArtistID")
        
        elif not artistid and artist and track:
            audiodb_url = 'http://www.theaudiodb.com/api/v1/json/193621276b2d731671156g/searchtrack.php'
            params = {'s' : artist, 't': track}
            response = requests.get(audiodb_url, params=params)
            if response and response.content:
                data = json.loads(response.content.decode('utf-8','replace'))
                if data and data.get("track") and len(data.get("track")) > 0:
                    adbdetails = data["track"][0]
                    albumid = adbdetails.get("strMusicBrainzAlbumID")
                    artistid = adbdetails.get("strMusicBrainzArtistID")
    except Exception as e:
        logMsg("getMusicArtworkByDbId AudioDb lookup failed --> " + str(e), 0)
        return {}
    logMsg("getMusicBrainzId results for artist %s  - artistid:  %s  - albumid:  %s" %(artist,artistid,albumid))
    return (artistid, albumid)
예제 #14
0
 def search(self, album_name):
     resp = mbz.search_release_groups(album_name)
     if rgl := resp.get("release-group-list"):
         resp = []
         for result in rgl:
             resp.append({
                 "album_id":
                 result["id"],
                 "name":
                 result["title"],
                 "artist_name":
                 result["artist-credit"][0]["artist"]["name"]
             })
         return resp
예제 #15
0
def get_musicbrainz_release_group_by_name(artist_id, album):
    records = []
    result = musicbrainzngs.search_release_groups(arid=artist_id,
                                                  release=album,
                                                  strict=True)

    for release_group in result['release-group-list']:
        release_group_name = release_group['title']
        release_group_mbid = release_group['id']
        records.append({
            'release_group_mbid': release_group_mbid,
            'release_group_name': release_group_name
        })

    return records
예제 #16
0
 def _get_release_groups(self, artist_id):
     limit = 100
     offset = 0
     total_pages_to_process = 1
     release_groups_list = []
     try:
         release_groups = musicbrainzngs.search_release_groups(
             arid=artist_id, limit=limit)
         release_groups_list.append(release_groups)
         release_groups_count = int(release_groups['release-group-count'])
         if (release_groups_count > limit):
             total_pages_to_process = math.ceil(
                 release_groups_count / limit) - 1
             for i in range(total_pages_to_process):
                 offset += limit
                 release_groups = musicbrainzngs.search_release_groups(
                     arid=artist_id, limit=limit, offset=offset)
                 release_groups_list.append(release_groups)
     except WebServiceError as exc:
         raise Exception(
             'Something went wrong with the request to musicbrainz: %s' %
             exc)
     else:
         return release_groups_list
예제 #17
0
def find_albums(name,
                limit=10,
                artist_id=None,
                wanted_keys=('name', 'id', 'title', 'country', 'release-group',
                             'ext:score', 'asin', 'artist-credit', 'type')):
    with musicbrainz_lock:
        strict = True if artist_id else False
        params = {'releasegroup': name, 'arid': artist_id}
        search_results = musicbrainzngs.search_release_groups(
            limit=limit, strict=strict, **params)['release-group-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]
예제 #18
0
    def find_art(self, artist, album):
        print("Musicbrainz: find_art:", artist, album)
        """ Search for the album and then identify the best match
            Algorithm for chosing the right album:
            put the search results into a table, search and sort the table accordingly
            1. Highest ex-score, highest fuzzy match of album and artist -weighted towards the alnum
            2. Best match on Artist name
            3. Best match on Album
            4. Album type could be used but some will be compilations??  """
        ALBUM_MATCH_WEIGHT = 1.5
        d = musicbrainzngs.search_release_groups(artist + ' ' + album)

        albums = []
        for k in d['release-group-list']:
            a = {}

            if 'id' in k and 'title' and 'artist-credit' and 'ext:score':
                print("Musicbrainz: find_art: looking for", k['title'])
                if self.coverart_exists(k['id']):
                    a['id'] = k['id']
                else:
                    continue
                a['score'] = int(k['ext:score'])
                a['title'] = k['title']
                a['match'] = ALBUM_MATCH_WEIGHT * fuzz.token_sort_ratio(
                    a['title'], album) + a['score']

            for n in k['artist-credit']:
                if 'name' in n:
                    a['name'] = n['name']
                    a['match'] += fuzz.token_sort_ratio(a['name'], artist)

            print(a)
            albums.append(a)

        best_match = 0
        best_id = ''
        for a in albums:
            if a['match'] > best_match:
                best_id = a['id']

        if best_match > 200:
            imagebin = musicbrainzngs.get_image_front(best_id)
            print("Image successfully found, match score was", best_match)
            return imagebin
        else:
            return None
예제 #19
0
    def find_art(self, artist, album, file=''):
        """ Search for the album and then identify the best match
            Algorithm for chosing the right album:
            put the search results into a table, search and sort the table accordingly
            1. Highest ex-score, highest fuzzy match of album and artist -weighted towards the alnum
            2. Best match on Artist name
            3. Best match on Album
            4. Album type could be used but some will be compilations??  """

        d = musicbrainzngs.search_release_groups(artist + ' ' + album)
        # print("Musicbrainz: find_art: for %30s/%s, releases %s" % (artist, album,  len(d['release-group-list'])))

        albums = []
        for k in d['release-group-list']:
            a={}

            if 'id' in k and 'title' and 'artist-credit' and 'ext:score':
                # print("Musicbrainz: find_art: looking for", k['title'])
                uri = self.get_image_uri(k['id'])
                if uri:
                    a['id']     = k['id']
                    a['uri']    = uri
                else:
                    continue
                a['score']  = int(k['ext:score'])
                a['title']  = k['title']
                a['match']  = ALBUM_MATCH_WEIGHT*fuzz.token_sort_ratio(a['title'], album) + a['score']

            for n in k['artist-credit']:
                if 'name' in n:
                    a['name']    = n['name']
                    a['match']  += fuzz.token_sort_ratio(a['name'], artist)

            # print(a)
            albums.append(a)

        Musicbrainz.match = 0
        for a in albums:
            if a['match'] > Musicbrainz.match:
                best = a

        if Musicbrainz.match > MATCH_THRESHOLD:
            # print("Musicbrainz: find_art: Image successfully found, match score was", best_match)
            return best['uri']
        else:
            return False
예제 #20
0
def findArtistbyAlbum(name):

    myDB = db.DBConnection()

    artist = myDB.action(
        'SELECT AlbumTitle from have WHERE ArtistName=? AND AlbumTitle IS NOT NULL ORDER BY RANDOM()',
        [name]).fetchone()

    if not artist:
        return False

    # Probably not neccessary but just want to double check
    if not artist['AlbumTitle']:
        return False

    term = '"' + artist['AlbumTitle'] + '" AND artist:"' + name + '"'

    results = None

    try:
        with mb_lock:
            results = musicbrainzngs.search_release_groups(term).get(
                'release-group-list')
    except musicbrainzngs.WebServiceError as e:
        logger.warn('Attempt to query MusicBrainz for %s failed (%s)' %
                    (name, str(e)))
        mb_lock.snooze(5)

    if not results:
        return False

    artist_dict = {}
    for releaseGroup in results:
        newArtist = releaseGroup['artist-credit'][0]['artist']
        # Only need the artist ID if we're doing an artist+album lookup
        #if 'disambiguation' in newArtist:
        #    uniquename = unicode(newArtist['sort-name'] + " (" + newArtist['disambiguation'] + ")")
        #else:
        #    uniquename = unicode(newArtist['sort-name'])
        #artist_dict['name'] = unicode(newArtist['sort-name'])
        #artist_dict['uniquename'] = uniquename
        artist_dict['id'] = unicode(newArtist['id'])
        #artist_dict['url'] = u'http://musicbrainz.org/artist/' + newArtist['id']
        #artist_dict['score'] = int(releaseGroup['ext:score'])

    return artist_dict
예제 #21
0
    def test_search_release_groups(self):
        musicbrainzngs.search_release_groups("Affordable Pop Music")
        self.assertEqual("http://musicbrainz.org/ws/2/release-group/?query=Affordable+Pop+Music", self.opener.get_url())

        musicbrainzngs.search_release_groups(releasegroup="Affordable Pop Music")
        expected_query = 'releasegroup:(affordable pop music)'
        expected = 'http://musicbrainz.org/ws/2/release-group/?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_release_groups(foo="value")
예제 #22
0
파일: mb.py 프로젝트: bennieb79/headphones
def findArtistbyAlbum(name):

    myDB = db.DBConnection()

    artist = myDB.action('SELECT AlbumTitle from have WHERE ArtistName=? AND AlbumTitle IS NOT NULL ORDER BY RANDOM()', [name]).fetchone()

    if not artist:
        return False

    # Probably not neccessary but just want to double check
    if not artist['AlbumTitle']:
        return False

    term = '"'+artist['AlbumTitle']+'" AND artist:"'+name+'"'

    results = None

    try:
        results = musicbrainzngs.search_release_groups(term).get('release-group-list')
    except musicbrainzngs.WebServiceError as e:
        logger.warn('Attempt to query MusicBrainz for %s failed (%s)' % (name, str(e)))
        time.sleep(5)


    if not results:
        return False

    artist_dict = {}
    for releaseGroup in results:
        newArtist = releaseGroup['artist-credit'][0]['artist']
        # Only need the artist ID if we're doing an artist+album lookup
        #if 'disambiguation' in newArtist:
        #    uniquename = unicode(newArtist['sort-name'] + " (" + newArtist['disambiguation'] + ")")
        #else:
        #    uniquename = unicode(newArtist['sort-name'])
        #artist_dict['name'] = unicode(newArtist['sort-name'])
        #artist_dict['uniquename'] = uniquename
        artist_dict['id'] = unicode(newArtist['id'])
        #artist_dict['url'] = u'http://musicbrainz.org/artist/' + newArtist['id']
        #artist_dict['score'] = int(releaseGroup['ext:score'])



    return artist_dict
예제 #23
0
def fetchAlbumArt(name, artist):
    debug("GET " + name + " " + artist)
    try:
        results = musicbrainzngs.search_release_groups(name,
                                                       limit=3,
                                                       artistname=artist,
                                                       primarytype="album")
        #pp.pprint(results['release-group-list'])
        results = results['release-group-list']
        resultid = results[0]['id']
        debug("ID =  " + resultid)
        imagelist = musicbrainzngs.get_release_group_image_list(resultid)
    except ResponseError:
        debug("No image found.")
        return None
    except NetworkError:
        debug("Cannot connect to MB server")
        return None
    return imagelist['images'][0]['thumbnails']['large']
예제 #24
0
파일: mb.py 프로젝트: noam09/headphones
def findAlbumID(artist=None, album=None):
    results = None

    try:
        if album and artist:
            criteria = {"release": album.lower()}
            criteria["artist"] = artist.lower()
        else:
            criteria = {"release": album.lower()}
        with mb_lock:
            results = musicbrainzngs.search_release_groups(limit=1, **criteria).get("release-group-list")
    except musicbrainzngs.WebServiceError as e:
        logger.warn("Attempt to query MusicBrainz for %s - %s failed (%s)" % (artist, album, str(e)))
        mb_lock.snooze(5)

    if not results:
        return False

    if len(results) < 1:
        return False
    rgid = unicode(results[0]["id"])
    return rgid
예제 #25
0
def set_imports_release_group_ids():

    app = create_app('config')
    musicbrainzngs.set_useragent("Muzlogger", "0.1",
                                 "https://github.com/maxdup/muzlog")

    with app.app_context():
        imports = Import.objects()
        print('--------------------')
        print('settings release ids')
        print('--------------------')
        for imp in imports:
            print(imp.album_title)

            if imp.mbrgid != None:
                print(imp.mbrgid)
                continue

            rgs = musicbrainzngs.search_release_groups(
                query=imp['album_title'])
            imp.mbrgid = rgs['release-group-list'][0]['id']
            print(imp.mbrgid)
            imp.save()
예제 #26
0
def findAlbumID(artist=None, album=None):
    results = None

    try:
        if album and artist:
            criteria = {'release': album.lower()}
            criteria['artist'] = artist.lower()
        else:
            criteria = {'release': album.lower()}
        with mb_lock:
            results = musicbrainzngs.search_release_groups(
                limit=1, **criteria).get('release-group-list')
    except musicbrainzngs.WebServiceError as e:
        logger.warn('Attempt to query MusicBrainz for %s - %s failed (%s)' %
                    (artist, album, str(e)))
        mb_lock.snooze(5)

    if not results:
        return False

    if len(results) < 1:
        return False
    rgid = unicode(results[0]['id'])
    return rgid
예제 #27
0
def search_release_groups(query='', artist='', release_group='', limit=None, offset=None):
    """Search for release groups."""
    api_resp = musicbrainzngs.search_release_groups(query=query, artistname=artist, releasegroup=release_group,
                                                    limit=limit, offset=offset)
    return api_resp.get('release-group-count'), api_resp.get('release-group-list')
 def testSearchReleaseGroup(self):
     musicbrainzngs.search_release_groups("Affordable Pop Music")
     self.assertEqual("http://musicbrainz.org/ws/2/release-group/?query=Affordable+Pop+Music", self.opener.get_url())
예제 #29
0
 def testSearchReleaseGroup(self):
     musicbrainzngs.search_release_groups("Affordable Pop Music")
     self.assertEqual("http://musicbrainz.org/ws/2/release-group/?query=Affordable+Pop+Music", self.opener.get_url())