예제 #1
0
 def __init__(self):
     super().__init__()
     musicbrainzngs.set_rate_limit()
     musicbrainzngs.set_useragent(BRAINZ_APP, VERSION,
                                  "*****@*****.**")
     musicbrainzngs.auth(plugin_config.get("username"),
                         plugin_config.get("password"))
예제 #2
0
 def __init__(self, username, password):
     self._username = username
     self._password = password
     musicbrainzngs.set_useragent(
         'SetlistPrediction', '0.1',
         'https://github.com/skuill/SetlistPrediction')
     musicbrainzngs.auth(self._username, self._password)
예제 #3
0
 def __init__(self):
     super(MusicBrainzCollectionPlugin, self).__init__()
     config["musicbrainz"]["pass"].redact = True
     musicbrainzngs.auth(config["musicbrainz"]["user"].as_str(), config["musicbrainz"]["pass"].as_str())
     self.config.add({"auto": False})
     if self.config["auto"]:
         self.import_stages = [self.imported]
예제 #4
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"})
예제 #5
0
def main(*argv):
    m.set_useragent("applicatiason", "0.201", "http://recabal.com")
    m.set_hostname("localhost:8080")
    m.auth("vm", "musicbrainz")

    f = open(sys.argv[1], 'r')
    for line in f.xreadlines():

        line = line.strip()
        lifeSpanString = "false,false"

        art_dict = m.search_artists(artist=line,
                                    limit=1,
                                    strict=True,
                                    tag="jazz")

        if art_dict['artist-count'] != 0:
            lifeSpanString = getLifeSpan(art_dict)

        else:
            art_dict = m.search_artists(artist=line, limit=1, strict=True)
            if art_dict['artist-count'] != 0:
                lifeSpanString = getLifeSpan(art_dict)

        print line + "," + lifeSpanString

    f.close()
예제 #6
0
    def configure_musicbrainz(self) -> None:
        """
        Configure the MusicBrainz library global settings using the values
        from this RipperConfig instance.
        """
        interval = 1.0 / self.musicbrainz_rate_limit
        log.info("Setting MusicBrainz ratelimit to interval=%g calls=1",
                 interval)
        mb.set_rate_limit(interval, 1)

        m = USER_AGENT_RE.match(self.musicbrainz_user_agent)
        if not m:
            raise ValueError(
                f"Invalid useragent format: expected app/version "
                f"( email@ domain ): {repr(self.musicbrainz_user_agent)}")
        app = m.group("app")
        ver = m.group("ver")
        contact: Optional[str] = m.group("contact")
        contact = contact if contact else None

        log.info("Setting MusicBrainz user-agent to app=%r ver=%r contact=%r",
                 app, ver, contact)
        mb.set_useragent(app, ver, contact)

        if self.musicbrainz_username and self.musicbrainz_password:
            mb.auth(self.musicbrainz_username, self.musicbrainz_password)
예제 #7
0
 def __init__(self):
     musicbrainzngs.set_useragent(
         "python-musicbrainzngs-example",
         "0.1",
         "https://github.com/alastair/python-musicbrainzngs/",
     )
     musicbrainzngs.auth('baloothebear4', 'meWzuh-katfyn-6qadqu')
예제 #8
0
 def __init__(self):
     self.user = USER_MUSIC
     self.password = PASSWORD_MUSIC
     self.app = 'Apimusic'
     self.version = '0.1'
     self.email = ''
     musicbrainzngs.auth(self.user, self.password)
     musicbrainzngs.set_useragent(self.app, self.version, self.email)
예제 #9
0
    def query(self, disc_id):
        logger.debug('Retrieving disc meta online')

        musicbrainzngs.set_useragent('cdp-sa', '0.0.1')
        musicbrainzngs.auth('', '')

        disc_meta = {'disc_id': disc_id, 'tracks': []}

        try:
            response = musicbrainzngs.get_releases_by_discid(
                disc_id, includes=["artists", "artist-credits", "recordings"])
        except musicbrainzngs.musicbrainz.ResponseError:
            logger.exception('Could not retrieve disc meta from Musicbrainz')
            return None

        if not 'disc' in response.keys(
        ) or not 'release-list' in response['disc'].keys():
            logger.error(
                'Musicbrainz response contains no relevant information')
            return None

        this_release = response['disc']['release-list'][0]
        if self.is_single_artist(this_release['artist-credit']):
            disc_meta['artist'] = this_release['artist-credit-phrase']

        disc_meta['title'] = this_release['title']
        disc_meta['total_cds'] = len(
            list(
                filter(lambda medium: medium['format'] == 'CD',
                       this_release['medium-list'])))

        for medium in this_release['medium-list']:
            for disc in medium['disc-list']:
                if disc['id'] == disc_id:
                    disc_meta['cd'] = int(medium['position'])
                    tracks = medium['track-list']
                    for track in tracks:
                        artist = track['recording']['artist-credit'][0][
                            'artist']['name']
                        disc_meta['tracks'].append({
                            'artist':
                            artist,
                            'title':
                            track['recording']['title'],
                            'duration':
                            (int(track['length']) // 1000) * SAMPLE_RATE
                        })
                    break

        if not disc_meta['tracks']:
            logger.error(
                'Musicbrainz response has no information about the tracks')
            return None

        disc_meta['duration'] = sum(track['duration']
                                    for track in disc_meta['tracks'])

        return disc_meta
예제 #10
0
파일: mbcollection.py 프로젝트: AGSD/beets
 def __init__(self):
     super(MusicBrainzCollectionPlugin, self).__init__()
     musicbrainzngs.auth(
         config['musicbrainz']['user'].get(unicode),
         config['musicbrainz']['pass'].get(unicode),
     )
     self.config.add({'auto': False})
     if self.config['auto']:
         self.import_stages = [self.imported]
예제 #11
0
 def __init__(self):
     super(MusicBrainzCollectionPlugin, self).__init__()
     musicbrainzngs.auth(
         config['musicbrainz']['user'].get(unicode),
         config['musicbrainz']['pass'].get(unicode),
     )
     self.config.add({'auto': False})
     if self.config['auto']:
         self.import_stages = [self.imported]
예제 #12
0
def main():
    if len(sys.argv) != 4:
        sys.exit(__doc__)

    m.auth(sys.argv[2], sys.argv[3])

    mpdclient = connect_to_mpd()
    add_release = partial(add_release_to_playlist, mpdclient)

    map(add_release, get_releases_in_collection(sys.argv[1]))
예제 #13
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_isrc("GBAYE9300106")

    m.auth("", "")
예제 #14
0
 def __init__(self):
     super(MusicBrainzCollectionPlugin, self).__init__()
     config['musicbrainz']['pass'].redact = True
     musicbrainzngs.auth(
         config['musicbrainz']['user'].as_str(),
         config['musicbrainz']['pass'].as_str(),
     )
     self.config.add({
         'auto': False,
         'collection': u'',
     })
     if self.config['auto']:
         self.import_stages = [self.imported]
예제 #15
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_isrc("GBAYE9300106")

	m.auth("", "")
예제 #16
0
 def __init__(self):
     super(MusicBrainzCollectionPlugin, self).__init__()
     config['musicbrainz']['pass'].redact = True
     musicbrainzngs.auth(
         config['musicbrainz']['user'].as_str(),
         config['musicbrainz']['pass'].as_str(),
     )
     self.config.add({
         'auto': False,
         'collection': u'',
         'remove': False,
     })
     if self.config['auto']:
         self.import_stages = [self.imported]
예제 #17
0
 def musicbrainz_connect(self, mb_user, mb_pass, mb_appid):
     # If you plan to submit data, authenticate
     m.auth(mb_user, mb_pass)
     m.set_useragent(mb_appid[0], mb_appid[1])  # 0=version, 1=app
     # If you are connecting to a different server
     # m.set_hostname("beta.musicbrainz.org")
     # m.set_rate_limit(limit_or_interval=1.0, new_requests=1)
     try:  # test request
         m.get_artist_by_id("952a4205-023d-4235-897c-6fdb6f58dfaa", [])
         self.ONLINE = True
         return True
     except WebServiceError as exc:
         log.error("connecting to MusicBrainz: %s" % exc)
         self.ONLINE = False
         return False
예제 #18
0
def setup_creds(user_creds_file):
    """
    Set up credentials for database mining.
    
    params:
    creds_file = str
    """
    # load credentials from "secure" file
    creds = {}
    with open(user_creds_file) as user_creds_file:
        for l in user_creds_file:
            name, val = l.split('=')
            creds[name] = val
    mb.auth(creds['username'], creds['password'])
    app = 'test app'
    version = '0.1'
    mb.set_useragent(app, version)
예제 #19
0
 def __init__(self):
     # self.__tackem_system = TackemSystemRoot('musicbrainz')
     self.__logged_in = False
     if CONFIG["musicbrainz"]["username"].value == "":
         return
     if CONFIG["musicbrainz"]["password"].value == "":
         return
     musicbrainzngs.set_useragent(PROGRAMNAME, PROGRAMVERSION,
                                  PROGRAMGITADDRESS)
     musicbrainzngs.set_hostname(CONFIG["musicbrainz"]["url"].value)
     musicbrainzngs.set_caa_hostname(
         CONFIG["musicbrainz"]["coverarturl"].value)
     if CONFIG["musicbrainz"]["username"].value != "":
         if CONFIG["musicbrainz"]["password"].value != "":
             musicbrainzngs.auth(
                 CONFIG["musicbrainz"]["username"].value,
                 CONFIG["musicbrainz"]["password"].value,
             )
     self.__logged_in = True
예제 #20
0
def tag_file(song_file):

    musicbrainzngs.auth(BRAINZ_USER, BRAINZ_PASS)
    musicbrainzngs.set_useragent("Auto tag script", "0.1", "http://localhost")

    #song = path.join(MP3_DIR, '3.mp3')
    print song_file
    for score, recording_id, title, artist in acoustid.match(
            APIKEY, song_file):
        # Get song data
        result_data = musicbrainzngs.get_recording_by_id(
            recording_id, includes=['artists', 'releases'])
        title = result_data['recording']['title']
        artist = result_data['recording']['artist-credit-phrase']
        print "%s - %s" % (title, artist)

        # Set ID3 tags
        audiofile = eyed3.load(song_file)
        audiofile.tag.artist = unicode(artist)
        audiofile.tag.title = unicode(title)

        # Get Cover Art
        if result_data['recording']['release-count']:
            try:
                imagedata = musicbrainzngs.get_image_front(
                    result_data['recording']['release-list'][0]['id'])
                print audiofile.tag.images.set(
                    eyed3.id3.frames.ImageFrame.FRONT_COVER, imagedata,
                    'image/jpeg')
                cover = open(
                    path.join(
                        COVER_DIR,
                        result_data['recording']['release-list'][0]['title'] +
                        '.jpg'), "w+")
                cover.write(imagedata)
                print "---"
            except musicbrainzngs.musicbrainz.ResponseError:
                pass

        audiofile.tag.save()
예제 #21
0
 def authenticate(self):
     """Sets the password if not set already
     """
     if not self.auth:
         print("")
         if self.username is None:
             printf("Please input your MusicBrainz username (empty=abort): ")
             self.username = user_input()
         if len(self.username) == 0:
             print("(aborted)")
             sys.exit(1)
         password = None
         if keyring is not None and options.keyring and not self.keyring_failed:
             password = keyring.get_password(options.server, self.username)
         if password is None:
             password = getpass.getpass(
                                 "Please input your MusicBrainz password: "******"")
         musicbrainzngs.auth(self.username, password)
         self.auth = True
         self.keyring_failed = False
         if keyring is not None and options.keyring:
             keyring.set_password(options.server, self.username, password)
예제 #22
0
 def authenticate(self):
     """Sets the password if not set already
     """
     if not self.auth:
         print("")
         if self.username is None:
             printf("Please input your MusicBrainz username (empty=abort): ")
             self.username = user_input()
         if len(self.username) == 0:
             print("(aborted)")
             sys.exit(1)
         password = None
         if keyring is not None and options.keyring and not self.keyring_failed:
             password = keyring.get_password(options.server, self.username)
         if password is None:
             password = getpass.getpass(
                                 "Please input your MusicBrainz password: "******"")
         musicbrainzngs.auth(self.username, password)
         self.auth = True
         self.keyring_failed = False
         if keyring is not None and options.keyring:
             keyring.set_password(options.server, self.username, password)
예제 #23
0
def main(*argv):
	m.set_useragent("applicatiason", "0.201", "http://recabal.com")
	m.set_hostname("localhost:8080")
	m.auth("vm", "musicbrainz")
	
	f = open(sys.argv[1],'r')
	for line in f.xreadlines():
		
		line = line.strip();
		lifeSpanString = "false,false"

		art_dict = m.search_artists(artist=line,limit=1,strict=True,tag="jazz")
		
		if art_dict['artist-count']!=0:
			lifeSpanString = getLifeSpan(art_dict)
			
		else:
			art_dict = m.search_artists(artist=line,limit=1,strict=True)
			if art_dict['artist-count']!=0:
				lifeSpanString = getLifeSpan(art_dict)			

		print line+","+lifeSpanString
				
	f.close()
예제 #24
0
def get(trackname, artist):

    # set up user agent and authentication for api calls
    musicbrainzngs.set_useragent("getYears", 1, contact=None)
    musicbrainzngs.auth("ezinberg", "ezinberg")

    dic = musicbrainzngs.search_recordings(trackname)

    recs = dic["recording-list"]

    oldestDate = "9999-01-01"

    for i in range(len(recs)):
        if recs[i]["artist-credit-phrase"] == artist:
            oldestDate = "9999-01-01"

            if recs[i].get("release-list") != None:
                if "date" in recs[i]["release-list"][0]:
                    dateFound = True
                    date = recs[i]["release-list"][0]["date"]
                    if date < oldestDate:
                        oldestDate = date

    return oldestDate
예제 #25
0
def status_view(request):
    bar = 25
    output = ''
    hostname = '192.168.54.101:5000'
    musicbrainzngs.set_hostname(hostname)
    musicbrainzngs.auth("user", "password")
    musicbrainzngs.set_useragent(
        'c3sbrainz',
        '0.1a',
        '*****@*****.**'
        )
    artistid = "952a4205-023d-4235-897c-6fdb6f58dfaa"
    #import pdb
    #pdb.set_trace()
    print(dir(musicbrainzngs))
    #output = dir(musicbrainzngs)
    output = musicbrainzngs.get_artist_by_id(artistid)
    print  musicbrainzngs.get_artist_by_id(artistid)
    return {
        'foo': 'foo',
        'bar': bar,
        'hostname': hostname,
        'output': output
        }
OUTPUTS
bonnarooAliasList.josn = Outputted automatically below. Consists of keys
    corresponding to each band in input file. Values are a list of aliases
    returned from the API GET request. Alias lists are tokenized and
    stripped of stopwords.
"""

import musicbrainzngs as mbrainz
import json
import string
import re
import nltk
from nltk.corpus import stopwords


mbrainz.auth('rosentep','testing') # Omitted for github
mbrainz.set_useragent('Btest/0.0','*****@*****.**') # Omitted for github
# To be used for removing punctuation
regex = re.compile('[%s]' % re.escape(string.punctuation))


################################
def clean_aliases(alias, regex):
    """
    Convert each alias to lowercase, remove punctuation,
    and remove stop words. The output is a list containing
    the remaining words.
    """
    alias = alias.lower().replace(' &amp;', '') # Remove ampersands
    alias = regex.sub('', alias) # Remove punctuation
    alias_words = [w for w in alias.split() if w not in stopwords.words('english')]
예제 #27
0
                     track['name'], int(track['length'] * 1000)))
        f.write('</div></body></html>')


def save_processing(mb_release):
    if mb_release['processed'] is None:
        db.execute("INSERT INTO bot_isrc_spotify (release) VALUES (%s)",
                   (mb_release['gid']))
    else:
        db.execute(
            "UPDATE bot_isrc_spotify SET processed = now() WHERE release = %s",
            (mb_release['gid']))


sws = SpotifyWebService()
musicbrainzngs.auth(cfg.MB_USERNAME, cfg.MB_PASSWORD)

for release in db.execute(query_releases_wo_isrcs):

    mb_release = dict(release)

    colored_out(
        bcolors.OKBLUE,
        'Looking up release "%s" https://musicbrainz.org/release/%s' %
        (mb_release['name'], mb_release['gid']))

    sp_albums = sws.search_albums('upc:%s' % mb_release['barcode'])
    if len(sp_albums) != 1:
        if len(sp_albums) == 0:
            out(' * no spotify release found')
        if len(sp_albums) > 1:
예제 #28
0
def mblogin():
    print "Username:",
    user = raw_input()
    passwd = getpass()
    musicbrainzngs.auth(user, passwd)
예제 #29
0
import musicbrainzngs as mb
import requests
import json
from getpass import getpass

this_disc = libdiscid.read(libdiscid.default_device())
mb.set_useragent(app='get-contents', version='0.1')
mb.auth(u=input('Musicbrainz username: '******'artists', 'recordings'])
if release.get('disc'):
   this_release=release['disc']['release-list'][0]
   title = this_release['title']
   artist = this_release['artist-credit'][0]['artist']['name']
 
   if this_release['cover-art-archive']['artwork'] == 'true':
      url = 'http://coverartarchive.org/release/' + this_release['id']
      art = json.loads(requests.get(url, allow_redirects=True).content)
      for image in art['images']:
         if image['front'] == True:
            cover = requests.get(image['image'], 
                                 allow_redirects=True)
            fname = '{0} - {1}.jpg'.format(artist, title)
            print('COVER="{}"'.format(fname))
            f = open(fname, 'wb')
            f.write(cover.content)
            f.close()
            break
 
   print('TITLE="{}"'.format(title))
예제 #30
0
                    names.append(path)
                fullnames.append(os.path.join(path, f))

    if verbose:
        print("> Found " + str(len(names)) + " files.")
    return fullnames, folders, names

fullnames, folders, names = get_filenames_in_dir(dir_name='/Users/meghanasudhindra/Manual_Annotations_Saraga')
mbid_list = []
for path in names:
	MBID_name = os.path.splitext(os.path.basename(path))[0]
	mbid_list.append(MBID_name)
	print MBID_name


musicbrainzngs.auth("meghanasudhindra", "musicbrains123")

musicbrainzngs.set_useragent("Dunya", "0.1")
musicbrainzngs.set_hostname("beta.musicbrainz.org")

MBID_Song = open("MBID_Song.txt", "w")
#recordings = []
recording_id = []
recording_title = []
#artist_id = "4cc5200e-a3f7-4d5d-8b15-9b10a8f9a9a2"
for name_artist in mbid_list:
    result = musicbrainzngs.get_recording_by_id(name_artist)
    print result['recording']['id']
    print result['recording']['title']
    recording_id.append(result['recording']['id'])
    recording_title.append(result['recording']['title'])
예제 #31
0
 def configure(self, config):
     username = ui.config_val(config, 'musicbrainz', 'user', '')
     password = ui.config_val(config, 'musicbrainz', 'pass', '')
     musicbrainzngs.auth(username, password)
예제 #32
0
 def configure(self, config):
     username = ui.config_val(config, 'musicbrainz', 'user', '')
     password = ui.config_val(config, 'musicbrainz', 'pass', '')
     musicbrainzngs.auth(username, password)
예제 #33
0
    parser.add_option('-r',
                      '--remove',
                      metavar="RELEASE-ID",
                      help="remove a release from the collection")
    options, args = parser.parse_args()

    if not args:
        parser.error('no username specified')
    username = args.pop(0)

    # Input the password.
    password = getpass.getpass('Password for {}: '.format(username))

    # Call musicbrainzngs.auth() before making any API calls that
    # require authentication.
    musicbrainzngs.auth(username, password)

    if args:
        # Actions for a specific collction.
        collection_id = args[0]
        if options.add:
            # Add a release to the collection.
            musicbrainzngs.add_releases_to_collection(collection_id,
                                                      [options.add])
        elif options.remove:
            # Remove a release from the collection.
            musicbrainzngs.remove_releases_from_collection(
                collection_id, [options.remove])
        else:
            # Print out the collection's contents.
            show_collection(collection_id)
parser.add_argument('-o',
                    '--output-directory',
                    help='output path for the output files',
                    type=str)
parser.add_argument('-c',
                    '--cover-art',
                    help='will attempt to embed the associated cover art',
                    action='store_true')
args = parser.parse_args()

# Setup MusicBrainz client
mb.set_useragent('Antiquarian Backups', '1.0.0')

# get Username/Password
creds = open('credentials', 'r').read().split('\n')
mb.auth(creds[0], creds[1])

# Select the disc and retrieve the MusicBrainz discid
disc = libdiscid.read(device=u'/dev/sr0')
disc_id = disc.id

# Collect the valuable metadata information from the discid in the MusicBrainz CDDA database
try:
    results = mb.get_releases_by_discid(disc_id,
                                        includes=['artists', 'recordings'])
except mb.musicbrainz.ResponseError as re:
    print(
        'Error retrieving the releases data, check if the Title has a discID on musicbrainz.org'
    )
    sys.exit(1)
# -*- coding: utf-8 -*-
"""
Created on Sun May 25 14:31:41 2014
This routine 

@author: Ethan
"""

import musicbrainzngs as mbrainz

mbrainz.auth('', '')  # Omitted for github
mbrainz.set_useragent('', '')  # Omitted for github

with open('BandList.txt', 'r') as fin:
    with open('MusicBrainzIDList.txt', 'w') as fout:
        for bands in fin:
            bands = bands.rstrip('\n')
            result = mbrainz.search_artists(artist=bands, limit=1)
            for artist in result['artist-list']:
                fout.write(artist['name'].encode('ascii', 'ignore') + ':' +
                           artist['id'].encode('ascii', 'ignore') + '\n')

    fout.close()
fin.close()
예제 #36
0
파일: app.py 프로젝트: scampion/pdfmp3
import musicbrainzngs
from mutagen import File
import shutil
import identicon
import random
from PIL import ImageFont
from PIL import ImageDraw
import re

def sub_dir(path):
    return [os.path.join(path, sub) for sub in os.listdir(path) if os.path.isdir(os.path.join(path, sub))]


login = os.environ.get("MUSICBRAINZ_LOGIN")
pwd = os.environ.get("MUSICBRAINZ_PWD")
musicbrainzngs.auth(login, pwd)
musicbrainzngs.set_useragent("PdfMp3", "0.1", "http://pdfmp3.fr")
rootdir = sys.argv[1]



def search(release_path, ext=None):
    query = os.path.basename(release_path)
    odir = os.path.abspath(release_path)
    if ext:
        odir = os.path.abspath(ext)
        query += " " + os.path.basename(ext)

    print (query, odir)
    jpg_query = "artcover_%s.jpg" % query
    ofile = os.path.join(odir, jpg_query)
# -*- coding: utf-8 -*-
"""
Created on Sun May 25 14:31:41 2014
This routine 

@author: Ethan
"""

import musicbrainzngs as mbrainz

mbrainz.auth("", "")  # Omitted for github
mbrainz.set_useragent("", "")  # Omitted for github


with open("BandList.txt", "r") as fin:
    with open("MusicBrainzIDList.txt", "w") as fout:
        for bands in fin:
            bands = bands.rstrip("\n")
            result = mbrainz.search_artists(artist=bands, limit=1)
            for artist in result["artist-list"]:
                fout.write(
                    artist["name"].encode("ascii", "ignore") + ":" + artist["id"].encode("ascii", "ignore") + "\n"
                )

    fout.close()
fin.close()
예제 #38
0
        f.write('<div style="font-weight:bold">%s</div>' % spotify['artist'])
        for track in spotify['tracks']:
            f.write('<div>%s-%s: %s (%s)</div>' %
                    (track['disc-number'], track['track-number'],
                     track['name'], int(track['length'] * 1000)))
        f.write('</div></body></html>')


def save_processing(mb_release):
    if mb_release['processed'] is None:
        db.execute("INSERT INTO bot_isrc_spotify (release) VALUES (%s)", (mb_release['gid']))
    else:
        db.execute("UPDATE bot_isrc_spotify SET processed = now() WHERE release = %s", (mb_release['gid']))

sws = SpotifyWebService()
musicbrainzngs.auth(cfg.MB_USERNAME, cfg.MB_PASSWORD)

for release in db.execute(query_releases_wo_isrcs):

    mb_release = dict(release)

    colored_out(bcolors.OKBLUE, 'Looking up release "%s" https://musicbrainz.org/release/%s' % (mb_release['name'], mb_release['gid']))

    sp_albums = sws.search_albums('upc:%s' % mb_release['barcode'])
    if len(sp_albums) != 1:
        if len(sp_albums) == 0:
            out(' * no spotify release found')
        if len(sp_albums) > 1:
            out(' * multiple spotify releases found')
        save_processing(mb_release)
        continue
예제 #39
0
import musicbrainzngs as m
from fuzzywuzzy import fuzz
import json
m.auth('ehschutzman', 'password123')
m.set_useragent("CS525App", "1.0", contact='')


def main(s):

    result = m.search_artists(artist=s)
    best_ratio = -1
    name = ''
    artist_id = ''
    for artist in result['artist-list']:
        ratio = fuzz.token_set_ratio(s, artist['name'])
        if ratio > best_ratio:
            best_ratio = ratio
            artist_id = artist['id']
            name = artist['name']
            if ratio == 100:
                break

    if (artist_id == ''):
        print("No artist by name ", s)
        return

    result = m.search_releases(arid=artist_id, limit=15)
    artist = m.get_artist_by_id(artist_id)

    print(json.dumps(artist, sort_keys=True, indent=4))
예제 #40
0
    parser.add_option('-a', '--add', metavar="RELEASE-ID",
                      help="add a release to the collection")
    parser.add_option('-r', '--remove', metavar="RELEASE-ID",
                      help="remove a release from the collection")
    options, args = parser.parse_args()

    if not args:
        parser.error('no username specified')
    username = args.pop(0)

    # Input the password.
    password = getpass.getpass('Password for {}: '.format(username))

    # Call musicbrainzngs.auth() before making any API calls that
    # require authentication.
    musicbrainzngs.auth(username, password)

    if args:
        # Actions for a specific collction.
        collection_id = args[0]
        if options.add:
            # Add a release to the collection.
            musicbrainzngs.add_releases_to_collection(
                collection_id, [options.add]
            )
        elif options.remove:
            # Remove a release from the collection.
            musicbrainzngs.remove_releases_from_collection(
                collection_id, [options.remove]
            )
        else:
예제 #41
0
# Import the module
import musicbrainzngs
import database_mysql
import pymysql

db_host = "localhost"
db_user = "******"
db_password = "******"
db_name = "radioszpieg"

# If you plan to submit data, authenticate
musicbrainzngs.auth("user", "password")

# Tell musicbrainz what your app is, and how to contact you
# (this step is required, as per the webservice access rules
# at http://wiki.musicbrainz.org/XML_Web_Service/Rate_Limiting )
musicbrainzngs.set_useragent("Example music app", "0.1",
                             "http://example.com/music")
musicbrainzngs.set_hostname("beta.musicbrainz.org")

db = pymysql.connect(db_host, db_user, db_password, db_name)
cursor = db.cursor()
zapytanie = "select id from years order by id desc limit 1"
cursor.execute(zapytanie)
result = cursor.fetchone()
il_literacjiroz = result[0]
print(il_literacjiroz)

db = pymysql.connect(db_host, db_user, db_password, db_name)
cursor = db.cursor()
zapytanie = "SELECT id, artist, title FROM lastfm"
예제 #42
0
# generate list of genres expressed in the training data.
import csv
import gzip
import musicbrainzngs

if __name__ == "__main__":
  musicbrainzngs.set_useragent("cs181", "1.0", "*****@*****.**")
  musicbrainzngs.auth("jvh181", "finale1")

  with gzip.open('../data/artists.csv.gz') as artists_fh:
    artists_csv = csv.reader(artists_fh, delimiter=',', quotechar='"')
    genres = {}
    next(artists_csv, None)
    for row in artists_csv:
      artist_id = row[0]
      artist_name = row[1]

      print artist_id

      result = musicbrainzngs.get_artist_by_id(artist_id, includes=["tags", "user-tags"])
      if 'tag-list' in result['artist']:
        for tag in result['artist']['tag-list']:
          if not tag['name'] in genres:
            genres[tag['name']] = {}
      else:
        print "tag-list not found in artist {0}".format(result['artist']['name'])

    with open('genre_list.txt', 'w') as results:
      results.write(','.join(genres.keys()))
예제 #43
0
 def __init__(self, user, password, limit):
     musicbrainzngs.auth(user, password)
     musicbrainzngs.set_useragent('Mutagenerate',
                                  '.'.join(map(str,
                                               mutagenerate_version)), user)
     self.limit = limit
예제 #44
0
#====================================================================
#>>>>>>>>>>>>>>>>>>>>>>>>>>>[ LOG IN ]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#====================================================================

with open('./.client_secret.json', 'r') as f:
    jsondata = json.loads(f.read())
    user_name = jsondata['user_name']
    user_pass = jsondata['user_pass']
    app_name = jsondata['app_name']
    app_version = jsondata['app_version']
    app_url = jsondata['app_url']
    host_url = jsondata['host_url']

# Login
mb.auth(user_name, user_pass)

# Set up an app
mb.set_useragent(app_name, app_version, app_url)

# Sign a host engine to search from
mb.set_hostname(host_url)

#====================================================================
#>>>>>>>>>>>>>>>>>>>>>>>[ SEARCH API ]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#====================================================================

# -----------[ Get By ID ]------------------

# Get an artist
id = 'e86ab653-bec8-46f3-b4b6-a1a866919ef6'
예제 #45
0
##############################################################################
#  _           _    __           _   _ _
# | |         | |  / _|         | | | (_)
# | | __ _ ___| |_| |_ _ __ ___ | | | |_ ____
# | |/ _` / __| __|  _| '_ ` _ \| | | | |_  /
# | | (_| \__ \ |_| | | | | | | \ \_/ / |/ /
# |_|\__,_|___/\__|_| |_| |_| |_|\___/|_/___|
#
# ----------------------------------------------------------------------------
# Musicbrainz parser for places and genres
##############################################################################
import aux
import keys
import setup as stp
import pandas as pd
import musicbrainzngs as mb

print('* Downloading data from MusicBrainz')
# Logging in
mb.auth(keys.MB_USR, keys.MB_PSW)
mb.set_useragent(keys.MB_NM, keys.MB_V, keys.MB_URL)
# Read artists list and write CSV and parse musicbrainz to file
data = pd.read_csv(stp.DATA_PATH + stp.USR + '_cln.csv', parse_dates=[3])
aux.parseFromMusicbrainz(data)
예제 #46
0
 def __init__(self):
     super(MusicBrainzCollectionPlugin, self).__init__()
     musicbrainzngs.auth(
         config['musicbrainz']['user'].get(unicode),
         config['musicbrainz']['pass'].get(unicode),
     )
예제 #47
0
 def changed(entry, key):
     if entry.get_property('sensitive'):
         plugin_config.set(key, entry.get_text())
         musicbrainzngs.auth(plugin_config.get("username"),
                             plugin_config.get("password"))
예제 #48
0
import random
from PIL import ImageFont
from PIL import ImageDraw
import re


def sub_dir(path):
    return [
        os.path.join(path, sub) for sub in os.listdir(path)
        if os.path.isdir(os.path.join(path, sub))
    ]


login = os.environ.get("MUSICBRAINZ_LOGIN")
pwd = os.environ.get("MUSICBRAINZ_PWD")
musicbrainzngs.auth(login, pwd)
musicbrainzngs.set_useragent("PdfMp3", "0.1", "http://pdfmp3.fr")
rootdir = sys.argv[1]


def search(release_path, ext=None):
    query = os.path.basename(release_path)
    odir = os.path.abspath(release_path)
    if ext:
        odir = os.path.abspath(ext)
        query += " " + os.path.basename(ext)

    print(query, odir)
    jpg_query = "artcover_%s.jpg" % query
    ofile = os.path.join(odir, jpg_query)
    if os.path.exists(ofile):
예제 #49
0
def main():
    parser = optparse.OptionParser()
    parser.add_option("-u", "--user", type=str, help="Username")
    parser.add_option("-p", "--password", type=str, help="Password")
    parser.add_option("-d", "--device", type=str,
            default=discid.get_default_device(),
            help="Device name, the default is %s" % discid.get_default_device())
    (args, options) = parser.parse_args()

    if not args.user:
        exit("No username given")

    if not args.password:
        password = getpass.getpass()
    else:
        password = args.password

    try:
        disc = discid.read(args.device)
    except discid.DiscError:
        exit("No discid could be calculated")

    musicbrainzngs.auth(args.user, password)
    musicbrainzngs.set_useragent("isrcsubmit-cdrdao", "0.2", "Mineo@Freenode")

    results = musicbrainzngs.get_releases_by_discid(
            disc.id, includes=["recordings", "isrcs",
            "artist-credits"])["disc"]["release-list"]

    if len(results) == 0:
        print "The disc is not in the database"
        print "Please submit it with: %s" % disc.submission_url
        exit(1)
    elif len(results) > 1:
        print "This Disc ID is ambiguous:"
        for i, release in enumerate(results):
            print str(i)+":", release["artist-credit-phrase"]
            print "-", release["title"]
            print release["id"]
        num = -1
        while True:
            try:
                num =  raw_input("Which one do you want? [0-%d] " % i)
                release = results[int(num)]
            except (IndexError, ValueError):
                continue
            break
    else:
        release = results[0]

    print 'Artist: %s' % release["artist-credit-phrase"]
    print 'Release: %s' % release["title"]

    real_medium = None
    for medium in release["medium-list"]:
        for mdisc in medium["disc-list"]:
            print mdisc
            if mdisc["id"] == disc.id:
                real_medium = medium
                break

    filename = "/tmp/cdrdao-%s.toc" % datetime.now()
    try:
        proc = subprocess.Popen(["cdrdao", "read-toc", "--fast-toc", "--device",
                args.device, "-v", "0", filename], stderr=subprocess.PIPE,
                stdout=subprocess.PIPE)
        proc.wait()
    except Exception, e:
        exit("Exception while calling cdrdao: %s" % str(e))