def from_file(file_name: str): ''' Construct a Track object from a file. ''' path = os.path.join(constant.FILE_PREFIX, file_name) extension = filetype.guess_extension(path) duration, fingerprint = aid.fingerprint_file(path) file_hash = hash_file(path) # Use AcoustID json_resp = aid.lookup(constant.API_KEY, fingerprint, duration) matches = aid.parse_lookup_result(json_resp) try: # Ignore score and recording_id _, _, title, artist = next(matches) except StopIteration: title = 'Track ' + file_hash[:constant.HASH_LEN] artist = 'Unknown' return Track(title, artist, duration, file_hash, fingerprint, extension, path=file_name, local=True)
def match(string): API_KEY = 'HMU8Btr6' #filename1 = 'song.mp3' dur, fingp = acoustid.fingerprint_file(string) commentText = "" try: #results = acoustid.match(API_KEY, filename) results1 = acoustid.lookup(API_KEY, fingp, dur) results = acoustid.parse_lookup_result(results1) except acoustid.NoBackendError: print("chromaprint library/tool not found", file=sys.stderr) sys.exit(1) except acoustid.FingerprintGenerationError: print("fingerprint could not be calculated", file=sys.stderr) sys.exit(1) except acoustid.WebServiceError as exc: print("web service request failed:", exc.message, file=sys.stderr) sys.exit(1) first = True for score, rid, title, artist in results: if first: first = False else: commentText += "\n" commentText += '%s - %s \n' % (artist, title) #commentText += 'http://musicbrainz.org/recording/%s \n'% rid #commentText += 'Score: %i%% \n'% (int(score * 100)) return (commentText)
def error_check_func(self): """ Error check for acousticbrainz URL method - Uses the song ID got from above to test if the acoustbrainz website responds correctly - The song ID is entered into the acoustbrainz.org URL for high-level metadata retrieval - If for any reason this fails the acoustid API is used for metadata retrieval - If the acoustid API is used the results are stored and edit_filename_func method is executed - If the acousticbrainz.org website works successfully the artist_func method is executed """ ID = self.ID website = "http://acousticbrainz.org/"+ID+"/high-level" try: response = urllib2.urlopen(website) except urllib2.HTTPError, e: if e.code: print "Using API\n" apikey = self.api_key fingerprint = self.fingerprint duration = self.duration data = acoustid.lookup(apikey, fingerprint, duration) result = acoustid.parse_lookup_result(data) for line in result: self.song = line[2] self.artist = line[3] self.edit_filename_func() return None
def execute(self, file_name: str, db_session: sessionmaker, conn: pymssql.Connection) -> (str, bool): # Get the secrets from environment. api_key = os.environ['ACOUSTID_API_KEY'] cursor: pymssql.Cursor = conn.cursor() # Fetch the fingerprint and length cursor.execute('EXEC sp_SelectFileFingerprintLength %s', file_name) length, fingerprint = cursor.fetchone() # Get the results from acoustid. results = acoustid.parse_lookup_result(acoustid.lookup(api_key, fingerprint, length)) results = [r for r in results if r[3] is not None] # If we don't want have any results from the fingerprint, that's fine. if len(results) == 0: return file_name, True # We want to select the most confident answer. max_confidence = max([r[0] for r in results]) results = [r for r in results if r[0] == max_confidence] # Store all possible results. for song in results: cursor.execute( 'EXEC sp_InsertPossibleMatches %s, %s, %s, %s', (file_name, song[3], song[2], song[1]) ) cursor.close() return (file_name, True)
def error_check_func(self): """ Error check for acousticbrainz URL method - Uses the song ID got from above to test if the acoustbrainz website responds correctly - The song ID is entered into the acoustbrainz.org URL for high-level metadata retrieval - If for any reason this fails the acoustid API is used for metadata retrieval - If the acoustid API is used the results are stored and edit_filename_func method is executed - If the acousticbrainz.org website works successfully the artist_func method is executed """ ID = self.ID website = "http://acousticbrainz.org/" + ID + "/high-level" try: response = urllib2.urlopen(website) except urllib2.HTTPError, e: if e.code: print "Using API\n" apikey = self.api_key fingerprint = self.fingerprint duration = self.duration data = acoustid.lookup(apikey, fingerprint, duration) result = acoustid.parse_lookup_result(data) for line in result: self.song = line[2] self.artist = line[3] self.edit_filename_func() return None
def getNamesLastFM(self, path): # Use acoustid API to get song data if ID3 tags are not available. fing = fingerprint_file(path, force_fpcalc=True) fing = fing[1] fing = str(fing) fing = fing[2:-1] url = 'https://api.acoustid.org/v2/lookup?client=' url += akey url += '&meta=recordings+releasegroups+compress&duration=' url += str(self.d) url += '&fingerprint=' url += fing try: text = urllib.request.urlopen(url) parsed = json.loads(text.read()) names = list(acoustid.parse_lookup_result(parsed)) for x in names: if None not in x: names = x title = names[-2] artist = names[-1] # Check if any feat. artists names in original name. if ';' in artist: artist = artist.split(';') artist = artist[0] if ',' in artist: artist = artist.split(',') artist = artist[0] break self.artist_name1 = artist self.song_name1 = title except: print("No name data during search...")
def match(string): API_KEY = 'HMU8Btr6' #filename1 = 'song.mp3' dur,fingp = acoustid.fingerprint_file(string) commentText = "" try: #results = acoustid.match(API_KEY, filename) results1 = acoustid.lookup(API_KEY, fingp, dur) results = acoustid.parse_lookup_result(results1) except acoustid.NoBackendError: print("chromaprint library/tool not found", file=sys.stderr) sys.exit(1) except acoustid.FingerprintGenerationError: print("fingerprint could not be calculated", file=sys.stderr) sys.exit(1) except acoustid.WebServiceError as exc: print("web service request failed:", exc.message, file=sys.stderr) sys.exit(1) first = True for score, rid, title, artist in results: if first: first = False else: commentText += "\n" commentText += '%s - %s \n' % (artist, title) #commentText += 'http://musicbrainz.org/recording/%s \n'% rid #commentText += 'Score: %i%% \n'% (int(score * 100)) return(commentText)
def __str__(self): "Show AcoustID artist and title if available, or otherwise the track path" if self.acoustid: for _score, _recording_id, title, artist in parse_lookup_result( self.acoustid): if title or artist: return '%s - %s' % (artist, title) return self.path
def best_match_dict(lookup_result): parsed = acoustid.parse_lookup_result(lookup_result) high_score = 0 res_dict = {} for i in parsed: if i[0] > high_score: res_dict['score'] = i[0] res_dict['artist'] = i[3] res_dict['title'] = i[2] return res_dict
def lookup_fp(fingerprint, duration): """Query MusicBrainz with given fingerprint""" import acoustid mb_json = acoustid.lookup(mb_apikey, fingerprint, duration) # # lookup(apikey, fingerprint, duration): Make a request to the # Acoustid API to look up the fingerprint returned by the # previous function. An API key is required, as is the length, # in seconds, of the source audio. Returns a parsed JSON # response. result = acoustid.parse_lookup_result(mb_json) # # parse_lookup_result(data): Given a parsed JSON response, return # an iterator over tuples containing the match score (a float # between 0 and 1), the MusicBrainz recording ID, title, and # artist name for each match return result
def id(self, track): try: dur, fp = acoustid.fingerprint_file(track.file) response = acoustid.parse_lookup_result(acoustid.lookup(API_KEY,fp,dur,'recordings')) response = response.next() releases = self.search((response[2],response[3],dur*1000)) track.title = response[2] artist = self.library.addArtist(response[3]) track.artist = artist albums = [] for album in releases: x = artist.addAlbum(album) albums.append(x) track.album = albums except EOFError: track.title = 'ERROR' except StopIteration: track.title = 'ERROR'
def error_check_func(self): ID = self.ID website = "http://acousticbrainz.org/"+ID+"/high-level" try: response = urllib2.urlopen(website) except urllib2.HTTPError, e: if e.code: print "ERROR" apikey = self.api_key fingerprint = self.fingerprint duration = self.duration data = acoustid.lookup(apikey, fingerprint, duration) result = acoustid.parse_lookup_result(data) for line in result: self.song = line[2] self.artist = line[3] self.dict_func() return None
def aidmatch(filename): try: #results = acoustid.match(API_KEY, filename) results1 = acoustid.lookup(API_KEY, fingp, dur) results = acoustid.parse_lookup_result(results1) except acoustid.NoBackendError: print("chromaprint library/tool not found", file=sys.stderr) sys.exit(1) except acoustid.FingerprintGenerationError: print("fingerprint could not be calculated", file=sys.stderr) sys.exit(1) except acoustid.WebServiceError as exc: print("web service request failed:", exc.message, file=sys.stderr) sys.exit(1) first = True for score, rid, title, artist in results: if first: first = False else: print() print('%s - %s' % (artist, title)) print('http://musicbrainz.org/recording/%s' % rid) print('Score: %i%%' % (int(score * 100)))
elif filename.endswith('.ogg'): file_metadata = OggVorbis(filename) decode_command = ['oggdec', filename, '-o', wavefile] elif filename.endswith('.mp3'): file_metadata = EasyID3(filename) decode_command = ['lame', '--decode', filename, wavefile] else: print "Don't know to handle this file" continue print 'Looking up track on AcoustID/MusicBrainz' print '--------------------------------------------------------------------------------' # TODO: max 3 requests/sec to AcoustID/MusicBrainz, just sleeping a sec for the time being time.sleep(1) acoustid_duration, acoustid_fingerprint = acoustid.fingerprint_file(filename) # TODO: use fingerprint & duration to check for duplicates in database? seems like matching fingerprints is not trivial acoustid_result = acoustid.parse_lookup_result(acoustid.lookup(acoustid_key, acoustid_fingerprint, acoustid_duration)) mb_metadata = [] for result in acoustid_result: track = mb.getTrackById(result[1], TrackIncludes(artist=True, releases=True)) # TODO: needs to be limited, what if we get 20 results from acoustid? releases = [] for release in track.getReleases(): releases.append({ 'name': release.getTitle(), 'tracknum': release.getTracksOffset() + 1, 'musicbrainz_release_id': release.getId()[release.getId().rfind('/') + 1:] }) mb_metadata.append({ 'artist': track.getArtist().getName(), 'title': track.getTitle(), 'releases': releases, 'musicbrainz_track_id': result[1],