• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python musicbrainzngs.search_recordings函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中musicbrainzngs.search_recordings函数的典型用法代码示例。如果您正苦于以下问题:Python search_recordings函数的具体用法?Python search_recordings怎么用?Python search_recordings使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了search_recordings函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_search_results

	def get_search_results(old_album, old_title, old_artist, old_date, old_track_number):
		results = musicbrainzngs.search_recordings(artist = old_artist, recording = old_title, release = old_album, tnum = old_track_number, limit = 5)

		"""this sequence of if statements is designed to query the database using incomplete parameters.
		This is useful in the event that some of the pre-existing tag information is incorrect"""
		if not results['recording-list']:
			results = musicbrainzngs.search_recordings(recording = old_title, release = old_album, limit = 5)
		if not results['recording-list']:
			results = musicbrainzngs.search_recordings(artist = old_artist, recording = old_title, limit = 5)
		if not results['recording-list']: #TODO: Search by duration
			results = musicbrainzngs.search_recordings(recording = old_title, limit = 5)
		
		return results['recording-list']
开发者ID:victorakabutu,项目名称:Supertagger,代码行数:13,代码来源:mp3_tagger.py


示例2: search_mb

def search_mb():
    musicbrainzngs.set_useragent('music-downloader', '0.1')
    criteria = {}
    if len(query_comps) > 1:
        criteria = {'artist': clear_comps[0], 'recording': clear_comps[1]}
    try:
        if criteria:
            recordings = musicbrainzngs.search_recordings(limit=10, **criteria)
        else:
            recordings = musicbrainzngs.search_recordings(limit=10, query=clear_query)
    except Exception as e:
        print "Failure: Something went wrong"
        sys.exit()
    for recording in recordings['recording-list']:
        yield get_mb_info(recording)
开发者ID:yenbekbay,项目名称:ion-downloader,代码行数:15,代码来源:downloader.py


示例3: handle_data

def handle_data( dict ) :
    if verbose:
            print (u"{} in {} by {}".format(dict['song'], dict['album'], dict['artist'] ) )
    
    result = m.search_recordings(artist = dict['artist'], recording=dict['song'], country='US', limit=15)
    
    lowestDate = 9999
    bestAlbum = dict['album']
    bestArtist = dict['artist']
    
    for (idx, release) in enumerate(result['recording-list']):
        (newsong, newartist, newalbum, newdate) = getinfo( release, dict['song'], dict['album'], dict['artist']  )
        if (lowestDate > newdate):
            lowestDate = newdate
            bestAlbum = newalbum
            bestArtist = newartist
            
        if verbose:
            print(u"     {} in {} by {}  on {}".format( newsong, newalbum, newartist, newdate) ) 

    if verbose:
            print()
    if verbose:
            print(u"----{} in {} by {}  on {}".format( dict['song'], bestAlbum, bestArtist, lowestDate) ) 
    return (dict['song'], bestAlbum, bestArtist, lowestDate)
开发者ID:ClarkGoble,项目名称:Scripts,代码行数:25,代码来源:fixalbum.py


示例4: search_rec_with_artist

def search_rec_with_artist(queryRecName, artist, mbSet):
    queryRecNameQuotes = '"%s"' % queryRecName
    
    artistMBID = artist['id']
    
    offset = 0
    limit = 100
    while True:
        result = mb.search_recordings(queryRecNameQuotes, arid=artistMBID, offset=offset, limit=limit)
        recs = result['recording-list']
    
        for r in recs:
            if not match( r['title'], queryRecName) :
                break
            
            # match recordingMBIDs in ABrainz
            if isRecordingInAbrainz(r, mbSet ):
                print "found recording with title {} with artist {} and with rec MBID {} in acoustic brainz".format(r["title"].encode('utf-8','replace'), artist["name"].encode('utf-8','replace'), r['id'].encode('utf-8','replace') )
                return r

        if offset > 200:
            print "Looked for this song in the 1000 first results but didn't find it, stopping"
            break
    
        offset += limit
    return None
开发者ID:georgid,项目名称:musicBrainzTools,代码行数:26,代码来源:Echonest2Abrainz.py


示例5: lookup_song

def lookup_song(artist, title, format_string, sql):
    musicbrainzngs.set_useragent('Song-Looker-Upper', '0.1', 'http://www.kbarnes3.com')

    query = '"{0}" AND artist:"{1}" AND status:official'.format(title, artist)

    result = musicbrainzngs.search_recordings(query)

    if len(result['recording-list']) < 1:
        print('No songs found for query ' + query, file=sys.stderr)
        return

    recording = result['recording-list'][0]

    try:
        artist = recording['artist-credit'][0]['artist']['name']
        artist = artist.replace(u'\u2019', "'")
        title = recording['title']
        title = title.replace(u'\u2019', "'")

        if sql:
            artist = artist.replace("'", "''")
            title = title.replace("'", "''")

        length = recording['release-list'][0]['medium-list'][1]['track-list'][0]['length']
        duration = int(int(length) / 1000)

        output = format_string.format(artist=artist, title=title, duration=duration)
        print(output, end='')
    except Exception as ex:
        print('Error handling recording: ' + str(recording), file=sys.stderr)
        print(ex.message, file=sys.stderr)
        raise RecordParseException(ex.message)
开发者ID:kbarnes3,项目名称:song-looker-upper,代码行数:32,代码来源:song-looker-upper.py


示例6: assign_songs

	def assign_songs(self, cleaned_tweets):
		print "Matching songs to tweets"
		cleaner_tweets = []
		tweets_used = 0
		for cleaned_tweet in cleaned_tweets:
			if " by " in cleaned_tweet['text']:
				split_text = cleaned_tweet['text'].split(' by ')
				artists_list = mbz.search_artists(split_text[0])
				try:
					mbID = artists_list['artist-list'][0]['id']
					works = mbz.search_recordings(query=split_text[0],
															arid=mbID)
					tweet = dict()	
					tweet['song'] = works['recording-list'][0]['title']
					tweet['text'] = cleaned_tweet['text']
					tweet['artist'] = artists_list['artist-list'][0]['name']
					tweet['musicbrainzID'] = works['recording-list'][0]['id']
					tweet['userID'] = cleaned_tweet['userID']
					cleaner_tweets.append(tweet)
					tweets_used += 1

				except (UnicodeEncodeError, IndexError):
					print "Unable to find song/artist"
		
		print "Tweets used: %s" % (tweets_used)
		return cleaner_tweets
开发者ID:zcarciu,项目名称:Python-Portfolio,代码行数:26,代码来源:MusicRecommender.py


示例7: get_recording_date

def get_recording_date(artist, album, title):

    t = "artist = {}; album = {} [not used in search], title = {} [in get_recording_date]".format(artist, album, title)
    print t.encode('ascii', 'ignore')
    
    try:
        result = musicbrainzngs.search_recordings(artist=artist, recording=title, limit=40, offset=None, strict=False)
    except:
        return "No date exception (search_recordings)"
    
    recording_list = result.get('recording-list')
    
    if recording_list is None:
        return "No date (search of musicbrainzngs did not produce a recording_list)"
    
    dates = []
    for d in recording_list:
        if int(d['ext:score']) > 98 and 'release-list' in d:
            rel_dict = d['release-list'][0] # it's a list but seems to have one element and that's a dictionary
            date = rel_dict.get('date', '9999')[0:4]
            title = rel_dict.get('title','No title')

            if rel_dict.get('artist-credit-phrase') == 'Various Artists':  #possibly could also use status:promotion
                dates.append((date,title,'z'))
            else:
                dates.append((date,title,'a'))
                
    if dates:
        dates.sort(key=itemgetter(0,2)) # idea is to put albums by the artist ahead of albums by various artists
        return u"{} - {}".format(dates[0][0], dates[0][1])   
    else:
        return '' 
开发者ID:slzatz,项目名称:sonos-companion,代码行数:32,代码来源:display_artists_instagram_dynamodb.py


示例8: fetch_recording

def fetch_recording(artist, title, **kwarg):
    """fetch recording from musicBrainz
    """
    result = musicbrainzngs.search_recordings(query='', limit=10, offset=None, strict=False, artist = artist, release = title)
    seq2 =' '.join([title, artist])
    high_score = 0
    idx = 0
    for i in range(0,10):
        seq1 = ' '.join([result['recording-list'][i]['title'], result['recording-list'][i]['artist-credit-phrase']])
        similarity_score = similar(seq1,seq2)
        if similarity_score > high_score and 'instrumental' not in seq1 and (not 'disambiguation' in result['recording-list'][i] or \
        (result['recording-list'][i]['disambiguation'] != 'music video')):
            high_score = similarity_score
            idx = i
            '''print similarity_score
            print seq1
            print seq2'''
    #print idx
    recording = {}
    recording['match_score'] = high_score
    if 'length' in result['recording-list'][idx]:
        recording['recording_length'] = result['recording-list'][idx]['length']
    else:
        recording['recording_length'] = -1
    recording['recording_mbid'] = result['recording-list'][idx]['id']
    recording['artist_mbid'] = result['recording-list'][idx]['artist-credit'][0]['artist']['id']
    recording['release_date'] = result['recording-list'][idx]['release-list'][0]['date']
    recording['release_mbid'] = result['recording-list'][idx]['release-list'][0]['id']
    if 'artist-credit-phrase' in result['recording-list'][idx]:
        recording['mb_artist'] = result['recording-list'][idx]['artist-credit-phrase']
    else:
        recording['mb_artist'] = ''
    recording['mb_title'] = result['recording-list'][idx]['title']
    #print result['recording-list']
    return recording
开发者ID:tonyhong272,项目名称:MusicML,代码行数:35,代码来源:recordingSearch.py


示例9: _find_recordings

def _find_recordings(artist_name, track_name):
	query = QueryBuilderFactory.create("recording")
	Fields = query.get_fields_enum()
	query.put(Fields.NAME, track_name).AND() \
	     .put(Fields.ARTIST, artist_name).AND() \
	     .NOT().put(Fields.SECONDARY_TYPE, "Live").AND() \
	     .put(Fields.STATUS, "Official")
	
	return musicbrainzngs.search_recordings(query=query.build())["recording-list"]
开发者ID:Auzzy,项目名称:personal,代码行数:9,代码来源:main.py


示例10: get_release_date

def get_release_date(artist, album, title):

    try:
        #print "artist = {}; album = {} [not used in search], title = {} [in get_release_date]".format(artist, album, title)
        t = "artist = {}; album = {} [not used in search], title = {} [in get_release_date]".format(artist, album, title)
        print t.encode('ascii', 'ignore')
    except UnicodeEncodeError as e: # should just be .encode('ascii', 'ignore')
        print "Unicode Error", e

    ## commented this out because I think in most circumstances where there is a legit album, there is an accompanying date
    ## (like for a ripped CD, a Rhapsody song, Pandora
    ## In addition, this allows you to display the first album where the song appeared 
    # try:
        # result = musicbrainzngs.search_releases(artist=artist, release=album, limit=20, strict=True)
    # except:
        # return "No date exception (search_releases)"
    
    # #release_list = result['release-list'] # can be missing
    
    # if 'release-list' in result:
            # release_list = result['release-list'] # can be missing
            # dates = [d['date'][0:4] for d in release_list if 'date' in d and int(d['ext:score']) > 90] 
    
            # if dates:
                # dates.sort()
                # return dates[0]  
        
    ### Generally if there was no date provided it's because there is also a bogus album (because it's a collection
    ### and so decided to comment out the above.  We'll see how that works over time.

    try:
        result = musicbrainzngs.search_recordings(artist=artist, recording=title, limit=40, offset=None, strict=False)
    except:
        return "No date exception (search_recordings)"
    
    recording_list = result.get('recording-list')
    
    if recording_list is None:
        return "No date (search of musicbrainzngs did not produce a recording_list)"
    
    dates = []
    for d in recording_list:
        if int(d['ext:score']) > 98 and 'release-list' in d:
            rel_dict = d['release-list'][0] # it's a list but seems to have one element and that's a dictionary
            date = rel_dict.get('date', '9999')[0:4]
            title = rel_dict.get('title','No title')

            if rel_dict.get('artist-credit-phrase') == 'Various Artists':  #possibly could also use status:promotion
                dates.append((date,title,'z'))
            else:
                dates.append((date,title,'a'))
                
    if dates:
        dates.sort(key=itemgetter(0,2)) # idea is to put albums by the artist ahead of albums by various artists
        return u"{} - {}".format(dates[0][0], dates[0][1])   
    else:
        return "?" 
开发者ID:slzatz,项目名称:sonos-companion,代码行数:57,代码来源:tft_sonos_events.py


示例11: search_mb

 def search_mb(self):
     musicbrainzngs.set_useragent("mudl", "0.1.3")
     criteria = {"artist": self.user_query.bare_artist(), "recording": self.user_query.bare_title()}
     try:
         recordings = musicbrainzngs.search_recordings(limit=10, **criteria)
         for recording in recordings["recording-list"]:
             yield VKDownloader.get_mb_info(recording)
     except Exception as e:
         print(colored.red(u"Something went wrong with the request: {0}".format(e)))
开发者ID:yenbekbay,项目名称:mudl,代码行数:9,代码来源:vk_downloader.py


示例12: searchItems

def searchItems( resourcetype, parameters ):

    luceneQuery = ""
    title = parameters['title']
    if title is not None and title != "":
        luceneQuery = 'recording:"' + title + '" '

    track = parameters['track']
    if track is not None and track != "":
        luceneQuery = 'tnum:' + track + ' '

    artist = parameters['author']
    if artist is not None and artist != "":
        luceneQuery = 'artistname:"' + artist + '" '

    album = parameters['album']
    if album is not None and album != "":
        luceneQuery = 'release:"' + album + '" '

    searchResults = []

    try:
        result = musicbrainzngs.search_recordings(luceneQuery, strict=True)

        if not result['recording-list']:
            WebExtractor.log( 'No results found for: ' + luceneQuery )

        # iterate over all available results
        for recording in result['recording-list']:

            if int(recording['ext:score']) < 50:
                continue

            detailString =""
            albumRelese = recording['release-list'][0]
            if albumRelese is not None:
                detailString = albumRelese['title']

            if 'date' in albumRelese:
                detailString = detailString + ' (' + albumRelese['date'] + ')'

            if 'type' in albumRelese['release-group']:
                detailString = detailString + ' - ' + albumRelese['release-group']['type']

            entryDict = dict (
                              title = recording["artist-credit-phrase"] + ' - ' + recording["title"],
                              details = detailString,
                              url = 'http://musicbrainz.org/recording/' + recording['id'],
                              distanceString = recording["artist-credit-phrase"] + recording["title"]
                             )

            searchResults.append(entryDict)

        WebExtractor.searchResults( searchResults )

    except Exception as err:
        WebExtractor.error("Script error: \n" + str(err))
开发者ID:KDE,项目名称:nepomuk-webminer,代码行数:57,代码来源:musicbrainz.py


示例13: _request

    def _request(query, artist, album=None, track=None):
        results = None
        if track:
            results = musicbrainzngs.search_recordings(query=query)
        elif album:
            results = musicbrainzngs.search_releases(query=query)
        elif artist:
            results = musicbrainzngs.search_artists(query=query)

        return results
开发者ID:FructusCode,项目名称:website,代码行数:10,代码来源:music.py


示例14: Tag

    def Tag(self, song):
        try:
            res = musicbrainzngs.search_recordings(limit = 1, query = song['title'], artist = song['artist'], release = song['album'], qdur = str(song['duration'] * 1000))['recording-list'][0]
            song['number'] = int(res['release-list'][0]['medium-list'][1]['track-list'][0]['number'])
            song['count']  =     res['release-list'][0]['medium-list'][1]['track-count']
            song['score']  =     res['ext:score']
            song['brain']  =     res['id']

        except:
            song['score']  = '0'

        Log("Tag%4s%%" % song['score'], song)
        return song['score'] == '100'
开发者ID:Hundak,项目名称:gominoa-xbmc-addons,代码行数:13,代码来源:pandoki.py


示例15: get_url

def get_url(artist, title):

    if artist is None or title is None:
        return None

    payload = {'func': 'getSong', 'artist': artist, 'song': title, 'fmt': 'realjson'}
    
    try:
         r = requests.get("http://lyrics.wikia.com/api.php", params=payload)
    except:
        url = None
         
    else:        
        q = r.json()
        
        url = q['url'] if 'url' in q else None
        
        if url and url.find("action=edit") != -1: 
            url = None 
            
    if url is not None:
        return url
            
    try:
        z = musicbrainzngs.search_recordings(artist=artist, recording=title, limit=5, offset=None, strict=False)
    except:
        return None
        
    for d in z['recording-list']:

         if int(d['ext:score'])==100:
             new_artist = d['artist-credit-phrase']
             new_title = d['title']
    
    payload = {'func': 'getSong', 'artist': new_artist, 'song': new_title, 'fmt': 'realjson'}
    
    try:
         r = requests.get("http://lyrics.wikia.com/api.php", params=payload)
    except:
        return None
                
    q = r.json()
        
    url = q['url'] if 'url' in q else None
        
    if url and url.find("action=edit") != -1: 
        url = None 
    else:
        print "got song lyrics by using musicbrainz db to figure out correct artist and title"
        
    return url
开发者ID:slzatz,项目名称:sonos-companion,代码行数:51,代码来源:display_artists_instagram_dynamodb.py


示例16: get_remote_data

 def get_remote_data(self):
   """Sends a query corresponding to the title/artist of the track to the
      MusicBrainz server. Careful : each query can take a few seconds."""
   query = ""
   # No query if not data was found.
   if self.localData.title == "":
     return
   # Adding details to the query.
   query += self.localData.title
   if self.localData.artist != "":
     query += ",artist:%s" %self.localData.artist
   # Sending it.
   results = mbngs.search_recordings(query, limit=10)
   return results   
开发者ID:Takido,项目名称:Media-Sniffer,代码行数:14,代码来源:audio_info.py


示例17: match_track

def match_track(artist, title, limit=SEARCH_LIMIT):
    """Searches for a single track and returns an iterable of TrackInfo
    objects. May raise a MusicBrainzAPIError.
    """
    criteria = {"artist": artist.lower(), "recording": title.lower()}

    if not any(criteria.itervalues()):
        return

    try:
        res = musicbrainzngs.search_recordings(limit=limit, **criteria)
    except musicbrainzngs.MusicBrainzError as exc:
        raise MusicBrainzAPIError(exc, "recording search", criteria, traceback.format_exc())
    for recording in res["recording-list"]:
        yield track_info(recording)
开发者ID:jwyant,项目名称:beets,代码行数:15,代码来源:mb.py


示例18: com_mediabrainz_get_recordings

 def com_mediabrainz_get_recordings(self, artist_name=None, release_name=None,
                                    song_name=None, return_limit=5, strict_flag=False):
     """
     # search by artist and song name
     """
     result = musicbrainzngs.search_recordings(artist=artist_name, release=release_name,
                                               recording=song_name, limit=return_limit,
                                               strict=strict_flag)
     if not result['recording-list']:
         common_global.es_inst.com_elastic_index('error', {'stuff': "no recording found"})
         return None
     else:
         for (idx, release) in enumerate(result['recording-list']):
             common_global.es_inst.com_elastic_index('info', {"match #{}:".format(idx + 1)})
             self.show_release_details(release)
         return release['id']
开发者ID:MediaKraken,项目名称:MediaKraken_Deployment,代码行数:16,代码来源:common_metadata_musicbrainz.py


示例19: search_musicbrainz

    def search_musicbrainz(self, song_name):
        info = self.song_info
        if info['title'] == '' or 'Track' in info['title']:
            # Converting song_name into lower case so that we don't have to
            # search for all .MP3 combination like(mp3,mP3,Mp3,MP3)
            song_name = song_name.lower()
            if '.mp3' in song_name:
                pos = song_name.find('.mp3')
            info['title'] = song_name[:pos]

        # Finding song information in DB of music brainz and taking only 1
        # result in response by using limit=1
        self.data = mbz.search_recordings(query=info['title'], limit=1,
                                          artist=info['artist'], release=info['album'],
                                          date=str(info['year']), qdur=str(info['duration'])
                                          )
开发者ID:dimball,项目名称:musicRenamer,代码行数:16,代码来源:renamer.py


示例20: findMatchMB

def findMatchMB(text, scoreComposer, searchString, scoreid):
    results = musicbrainzngs.search_recordings(query=text, limit=5)
    # remove title from search string
    lText = text.lower()
    lSearchString = searchString.lower()
    regex = re.compile(r'\b('+text+r')\b', flags=re.IGNORECASE)
    lSearchString = regex.sub("", lSearchString)
    for i, t in enumerate(results['recording-list']):
        #print t['artist-credit'][0]['artist']['name']
        artist = t['artist-credit'][0]['artist']['name']
        lArtist = artist.lower()
        if lSearchString.find(lArtist) >= 0 or (scoreComposer != "" and lArtist.find(scoreComposer) >= 0) :
              print "MATCH ", scoreid, t['title'] + " - " + artist
              #print "MATCH artist " + t['artists'][0]['uri']
              #print "MATCH track " + t['uri']
              return (scoreid, artist.encode("utf-8"), t['artist-credit'][0]['artist']['uri'], t['title'].encode("utf-8"), t['uri'])
    return None
开发者ID:serkanozer,项目名称:ScoreMatch,代码行数:17,代码来源:findtrack.py



注:本文中的musicbrainzngs.search_recordings函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python musicbrainzngs.search_releases函数代码示例发布时间:2022-05-27
下一篇:
Python musicbrainzngs.search_artists函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap