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 lookup(self): json_file = acoustid.lookup(self.API_KEY , self._fingerprint , self.duration) if 'error' in json_file: raise MusicUtilsException(json_file['error']['code'],json_file['error']['message']) self._scores , self._recording_ids , temp_song, temp_artist = parse_result(json_file) self.song_title , self.artist = max(temp_song.iteritems(), key = operator.itemgetter(1))[0].encode('utf-8') , max(temp_artist.iteritems(), key = operator.itemgetter(1))[0].encode('utf-8') self._best_acoust ,self._best_score = self._bestacoustid(self._scores) self._mbids,self._song_details = self._recording_details(self._recording_ids[self._best_acoust]) self.mbid ,self.date = self._latestmbid(self._song_details) self.album = self._extract_album_name(self.mbid) return MusicUtils(API_KEY= self.API_KEY, scores = self._scores, recording_ids = self._recording_ids, song_title = self.song_title, artist = self.artist , best_acoust_id = self._best_acoust, best_score = self._best_score, mbids = self._mbids, song_details= self._song_details, mbid= self.mbid, date= self.date, album=self.album, #backup_date = self._backup_date, fingerprint = self._fingerprint, duration = self.duration, cover_art_url = MusicUtils.base_image_url + self.mbid #mbid_dates=self._mbid_dates )
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 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 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 acoustid_lookup(fingerprint, duration): results = acoustid.lookup(ACOUST_ID_API_KEY, fingerprint, duration, meta='recordings + releasegroups') if results.get('results') and results['results'][0].get('recordings'): LOGGER.info('AcoustID result found!') recordings = results['results'][0]['recordings'] recording = max(recordings, key=lambda x: len(x.keys())) recording_id = recording['id'] recording_artists = recording['artists'] recording_title = recording['title'] album_artist = recording_artists[0]['name'] artist = ''.join([ artist['name'] + artist.get('joinphrase', '') for artist in recording_artists ]) album = recording['releasegroups'][0][ 'title'] # TODO: the results of this are often inconsistent return { 'musicbrainz_releasetrackid': recording_id, 'title': recording_title, 'artist': artist, 'albumartist': album_artist, 'album': album } else: LOGGER.info('No AcoustID results found.') return {}
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 acoustid_match(log, path): """Gets metadata for a file from Acoustid and populates the _matches, _fingerprints, and _acoustids dictionaries accordingly. """ try: duration, fp = acoustid.fingerprint_file(util.syspath(path)) except acoustid.FingerprintGenerationError as exc: log.error('fingerprinting of {0} failed: {1}', util.displayable_path(repr(path)), exc) return None fp = fp.decode() _fingerprints[path] = fp try: res = acoustid.lookup(API_KEY, fp, duration, meta='recordings releases') except acoustid.AcoustidError as exc: log.debug('fingerprint matching {0} failed: {1}', util.displayable_path(repr(path)), exc) return None log.debug('chroma: fingerprinted {0}', util.displayable_path(repr(path))) # Ensure the response is usable and parse it. if res['status'] != 'ok' or not res.get('results'): log.debug('no match found') return None result = res['results'][0] # Best match. if result['score'] < SCORE_THRESH: log.debug('no results above threshold') return None _acoustids[path] = result['id'] # Get recording and releases from the result if not result.get('recordings'): log.debug('no recordings found') return None recording_ids = [] releases = [] for recording in result['recordings']: recording_ids.append(recording['id']) if 'releases' in recording: releases.extend(recording['releases']) # The releases list is essentially in random order from the Acoustid lookup # so we optionally sort it using the match.preferred configuration options. # 'original_year' to sort the earliest first and # 'countries' to then sort preferred countries first. country_patterns = config['match']['preferred']['countries'].as_str_seq() countries = [re.compile(pat, re.I) for pat in country_patterns] original_year = config['match']['preferred']['original_year'] releases.sort(key=partial( releases_key, countries=countries, original_year=original_year)) release_ids = [rel['id'] for rel in releases] log.debug('matched recordings {0} on releases {1}', recording_ids, release_ids) _matches[path] = recording_ids, release_ids
def acoustid_match(log, path): """Gets metadata for a file from Acoustid and populates the _matches, _fingerprints, and _acoustids dictionaries accordingly. """ try: duration, fp = acoustid.fingerprint_file(util.syspath(path)) except acoustid.FingerprintGenerationError as exc: log.error(u'fingerprinting of {0} failed: {1}', util.displayable_path(repr(path)), exc) return None fp = fp.decode() _fingerprints[path] = fp try: res = acoustid.lookup(API_KEY, fp, duration, meta='recordings releases') except acoustid.AcoustidError as exc: log.debug(u'fingerprint matching {0} failed: {1}', util.displayable_path(repr(path)), exc) return None log.debug(u'chroma: fingerprinted {0}', util.displayable_path(repr(path))) # Ensure the response is usable and parse it. if res['status'] != 'ok' or not res.get('results'): log.debug(u'no match found') return None result = res['results'][0] # Best match. if result['score'] < SCORE_THRESH: log.debug(u'no results above threshold') return None _acoustids[path] = result['id'] # Get recording and releases from the result if not result.get('recordings'): log.debug(u'no recordings found') return None recording_ids = [] releases = [] for recording in result['recordings']: recording_ids.append(recording['id']) if 'releases' in recording: releases.extend(recording['releases']) # The releases list is essentially in random order from the Acoustid lookup # so we optionally sort it using the match.preferred configuration options. # 'original_year' to sort the earliest first and # 'countries' to then sort preferred countries first. country_patterns = config['match']['preferred']['countries'].as_str_seq() countries = [re.compile(pat, re.I) for pat in country_patterns] original_year = config['match']['preferred']['original_year'] releases.sort(key=partial(releases_key, countries=countries, original_year=original_year)) release_ids = [rel['id'] for rel in releases] log.debug(u'matched recordings {0} on releases {1}', recording_ids, release_ids) _matches[path] = recording_ids, release_ids
def match(apikey, path, fp=None, dur=None, meta='releases recordings tracks'): """Look up the metadata for an audio file. If ``parse`` is true, then ``parse_lookup_result`` is used to return an iterator over small tuple of relevant information; otherwise, the full parsed JSON response is returned. """ path = os.path.abspath(os.path.expanduser(path)) if None in (fp, dur): dur, fp = fingerprint_file(path) response = acoustid.lookup(apikey, fp, dur, meta) return response, fp
def _acoustid_tag_file(self, filepath): """ Gets metadata for a file from Acoustid. returns a Result object with Fingerprint, acoustid, recording_ids and release_ids Suppresses all exceptions - will return None if failed """ path = Path(filepath) try: duration, fingerprint = acoustid.fingerprint_file(str(path)) except acoustid.FingerprintGenerationError as exc: logger.error('fingerprinting of {0} failed: {1}', filepath, exc) return None try: res = acoustid.lookup(self.api_key, fingerprint, duration, meta='recordings releases') except acoustid.AcoustidError as exc: logger.debug('fingerprint matching {0} failed: {1}', filepath, exc) return None logger.debug('fingerprinted {0}', filepath) # Ensure the response is usable and parse it. if res['status'] != 'ok' or not res.get('results'): logger.debug('no match found') return None acoustid_result = res['results'][0] # Best match. if acoustid_result['score'] < self.SCORE_THRESH: logger.debug('no results above threshold') return None # Get recording and releases from the result. if not acoustid_result.get('recordings'): logger.debug('no recordings found') return None recording_ids = [] release_ids = [] for recording in acoustid_result['recordings']: recording_ids.append(recording['id']) if 'releases' in recording: release_ids += [rel['id'] for rel in recording['releases']] logger.debug('matched recordings {0} on releases {1}', recording_ids, release_ids) return AcoustIDTaggerResult(fingerprint, acoustid_result['id'], recording_ids, release_ids)
def lookup(self): "Get the artist and title for a track" if self.acoustid: return fp = encode_fingerprint(self.fingerprint, settings.FINGERPRINT_VERSION) self.acoustid = lookup(settings.ACOUSTID_API_KEY, fp, self.duration.total_seconds()) # print(dumps(self.acoustid, sort_keys=True, indent=2)) if self.acoustid[ 'status'] == 'ok' and 'results' in self.acoustid and self.acoustid[ 'results']: super().save()
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 acoustid_match(log, path): """Gets metadata for a file from Acoustid and populates the _matches, _fingerprints, and _acoustids dictionaries accordingly. """ try: duration, fp = acoustid.fingerprint_file(util.syspath(path)) except acoustid.FingerprintGenerationError as exc: log.error(u'fingerprinting of {0} failed: {1}', util.displayable_path(repr(path)), exc) return None _fingerprints[path] = fp try: res = acoustid.lookup(API_KEY, fp, duration, meta='recordings releases') except acoustid.AcoustidError as exc: log.debug(u'fingerprint matching {0} failed: {1}', util.displayable_path(repr(path)), exc) return None log.debug(u'chroma: fingerprinted {0}', util.displayable_path(repr(path))) # Ensure the response is usable and parse it. if res['status'] != 'ok' or not res.get('results'): log.debug(u'no match found') return None result = res['results'][0] # Best match. if result['score'] < SCORE_THRESH: log.debug(u'no results above threshold') return None _acoustids[path] = result['id'] # Get recording and releases from the result. if not result.get('recordings'): log.debug(u'no recordings found') return None recording_ids = [] release_ids = [] for recording in result['recordings']: recording_ids.append(recording['id']) if 'releases' in recording: release_ids += [rel['id'] for rel in recording['releases']] log.debug(u'matched recordings {0} on releases {1}', recording_ids, release_ids) _matches[path] = recording_ids, release_ids
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 acoustid_match(path): """Gets metadata for a file from Acoustid and populates the _matches, _fingerprints, and _acoustids dictionaries accordingly. """ try: duration, fp = acoustid.fingerprint_file(path) except acoustid.FingerprintGenerationError as exc: log.error('fingerprinting of %s failed: %s' % (repr(path), str(exc))) return None _fingerprints[path] = fp try: res = acoustid.lookup(API_KEY, fp, duration, meta='recordings releases') except acoustid.AcoustidError as exc: log.debug('fingerprint matching %s failed: %s' % (repr(path), str(exc))) return None log.debug('chroma: fingerprinted %s' % repr(path)) # Ensure the response is usable and parse it. if res['status'] != 'ok' or not res.get('results'): log.debug('chroma: no match found') return None result = res['results'][0] if result['score'] < SCORE_THRESH: log.debug('chroma: no results above threshold') return None _acoustids[path] = result['id'] # Get recordings from the result. if not result.get('recordings'): log.debug('chroma: no recordings found') return None recording = result['recordings'][0] recording_id = recording['id'] if 'releases' in recording: release_ids = [rel['id'] for rel in recording['releases']] else: release_ids = [] log.debug('chroma: matched recording {0}'.format(recording_id)) _matches[path] = recording_id, release_ids
def acoustid_match(log, path): """Gets metadata for a file from Acoustid and populates the _matches, _fingerprints, and _acoustids dictionaries accordingly. """ try: duration, fp = acoustid.fingerprint_file(util.syspath(path)) except acoustid.FingerprintGenerationError as exc: log.error(u"fingerprinting of {0} failed: {1}", util.displayable_path(repr(path)), exc) return None _fingerprints[path] = fp try: res = acoustid.lookup(API_KEY, fp, duration, meta="recordings releases") except acoustid.AcoustidError as exc: log.debug(u"fingerprint matching {0} failed: {1}", util.displayable_path(repr(path)), exc) return None log.debug(u"chroma: fingerprinted {0}", util.displayable_path(repr(path))) # Ensure the response is usable and parse it. if res["status"] != "ok" or not res.get("results"): log.debug(u"no match found") return None result = res["results"][0] # Best match. if result["score"] < SCORE_THRESH: log.debug(u"no results above threshold") return None _acoustids[path] = result["id"] # Get recording and releases from the result. if not result.get("recordings"): log.debug(u"no recordings found") return None recording_ids = [] release_ids = [] for recording in result["recordings"]: recording_ids.append(recording["id"]) if "releases" in recording: release_ids += [rel["id"] for rel in recording["releases"]] log.debug(u"matched recordings {0} on releases {1}", recording_ids, release_ids) _matches[path] = recording_ids, release_ids
def acoustid_lookup(fingerprint, duration): results = acoustid.lookup(ACOUST_ID_API_KEY, fingerprint, duration, meta='recordings + releasegroups') if results.get('results') and results['results'][0].get('recordings'): LOGGER.info('AcoustID result found!') recordings = results['results'][0]['recordings'] recording = max(recordings, key=lambda x: len(x.keys())) recording_id = recording['id'] recording_artists = recording['artists'] recording_title = recording['title'] album_artist = recording_artists[0]['name'] artist = ''.join([artist['name'] + artist.get('joinphrase', '') for artist in recording_artists]) album = recording['releasegroups'][0]['title'] # TODO: the results of this are often inconsistent return {'musicbrainz_releasetrackid': recording_id, 'title': recording_title, 'artist': artist, 'albumartist': album_artist, 'album': album} else: LOGGER.info('No AcoustID results found.') return {}
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)))
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
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],
def lookup(audio_file): fingerprint = audio_file['fingerprint'] duration = audio_file['duration'] return acoustid.lookup('cSpUJKpD', fingerprint, duration)['results']
def lookup_fingerprint(song_fingerprint, song_duration, API_Key='UrmHbpV5BV'): res = acoustid.lookup(API_Key, song_fingerprint, song_duration) return res
_userkey = None def acoustid_match(path): """Gets metadata for a file from Acoustid and populates the _matches, _fingerprints, and _acoustids dictionaries accordingly. """ try: duration, fp = acoustid.fingerprint_file(path) except acoustid.FingerprintGenerationError, exc: log.error('fingerprinting of %s failed: %s' % (repr(path), str(exc))) return None _fingerprints[path] = fp try: res = acoustid.lookup(API_KEY, fp, duration, meta='recordings releases') except acoustid.AcoustidError, exc: log.debug('fingerprint matching %s failed: %s' % (repr(path), str(exc))) return None log.debug('chroma: fingerprinted %s' % repr(path)) # Ensure the response is usable and parse it. if res['status'] != 'ok' or not res.get('results'): log.debug('chroma: no match found') return None result = res['results'][0] if result['score'] < SCORE_THRESH: log.debug('chroma: no results above threshold') return None _acoustids[path] = result['id']
def process_file(file_name): "process a file and returns information about the audio." (duration, fingerprint) = ad.fingerprint_file(file_name) return ad.lookup(apikey, fingerprint, duration)
#!/usr/bin/python import acoustid import sys import audioread with audioread.audio_open(sys.argv[1]) as f: duration = int(f.duration) fp = acoustid.fingerprint(f.samplerate, f.channels, iter(f)) user_key = "VUz6PQRB" app_key = "k3QqfYqe" acoustid.set_base_url("http://132.206.14.136/ws/v2/") print acoustid.lookup(app_key, fp, duration)
def _fetch_lookup(self, duration, fingerprint, meta=None): return acoustid.lookup(self.apikey, fingerprint, duration, meta or self.lookup_meta)
sp.current_user playlist = sp.user_playlist_create(sp.current_user()['id'], playlist_name) # print(playlist) sys.path += [os.getcwd()] path = "./music" spids = [] for _, _, files in os.walk(path): for f in files: file = os.path.join(path, f) print(f) duration, fp = acoustid.fingerprint_file(file) print() json = acoustid.lookup('lFPruUAJVk', fp, duration, meta='recordings') if not json['results']: print('no se xd') else: results = json['results'] for result in results: if 'recordings' in result: recordings = result['recordings'] for recording in recordings: if 'title' in recording: title = recording['title'] artist = '' for a in recording['artists']: artist += str(a['name']) + ' ' artist.strip() q = title + ' ' + artist
def match_fingerprint(fprnt, api_key): return acoustid.lookup(api_key, fprnt[1], fprnt[0])