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())
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
    def test_set_https(self):
        musicbrainzngs.set_hostname("mbmirror.org", use_https=True)

        musicbrainzngs.get_release_by_id(
            "5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b")
        self.assertEqual(
            "https://mbmirror.org/ws/2/release/5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b",
            self.opener.get_url())
Ejemplo n.º 4
0
    def test_set_port(self):
        musicbrainzngs.set_hostname("localhost:8000", use_https=False)

        musicbrainzngs.get_release_by_id(
            "5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b")
        self.assertEqual(
            "http://localhost:8000/ws/2/release/5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b",
            self.opener.get_url())
Ejemplo n.º 5
0
    def test_set_http(self):
        musicbrainzngs.set_hostname("beta.musicbrainz.org")

        musicbrainzngs.get_release_by_id(
            "5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b")
        self.assertEqual(
            "http://beta.musicbrainz.org/ws/2/release/5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b",
            self.opener.get_url())
Ejemplo n.º 6
0
    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"])
Ejemplo n.º 7
0
    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())
Ejemplo n.º 8
0
def get_musicbrainz_release(record_id):
    track_count = 0
    album_length = 0
    medium_types_arr = []

    try:
        release = musicbrainzngs.get_release_by_id(record_id,
                                                   includes=[
                                                       'recordings',
                                                   ])
        release = release['release']
    except:
        release = musicbrainzngs.get_release_by_id(record_id)

    for recording in release['medium-list']:
        try:
            medium_types_arr.append(recording['format'])
        except KeyError:
            pass

        track_count += int(recording['track-count'])
        for track in recording['track-list']:
            try:
                album_length += int(track['track_or_recording_length'])
            except:
                album_length += 0

    try:
        date = release['date']
    except KeyError:
        date = 'unknown'
    try:
        country = release['country']
    except KeyError:
        country = 'unknown'

    medium_types = ",".join(medium_types_arr)
    album_length = album_length / 1000
    release_dict = {
        'date': date,
        'id': release['id'],
        'medium_count': release['medium-count'],
        'medium_type': medium_types,
        'country': country,
        'track_count': track_count,
        'album_length': album_length
    }

    return release_dict
Ejemplo n.º 9
0
    def release_by_id(self, mbid, cuesheet=None):
        """Return a release by MusicBrainz ID, or None.

        If cuesheet is present, return only the medium with a disc ID or TOC
        match. Includes track information.
        """
        release = None
        try:
            response = mb_client.get_release_by_id(mbid,
                                                   includes=[
                                                       'artist-credits',
                                                       'discids',
                                                       'recordings',
                                                       'release-groups',
                                                   ])
            release = response['release']
        except mb_client.ResponseError as e:
            if isinstance(e.cause, HTTPError) and e.cause.code == 404:
                pass  # no matches
            else:
                raise MusicBrainzError from e
        if release is not None:
            if cuesheet is not None:
                disc = MusicBrainzDisc(cuesheet)
            else:
                disc = None
            return _parse_release(release, disc)
        else:
            return None
Ejemplo n.º 10
0
def fetch_release(release_id, refresh=False):
    if not os.path.isfile("{0}.data".format(release_id[0])) or refresh:
        logger.debug("Hard refreshing data for {0}".format(release_id[0]))
        try:
            release = musicbrainzngs.get_release_by_id(
                release_id[0], includes=["artists", "labels"])['release']
        except musicbrainzngs.WebServiceError as exc:
            logger.error("Error fetching data for {0}".format(release_id[0]))
            logger.error(exc)
            logger.info('Shutting down')
            return False

        try:
            with open("{0}.data".format(release_id[0]), "w") as out_file:
                artist = release["artist-credit"][0]["artist"]
                try:
                    label = release["label-info-list"][0]["label"]["name"]
                    catno = release["label-info-list"][0]["catalog-number"]
                except IndexError:
                    label = ''
                    catno = ''

                out_file.writelines('\n'.join([
                    artist["name"], release["title"], release["date"], label,
                    catno, release_id[1], release_id[2]
                ]))
        except EnvironmentError:
            logger.error('Cannot write data for {0} to file'.format(
                release_id[0]))
            logger.info('Shutting down')
            return False
    else:
        logger.debug("Using pre-fetched data for {0}".format(release_id[0]))

    return True
Ejemplo n.º 11
0
def get_release_info(album_title):
    """Return release info given an id."""
    release_id = __search_for_release(album_title)
    release_info = musicbrainzngs.get_release_by_id(
        id=release_id, includes=['tags', 'recordings'])

    return release_info
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
def music_brainz_get_release_tracklist(release_id: str):
    """get release group info by it id
    :param 
        release_group_id (str): release group id from Music Brainz
    :return: 
        (list) a list of tracks (track titles) for the current release (album)
    """
    try:
        release_info = musicbrainzngs.get_release_by_id(
            release_id, includes=['media', 'recordings'])
    except (HTTPError, ResponseError) as e:
        print(f'a response error occurred for {release_id}', e)
        return None
    if not release_info:
        print(f'no release info returned for {release_id}')
        return None
    try:
        tracklist = []
        for album_cd in release_info['release']['medium-list']:
            tracklist += album_cd['track-list']
    except (IndexError, TypeError, KeyError, ValueError) as e:
        print(e, f'could not find tracklist for {release_id}')
        return None
    tracklist = [track_info['recording']['title'] for track_info in tracklist]
    return tracklist
Ejemplo n.º 14
0
def find_release(release_title, artist=None):
    release_group = find_release_group(release_title, artist=artist)

    results = musicbrainzngs.search_releases(
        'rgid:' + release_group['id'])['release-list']

    table_data = [
        ('Index', 'Title', '# Tracks', 'Date', 'CC', 'Label', 'Status',
         'Format'),
    ]

    for i, r in enumerate(results):
        try:
            label = r['label-info-list'][0]['label']['name']
        except KeyError:
            label = '?'
        table_data.append((i, r['title'], r['medium-list'][0]['track-count'],
                           r.get('date', '?'), r.get('country', '?'), label,
                           r.get('status',
                                 '?'), r['medium-list'][0].get('format', '?')))

    print(terminaltables.SingleTable(table_data).table)
    while True:
        choice = input("Select the exact release, if known (Enter to skip): ")
        try:
            choice = results[int(choice)]
        except (IndexError, ValueError):
            if choice == '':
                return None, release_group
        else:
            release = musicbrainzngs.get_release_by_id(
                choice['id'],
                includes=['release-groups', 'media', 'recordings',
                          'url-rels'])['release']
            return release, release_group
Ejemplo n.º 15
0
def gather(artist, title):
    result = musicbrainzngs.search_releases(artist=artist, release=title)
    for item in result['release-list']:
        print artist, title
        print json.dumps(item,
                         sort_keys=True,
                         indent=4,
                         separators=(',', ': '))
        if (re.search(artist,
                      item['artist-credit'][0]['artist']['name'],
                      flags=re.IGNORECASE)
                and re.search(
                    artist, item['artist-credit-phrase'], flags=re.IGNORECASE)
                and re.search(title, item['title'], flags=re.IGNORECASE)
                and re.search('Album', item['release-group']['primary-type'])):
            #if (item['artist-credit'][0]['artist']['name'] == artist and item['title'] == title):
            actual.append(item['id'])
            print actual[0]
            foo = musicbrainzngs.get_release_by_id(
                actual[0], includes=['recordings', 'release-groups'])
        #elif (item['title'] == title):
        #    actual = item['id']
        #    foo = musicbrainzngs.get_release_by_id(actual,includes=['recordings','release-groups'])
    #print "Positions: ",foo['release']['medium-list'][0]['track-list'][-1]['position'], "Tracks: ",foo['release']['medium-list'][0]['track-list'][-1]['number']
    return foo['release']['medium-list'][0]['track-list'][-1]['number']
Ejemplo n.º 16
0
def main():
    m.set_useragent("application", "0.01", "http://example.com")
    print(m.get_artist_by_id("952a4205-023d-4235-897c-6fdb6f58dfaa", []))
    print(m.get_label_by_id("aab2e720-bdd2-4565-afc2-460743585f16"))
    print(m.get_release_by_id("e94757ff-2655-4690-b369-4012beba6114"))
    print(m.get_release_group_by_id("9377d65d-ffd5-35d6-b64d-43f86ef9188d"))
    print(m.get_recording_by_id("cb4d4d70-930c-4d1a-a157-776de18be66a"))
    print(m.get_work_by_id("7e48685c-72dd-3a8b-9274-4777efb2aa75"))

    print(m.get_releases_by_discid("BG.iuI50.qn1DOBAWIk8fUYoeHM-"))
    print(m.get_recordings_by_puid("070359fc-8219-e62b-7bfd-5a01e742b490"))
    print(m.get_recordings_by_isrc("GBAYE9300106"))

    m.auth("", "")
    m.submit_barcodes(
        {"e94757ff-2655-4690-b369-4012beba6114": "9421021463277"})
    m.submit_tags(recording_tags={
        "cb4d4d70-930c-4d1a-a157-776de18be66a": ["these", "are", "my", "tags"]
    })
    m.submit_tags(
        artist_tags={"952a4205-023d-4235-897c-6fdb6f58dfaa": ["NZ", "twee"]})

    m.submit_ratings(
        recording_ratings={"cb4d4d70-930c-4d1a-a157-776de18be66a": 20})
    m.submit_echoprints(
        {"e97f805a-ab48-4c52-855e-07049142113d": "anechoprint1234567"})
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
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
Ejemplo n.º 19
0
def get_release(mbid):
    try:
        rel = musicbrainzngs.get_release_by_id(mbid,
                                               includes=["release-groups"])
        return rel["release"]
    except musicbrainzngs.ResponseError:
        return {}
Ejemplo n.º 20
0
def getReleaseMetadata(release_id, discid=None, country=None, record=False):
    """
    Return a DiscMetadata object based on MusicBrainz Release ID and Disc ID.

    If the disc id is not specified, it will match with any disc that is on
    the release disc-list. Otherwise only returns metadata of one disc in
    release disc-list.

    :param release_id: MusicBrainz Release ID
    :type release_id: str
    :param discid: MusicBrainz Disc ID
    :type discid: str or None
    :param country: the country the release was issued in
    :type country: str or None
    :param record: whether to record to disc as a JSON serialization
    :type record: bool
    :returns: a DiscMetadata object based on MusicBrainz Release ID & Disc ID
    :rtype: `DiscMetadata`
    """
    # to get titles of recordings, we need to query the release with
    # artist-credits

    res = musicbrainzngs.get_release_by_id(
        release_id,
        includes=[
            "artists", "artist-credits", "recordings", "discids", "labels",
            "recording-level-rels", "work-rels", "release-groups",
            "work-level-rels", "artist-rels"
        ])
    _record(record, 'release', release_id, res)
    releaseDetail = res['release']
    formatted = json.dumps(releaseDetail, sort_keys=False, indent=4)
    logger.debug('release %s', formatted)
    return _getMetadata(releaseDetail, discid, country)
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
def get_taggable_information(album_ids):
    """Find the songs, release year, and coverartarchive.org URL of an album
    by its ID.
    """
    album_dict = musicbrainzngs.get_release_by_id(id=album_ids[0],
                                                  includes="recordings")
    image_dict = musicbrainzngs.get_image_list(album_ids[1])
    taggable_information = {}

    taggable_information["year"] = re.sub(r"([0-9]{4})(-[0-9]{2}){2}", r"\1",
                                          album_dict["release"]["date"])

    discs = album_dict["release"]["medium-list"]
    taggable_information["tracks"] = []
    for disc in sorted(discs, key=lambda disc: int(disc["position"])):
        for song in sorted(disc["track-list"],
                           key=lambda song: int(song["position"])):
            if "title" in song:
                title = song["title"]
            else:
                title = song["recording"]["title"]
            taggable_information["tracks"].append(custom_replace_title(title))

    for image in image_dict["images"]:
        if "Front" in image["types"]:
            taggable_information["image_url"] = image["image"]

    return taggable_information
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
def music_brainz_get_release_tracklist_b_sides(release_id: str):
    """extra function: GET ONLY B-SIDES, CD2, etc, skipping CD1 in medium-list
    :param 
        release_group_id (str): release group id from Music Brainz
    :return: 
        (list) a list of tracks (track titles) for the current release (album)
    """
    try:
        release_info = musicbrainzngs.get_release_by_id(
            release_id, includes=['media', 'recordings'])
    except (HTTPError, ResponseError) as e:
        print(f'a response error occurred for {release_id}', e)
        return None
    if not release_info:
        print(f'no release info returned for {release_id}')
        return None
    try:
        tracklist = []
        if len(release_info['release']['medium-list']) > 1:
            for album_cd in release_info['release']['medium-list'][1:]:
                tracklist += album_cd['track-list']
        else:
            print("ONLY 1 CD FOUND")
            return None
    except (IndexError, TypeError, KeyError, ValueError) as e:
        print(e, f'could not find tracklist for {release_id}')
        return None
    tracklist = [track_info['recording']['title'] for track_info in tracklist]
    return tracklist
Ejemplo n.º 25
0
 def get_release_by_id(self, release_id, includes=[]):
     try:
         return musicbrainzngs.get_release_by_id(release_id,
                                                 includes=includes)
     except WebServiceError as err:
         print_error("Couldn't fetch release: %s" % err)
         sys.exit(1)
Ejemplo n.º 26
0
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"))
Ejemplo n.º 27
0
    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
Ejemplo n.º 28
0
def get_release_group_by_release_id(release_id):
    with musicbrainz_lock:
        results = musicbrainzngs.get_release_by_id(release_id,
                                                   includes='release-groups')
        if results:
            return results['release']['release-group']['id']
        return None
Ejemplo n.º 29
0
 def get_release_by_id(self, release_id, includes=[]):
     try:
         return musicbrainzngs.get_release_by_id(release_id,
                                                 includes=includes)
     except WebServiceError as err:
         print_error("Couldn't fetch release: %s" % err)
         sys.exit(1)
Ejemplo n.º 30
0
Archivo: tag.py Proyecto: stassats/mm
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)
Ejemplo n.º 31
0
def music_get_album(album_id: str, locale: str):
    album = musicbrainzngs.get_release_by_id(
        album_id, includes=["artists", "recordings"])["release"]
    album_name: str = album["title"]
    artist = album["artist-credit"][0]["artist"]
    artist_id: str = artist["id"]
    artist_name: str = artist["name"]
    tracks = album["medium-list"][0]["track-list"]

    doc: Document = minidom.Document()
    feed: Element = create_feed(doc, album_name, album_id, request.endpoint)

    if bool(album["cover-art-archive"]["front"]):
        # Add front cover
        image_elem: Element = doc.createElement("image")
        image_id_elem: Element = create_id(doc, album_id)
        image_elem.appendChild(image_id_elem)
        feed.appendChild(image_elem)

    for track in tracks:
        recording = track["recording"]
        track_id: str = recording["id"]
        track_title: str = recording["title"]
        entry: Element = create_entry(doc, track_title, track_id,
                                      f"/v3.2/{locale}/")

        # Create primaryArtist element
        primary_artist_elem: Element = doc.createElement("primaryArtist")
        artist_id_element: Element = doc.createElement("id")
        set_element_value(artist_id_element, artist_id)
        primary_artist_elem.appendChild(artist_id_element)
        artist_name_element: Element = doc.createElement("name")
        set_element_value(artist_name_element, artist_name)
        primary_artist_elem.appendChild(artist_name_element)
        entry.appendChild(primary_artist_elem)

        try:
            length_ms: str = track["track_or_recording_length"]
            # FIXME: Add duration element
            length_elem: Element = doc.createElement("duration")
            set_element_value(length_elem, length_ms)
        except:
            pass
        try:
            track_position: str = track["position"]
            # FIXME: Add index element
            index_elem: Element = doc.createElement("index")
            set_element_value(index_elem, track_position)
        except:
            pass

        feed.appendChild(entry)

    # doc.appendChild(feed)
    xml_str = doc.toprettyxml(indent="\t")
    return Response(xml_str, mimetype=MIME_XML)
Ejemplo n.º 32
0
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'])
Ejemplo n.º 33
0
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'])
Ejemplo n.º 34
0
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"]
Ejemplo n.º 35
0
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"]
Ejemplo n.º 36
0
Archivo: mb.py Proyecto: satlank/smg
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
Ejemplo n.º 37
0
 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)
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;  
Ejemplo n.º 39
0
 def tracks(self):
     if not self._tracks:
         data = brainz.get_release_by_id(self.id, includes='recordings')['release']
         assert(self.name == data['title'])
         tracks = []
         for i in data['medium-list']:
             tracks += i['track-list']
         self._tracks = [BrainzSong(i) for i in tracks]
         for track in self._tracks:
             track.artist = self.artist
             track.album = self.name
     return self._tracks
Ejemplo n.º 40
0
    def release_info(self, release_list):
        ##Need to clean up data list to include only necessary data
        data = [
            'artists', 'labels', 'recordings', 'release-groups', 'media',
            'artist-credits', 'discids', 'isrcs', 'recording-level-rels',
            'work-level-rels', 'annotation', 'aliases', 'area-rels',
            'artist-rels', 'label-rels', 'place-rels', 'recording-rels',
            'release-rels', 'release-group-rels', 'url-rels', 'work-rels'
        ]
        # data = ['artists', 'labels', 'recordings', 'media', 'release-groups', 'release-rels', 'artist-rels']
        image = False
        formats = ''
        release_date = ''
        labels = ''
        release_display_list = []
        ########
        #Shortening Release list because long release lists cause timeout
        #######
        release_list = release_list[0:5]

        for release in release_list:
            album_data = mbz.get_release_by_id(release, includes=data)
            labels = [
                label['label']['name']
                for label in album_data['release']['label-info-list']
            ]
            try:
                formats = [
                    medium['format']
                    for medium in album_data['release']['medium-list']
                ]
            except KeyError:
                pass
            tracks = album_data['release']['medium-list'][0]['track-list']
            if album_data['release']['cover-art-archive']['artwork'] == 'true':
                r = requests.get('{0}/release/{1}'.format(caa, release)).json()
                image = r['images'][0]['image']
            try:
                release_date = datetime.datetime.strptime(
                    album_data['release']['release-group']
                    ['first-release-date'], '%Y-%m-%d').strftime("%B %d, %Y")
            except ValueError:
                release_date = album_data['release']['release-group'][
                    'first-release-date']
            release_display_list.append({
                'image': image,
                'tracks': tracks,
                'labels': labels,
                'formats': formats,
                'release_date': release_date,
                'title': album_data['release']['title']
            })
        return release_display_list
Ejemplo n.º 41
0
 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)
Ejemplo n.º 42
0
def lookup_info(release):
    info = musicbrainzngs.get_release_by_id(
        str(release), includes=['artists', 'artist-credits'])['release']
    title = info.get('title')
    year = int(info['date'][:4]) if 'date' in info else None
    artists = []
    for a in info['artist-credit']:
        if isinstance(a, dict) and 'name' in a['artist']:
            artists.append(a['artist']['name'])
        else:
            print(a)
    return title, year, artists
Ejemplo n.º 43
0
def getAlbumYearFromMusicBrainz(albumMbid):
	global datesAfterYear

	musicbrainzngs.set_useragent("BARRISS_BillboardChartAnalyzer","1","*****@*****.**")
	album = musicbrainzngs.get_release_by_id(albumMbid)
	if 'release' in album and 'date' in album['release']:
		albumYear = album['release']['date'][0:4]
		if int(albumYear) > year:
			datesAfterYear += 1
		return albumYear
	else:
		return 0
Ejemplo n.º 44
0
    def complete_musicbrainz__(self, results):
        
        completed_results = []
        
        i = 0
        
        for r in results:
            
            if i > 3:
                #pass
                break
            
            i+=1
            
            print
            print 'RESULT'
            
            
            releases = []
            
            recording = r['recording']
            for release in recording['release-list']:
                
                #print release['id']
                
                release = musicbrainzngs.get_release_by_id(id=release['id'], includes=['url-rels', 'release-groups'])
                
                #print 'RELEASE!:::::::::::::::::::::::::::::::::::::::::::::::::'
                #print release
                
                relations = []
                
                try:
                    for relation in release['release']['url-relation-list']:
                        #print "Relation: target: %s - url: %s" % (relation['type'], relation['target'])
                        relations.append(relation)
                        
                except Exception, e:
                    #print e
                    pass
                
                release['relations'] = relations
                    
                releases.append(release)
                

            # order releases by date
            releases = self.mb_order_by_releasedate(releases)
            
            r['release-list'] = releases 
            
            completed_results.append(r)
Ejemplo n.º 45
0
def fetch_album_from_id(id):
    """Retrieves an album (aka release) from MusicBrainz, and parses
    the MusicBrainz data to return a dict of relevant information."""

    try:
        release = musicbrainzngs.get_release_by_id(
            id, includes=['artists', 'media', 'recordings',
            'release-groups', 'labels', 'artist-credits', 'aliases'])
        release = release["release"]
    except musicbrainzngs.MusicBrainzError:
        raise

    # These tags aren't hidden behind layers of data structures,
    # and can be fetched without doing copious error checking
    info = {
        "album"         : release.get("title"),
        "albumartist_credit" : \
            release.get("artist-credit-phrase"),
        "album_id"      : release.get("id"),
        "country"       : release.get("country"),
        "date"          : release.get("date"),
        "status"        : release.get("status"),
        "totaldiscs"    : release.get("medium-count")
    }

    # But these all are
    try: artist_info = release["artist-credit"][0]["artist"]
    except KeyError: artist_info = {}

    info["albumartist"] = artist_info.get("name")
    info["albumartist_id"] = artist_info.get("id")
    info["albumartist_sort"] = artist_info.get("sort-name")
        
    try: info["label"] = release["label-info-list"][0]["label"]["name"]
    except KeyError: info["label"] = None

    try: media = release["medium-list"][0]["format"]
    except KeyError: media = None

    releasegroup_info = release.get("release-group", {})
    info["releasegroup_id"] = releasegroup_info.get("id")
    info["originaldate"] = releasegroup_info.get("first-release-date")

    text_info = release.get("text-representation", {})
    info["language"] = text_info.get("language")
    info["script"] = text_info.get("script")
    
    # Produce information about discs and tracks
    medium_list = release.get("medium-list")
    info["contents"] = sort_album_contents(medium_list)

    return info
Ejemplo n.º 46
0
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. May raise a
    MusicBrainzAPIError.
    """
    try:
        res = musicbrainzngs.get_release_by_id(albumid, RELEASE_INCLUDES)
    except musicbrainzngs.ResponseError:
        log.debug("Album ID match failed.")
        return None
    except musicbrainzngs.MusicBrainzError as exc:
        raise MusicBrainzAPIError(exc, "get release by ID", albumid, traceback.format_exc())
    return album_info(res["release"])
Ejemplo n.º 47
0
 def get_performance_credit_for_recording(self, recordingid):
     recording = mb.get_recording_by_id(recordingid, includes=["releases"])
     recording = recording["recording"]
     ret = []
     for release in recording.get("release-list", []):
         relid = release["id"]
         mbrelease = mb.get_release_by_id(relid, includes=["artist-credits", "recordings"])
         mbrelease = mbrelease["release"]
         for medium in mbrelease.get("medium-list", []):
             for track in medium.get("track-list", []):
                 if track["recording"]["id"] == recordingid:
                     ret.append(track["recording"]["artist-credit-phrase"])
     return list(set(ret))
Ejemplo n.º 48
0
    def complete_musicbrainz__(self, results):

        completed_results = []

        i = 0

        for r in results:

            if i > 3:
                #pass
                break

            i += 1

            print
            print 'RESULT'

            releases = []

            recording = r['recording']
            for release in recording['release-list']:

                #print release['id']

                release = musicbrainzngs.get_release_by_id(
                    id=release['id'], includes=['url-rels', 'release-groups'])

                #print 'RELEASE!:::::::::::::::::::::::::::::::::::::::::::::::::'
                #print release

                relations = []

                try:
                    for relation in release['release']['url-relation-list']:
                        #print "Relation: target: %s - url: %s" % (relation['type'], relation['target'])
                        relations.append(relation)

                except Exception, e:
                    #print e
                    pass

                release['relations'] = relations

                releases.append(release)

            # order releases by date
            releases = self.mb_order_by_releasedate(releases)

            r['release-list'] = releases

            completed_results.append(r)
Ejemplo n.º 49
0
 def get_performance_credit_for_recording(self, recordingid):
     recording = mb.get_recording_by_id(recordingid, includes=["releases"])
     recording = recording["recording"]
     ret = []
     for release in recording.get("release-list", []):
         relid = release["id"]
         mbrelease = mb.get_release_by_id(
             relid, includes=["artist-credits", "recordings"])
         mbrelease = mbrelease["release"]
         for medium in mbrelease.get("medium-list", []):
             for track in medium.get("track-list", []):
                 if track["recording"]["id"] == recordingid:
                     ret.append(track["recording"]["artist-credit-phrase"])
     return list(set(ret))
Ejemplo n.º 50
0
    def mb_shit(self, mb_id):
        self.mb = mb_id
        import musicbrainzngs
        musicbrainzngs.set_useragent('a','.1','foo')
        r = musicbrainzngs.get_release_by_id(self.mb, includes=["artists", "recordings"])['release']
        d = {}
        all_tracklist = []
        for disc in r['medium-list']:
            all_tracklist += disc['track-list']

        d['trackCount'], d['artistName'], d['releaseDate'], d['primaryGenreName'], d['collectionPrice'] = len(all_tracklist), r['artist-credit'][0]['artist']['name'], str(r['date'])[0:4] + '-01-01T00:00:00Z', 'MB', None
        d['trackDetails'] = [{'trackTimeMillis': int(rec['recording']['length'])} for rec in all_tracklist]
        self.mb_details = d
        self.title = r['title']
        self.details = [{'artistName': d['artistName'], 'releaseDate': d['releaseDate']}]
Ejemplo n.º 51
0
def get_tracks(evt):
    albumslist = m.get_release_group_by_id(evt.target.get_selected_items()[0]['id'], includes="releases")
    resultList = [] 

    print("=========================")
    print("=========================")
    print(albumslist)
    print("=========================")
    print("=========================")
    tracks = m.get_release_by_id(albumslist['release-group']['release-list'][0]['id'], includes=["artists", "recordings"])
    
    album_id = tracks["release"]["id"]
    for idx, track in enumerate(tracks["release"]["medium-list"][0]["track-list"]):
        resultList.append([track["recording"]["title"], album_id])

    lv = mainwin['trackslist']
    lv.items = resultList
Ejemplo n.º 52
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 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", self.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", self.opener.get_url())

        # more than one include
        musicbrainzngs.get_release_by_id("5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b", includes=["artists", "recordings", "artist-credits"])
        expected = "http://musicbrainz.org/ws/2/release/5e3524ca-b4a1-4e51-9ba5-63ea2de8f49b?inc=artists+recordings+artist-credits"
        self.assertEqual(expected, self.opener.get_url())
Ejemplo n.º 54
0
	def get(self, mb_id):		
		# Lookup the artist and album name from the musicbrainz ID
		infoDict = musicbrainzngs.get_release_by_id(mb_id, ['artists'])
		
		# The main dictionary is for the whole release
		releaseDict = infoDict.get('release', None)
		
		albumName = ""
		artist = ""
		
		# If this dictionary doesn't exist, we won't have anything to show
		if releaseDict == None:
			self.redirect("/")
		
		# Pull out the album name
		albumName = releaseDict.get('title', 'Unknown')
		
		# Now get the list of artists
		artistsDicts = releaseDict.get('artist-credit', None)
		
		if artistsDicts != None:
			
			# There can be a list of artists, so look for each one
			artists = []
			for artistDict in artistsDicts:
				if artistDict == None:
					continue
				
				# Get this specific artist's info
				artistInfo = artistDict.get('artist')
				
				if artistInfo != None:
					# Append on the artist's name 
					artists.append(artistInfo.get('name', ''))
			
			# Join all the artists together
			artist = ", ".join(artists)
		
		# Look up all the reviews with for that particular album by that particular artist		
		reviews = Review.get_review_by_album_artist(albumName, artist)
			
		if reviews != None:
			self.render("albumPage.html", reviews=reviews, album=albumName, artist=artist, user=self.user, mb_id=mb_id)
		else:
			self.redirect("/")
Ejemplo n.º 55
0
def get_release_by_id(id):
    """Get release with the MusicBrainz ID.

    Returns:
        Release object with the following includes: recordings, media.
    """
    key = cache.gen_key(id)
    release = cache.get(key)
    if not release:
        try:
            release = musicbrainzngs.get_release_by_id(id, ['recordings', 'media', 'release-groups']).get('release')
        except ResponseError as e:
            if e.cause.code == 404:
                return None
            else:
                raise InternalServerError(e.cause.msg)
        cache.set(key=key, val=release, time=DEFAULT_CACHE_EXPIRATION)
    return release
Ejemplo n.º 56
0
    def _match_releases(self, result_list):
        """
        determines which releases the items have in common.
        also uses number of tracks to make sure its the same release
        :returns release_id or None
        """
        result_ids = chain.from_iterable([result.release_id for result in result_list if result])
        top_matches = Counter(result_ids).most_common(self.MAX_RELEASES)
        actual_number_of_tracks = len(result_list)

        for release_id, _ in top_matches:
            r = musicbrainzngs.get_release_by_id(release_id, includes='recordings')
            mediums = r['release']['medium-list']
            tracks = sum([medium['track-count'] for medium in mediums])
            if tracks == actual_number_of_tracks:
                return release_id

        return None
Ejemplo n.º 57
0
def album_for_id(releaseid):
    """Fetches an album by its MusicBrainz ID and returns an AlbumInfo
    object or None if the album is not found. May raise a
    MusicBrainzAPIError.
    """
    albumid = _parse_id(releaseid)
    if not albumid:
        log.debug(u'Invalid MBID ({0}).', releaseid)
        return
    try:
        res = musicbrainzngs.get_release_by_id(albumid,
                                               RELEASE_INCLUDES)
    except musicbrainzngs.ResponseError:
        log.debug(u'Album ID match failed.')
        return None
    except musicbrainzngs.MusicBrainzError as exc:
        raise MusicBrainzAPIError(exc, u'get release by ID', albumid,
                                  traceback.format_exc())
    return album_info(res['release'])
Ejemplo n.º 58
0
    def complete_release_meta(self, r, it):
        includes = [
            "artists", "labels", "recordings", "release-groups", "media",
            "artist-credits", "discids", "puids", "isrcs", "artist-rels",
            "label-rels", "recording-rels", "release-rels",
            "release-group-rels", "url-rels", "work-rels",
            "recording-level-rels", "work-level-rels"
        ]
        mb_release = musicbrainzngs.get_release_by_id(
            id=it['mb_release_id'], includes=includes)

        mbr = mb_release['release']

        print '***************************************'

        if 'status' in mbr:
            print mbr['status']

        if 'title' in mbr:
            print mbr['title']

        if 'url-relation-list' in mbr:
            # print mbr['url-relation-list']

            for rel in mbr['url-relation-list']:
                print rel
                if rel['type'] == 'discogs':
                    print 'DISCOGS: %s' % rel['target']

                    try:
                        # pass
                        rel = Relation(content_object=r, url=rel['target'])
                        rel.save()
                    except Exception, e:
                        print 'RELATION EXCEPTION'
                        print e

                    try:
                        discogs_image = discogs_image_by_url(rel['target'])
                        img = filer_extra.url_to_file(discogs_image, r.folder)
                        r.main_image = img
                    except:
                        pass
Ejemplo n.º 59
0
 def get_release_by_id(self, id, includes=[]):
     """Get release with the MusicBrainz ID.
     Available includes: artists, labels, recordings, release-groups, media, artist-credits, discids, isrcs,
     recording-level-rels, work-level-rels, annotation, aliases, area-rels, artist-rels, label-rels, place-rels,
     recording-rels, release-rels, release-group-rels, url-rels, work-rels.
     """
     key = generate_cache_key(id, type='release', source='api', params=includes)
     release = cache.get(key)
     if not release:
         try:
             release = get_release_by_id(id, includes).get('release')
         except ResponseError as e:
             if e.cause.code == 404:
                 raise APIError(code=e.cause.code,
                                desc="Sorry, we could not find a release with that MusicBrainz ID.")
             else:
                 raise APIError(code=e.cause.code, desc=e.cause.msg)
         cache.set(key, release, DEFAULT_CACHE_EXPIRATION)
     return release