class Acr_cloud(object): def __init__(self, config_file): self.config = self.load_creds(config_file) self.acr = ACRCloudRecognizer(self.config) def load_creds(self, config_file): try: with open(config_file, 'r') as creds: usr_key = json.load(creds) return usr_key except Exception as e: logging.error(e) def trace_sample(self, wav_file): data_dictionary = json.loads(self.acr.recognize_by_file(wav_file, 0)) data_dictionary = data_dictionary["metadata"] song_data = { "Artist": data_dictionary["music"][0]["artists"][0]["name"], "Title": data_dictionary["music"][0]["title"], "Duration": data_dictionary["music"][0]["duration_ms"] } mins = str(round((float(song_data["Duration"]) / 1000) / 60, 2)) # Convert duration_ms to minutes and seconds song_data["Duration"] = mins.replace(".", ":") song_data["Genre"] = data_dictionary["music"][1]["genres"][0]["name"] return song_data
def sound_find(self, file_path): file = file_path config = { #Replace "xxxxxxxx" below with your project's host, access_key and access_secret. 'host': self.host, 'access_key': self.access_key, 'access_secret': self.access_secret, 'timeout': 60 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. #print(re.recognize_by_file(file, 0)) indata = re.recognize_by_file(file, 0) indata = str(indata) indata = json.loads(indata) #print(type(indata)) #you_id=indata["metadata"]["music"][0]["external_metadata"]["youtube"]["vid"] #print("https://www.youtube.com/watch?v="+you_id) if indata["status"]["msg"] == "Success": return indata["metadata"]["music"][0]["external_metadata"] else: return False pass
def music_print(self): # tag : artist, title, genre, album, label config = { 'host': 'us-west-2.api.acrcloud.com', 'access_key': '', 'access_secret': '', 'debug': False, 'timeout': 10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) dict1 = ast.literal_eval(re.recognize_by_file(self.megafile.get_url(), 0)) if dict1['status']['msg'] == 'Success' and dict1['metadata'] and dict1['metadata']['music'][0]: return dict1 else: # make sure to catch IOError buf = open(self.megafile.get_url(), 'rb').read() dict2 = ast.literal_eval(re.recognize_by_filebuffer(buf, 0)) if dict2['status']['msg'] == 'Success' and dict2['metadata'] and dict2['metadata']['music'][0]: return dict2
def recognize(file_name): config = { 'host': 'identify-cn-north-1.acrcloud.com', 'access_key': 'a2027bf3a7998a47874e361ad626409e', 'access_secret': 'n8u8aoLWvqqM5v3Gg6wDPxya8VpnwIpYreq7JrMx', 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_AUDIO, 'debug': False, 'timeout': 10 # seconds } print('config ok') '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) print('read config ok') res = json.loads(re.recognize_by_file(file_name)) number = len(res['metadata']['music']) songList = [] for i in range(number): song = {} song["name"] = res['metadata']['music'][i]['title'] song["singer"] = res['metadata']['music'][i]['artists'][0]['name'] songList.append(song) result = {} result["songlist"] = songList #result=json.loads(result) result = str(result) return result.replace('u\'', '\'')
def get_subs(): while True: print('Recording... ',end='\r') data = sd.rec(int(SECONDS * RATE), samplerate=RATE, channels=2) sd.wait() wavf.write('out.wav', RATE, data) acr = ACRCloudRecognizer(config) results = json.loads(acr.recognize_by_file('out.wav', 0)) if results.get('status') and results['status'].get('code') == 1001: continue break with open('logs/res_dump.json', 'w') as f: json.dump(results, f, indent=2) response_time = results['cost_time'] load_lyric_start = timer() subs = None for result in acr['metadata']['music']: artist = result['artists'][0]['name'].split(';')[0] song = result['title'] offset_time = result['play_offset_ms'] / 1000 run_time = result['duration_ms'] / 1000 print(song, artist) search_request = SearchRequest(artist, song) subs = ComboLyricsProvider().search(search_request) if subs: print(f"Found Using Engine '{subs.metadata['provider']}'") return subs, load_lyric_start-response_time-offset_time, run_time, song return None
def check_music(self): '''Проверка музыки''' config = { 'host': 'identify-eu-west-1.acrcloud.com', 'access_key': 'a18a4f6a76f4a6edf47e3204266f8692', 'access_secret': 'iGKRisfMUvAex9mFKTlOloMPPqf3BrMmfxjzL85g', 'debug': False, 'timeout': 10, } acrcloud = ACRCloudRecognizer(config) data = acrcloud.recognize_by_file(file_path = 'audio/{}.mp4'.format(self.name), start_seconds = 0) data = json.loads(data) path = os.path.join(os.path.abspath(os.getcwd()), 'audio/{}.mp4'.format(self.name)) os.remove(path) try: name_artist = data['metadata']['music'][0]['artists'][0]['name'] name_song = data['metadata']['music'][0]['title'] self.result = str(name_artist) + ' - ' + str(name_song) return 'ok' except: result_error = data['status']['msg'] if result_error == 'Missing/Invalid Access Key': self.result = 'Ошибка на стороне сервера' return 'ok' elif result_error == 'No result': self.result = 'Песня не найдена' return 'ok'
def recognize_music(full_path): re = ACRCloudRecognizer(config) result = json.loads(re.recognize_by_file(full_path, 0)) if result['status']['code'] != 0: buf = open(full_path, 'rb').read() result = json.loads(re.recognize_by_filebuffer(buf, 0)) if result['status']['code'] != 0: return 'UNKNOWN' data = result['metadata']['music'][0] return data['title'] + '-' + data['artists'][0]['name']
def get_tracks_from_audio(file): response = ({}, 404) if file is None or file == '': print('invalid audio file') response = ({}, 400) else: config = { 'host': 'identify-us-west-2.acrcloud.com', 'access_key': os.environ.get('ACCESS_KEY'), 'access_secret': os.environ.get('ACCESS_SECRET'), 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_BOTH, 'debug': False, 'timeout': 10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' recognizer = ACRCloudRecognizer(config) f = tempfile.NamedTemporaryFile() f.write(file.read()) duration = ACRCloudRecognizer.get_duration_ms_by_file(str(f.name)) print("duration_ms=" + str(duration)) if duration // 1000 > 10: max_duration = max(10, (duration * 20 // 100) // 1000) else: max_duration = 10 result = json.loads(recognizer.recognize_by_file(str(f.name), 0, max_duration)) print(result) f.close() tracks = process_metadata(result) data = { 'data': tracks } response = (data, 200) print(json.dumps(response[0], indent=4)) return response
def recognize(path): recognized = { 'title': '', 'artist': '', } # Load song metadata from acrcloud try: from acrcloud.recognizer import ACRCloudRecognizer re = ACRCloudRecognizer(storage.config) recognized_data = json.loads(re.recognize_by_file(path, 0)) recognized_song = recognized_data['metadata']['music'][0] recognized['title'] = recognized_song['title'] recognized['artist'] = recognized_song['artists'][0]['name'] except KeyError: pass return recognized
def main(): sp = spotipy.Spotify(auth=token) sp.trace = False music = "" artist = "" config = { #Replace "xxxxxxxx" below with your project's host, access_key and access_secret. 'host':'identify-eu-west-1.acrcloud.com', 'access_key':'c20267418e799f23a3f94b14baf3a790', 'access_secret':'aiwwg7KPELXaWt9AwvfYv6IclZSCTndEltCftKjJ', 'timeout':10 # seconds } re = ACRCloudRecognizer(config) while(1): os.system('sudo ./ripper.sh') json_data = json.loads(re.recognize_by_file("/tmp/aaa.mp3", 0)) print(json.dumps(json_data)) if(json_data["status"]["msg"] == "Success"): current_music = json_data["metadata"]["music"][0]["title"] current_artist = json_data["metadata"]["music"][0]["artists"][0]["name"] if current_music != music or current_artist != artist: music = current_music artist = current_artist external = json_data["metadata"]["music"][0]["external_metadata"] if "spotify" in external: spotify_id = external["spotify"]["track"]["id"] print("SPOT ID ", spotify_id) if(token): try: r = sp.user_playlist_remove_all_occurrences_of_tracks(username,playlist,[spotify_id]) print(r) r = sp.user_playlist_add_tracks(username, playlist, [spotify_id]) print(r) except spotipy.client.SpotifyException: print("exception") refresh() sp = spotipy.Spotify(auth=token) sp.trace = False sp.user_playlist_remove_all_occurrences_of_tracks(username,playlist,[spotify_id]) sp.user_playlist_add_tracks(username, playlist, [spotify_id]) os.remove("/tmp/aaa.mp3") os.remove("/tmp/aaa.cue")
def recognize_music(filePath, config, start): config["timeout"] = 10 # seconds re = ACRCloudRecognizer(config) # recognize by file path, and skip 'start' seconds from from the beginning of sys.argv[1]. result = json.loads(re.recognize_by_file(filePath, start, start + 10)) if 'metadata' in result.keys(): result = result['metadata']['music'][0] if 'genres' in result.keys(): # TODO : check if genres in required list return (result['title'], result['artists'][0]['name'], ','.join([g['name'] for g in result['genres']])) else: return (result['title'], result['artists'][0]['name'], '') else: return ('', '', '')
def collect_metadata(msg, chtid): file_id = msg["voice"]["file_id"] filep = bot.getFile(file_id) re = ACRCloudRecognizer(config) abc = filep["file_path"] newres = "https://api.telegram.org/file/bot" + botid + "/" + abc file_name = wget.download(newres) respon = re.recognize_by_file(file_name, 0) result = json.loads(respon) if (result["status"]["msg"] == "Success"): print(result) name = result["metadata"]["music"][0]["title"] artist = result["metadata"]["music"][0]["artists"][0]["name"] album = result["metadata"]["music"][0]["album"]["name"] bot.sendMessage( chtid, "Song Name : " + name + "\nArtist : " + artist + "\nAlbum : " + album) else: bot.sendMessage(chtid, "No data found\nPlease try again")
def identify(): config = { 'host': 'identify-us-west-2.acrcloud.com', 'access_key': 'e0dec6b559cf1186da4b5283ab214b98', 'access_secret': 'k8Mb4sYf0A0xcVpptNb24m7uQ8jrGUSAR3nblN3X', 'recognize_type': ACRCloudRecognizeType. ACR_OPT_REC_AUDIO, # you can replace it with [ACR_OPT_REC_AUDIO,ACR_OPT_REC_HUMMING,ACR_OPT_REC_BOTH], The SDK decide which type fingerprint to create accordings to "recognize_type". 'debug': False, 'timeout': 10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sound file. json = re.recognize_by_file("file.flac", 0, 10) #print(json) if "Success" not in json: #we have an error return "error recording song" else: #gonna cut out title and artist from what is returned start = json.index("\"artists\":[{\"name\":" ) + 20 ##20 chars before the stuff we want end = json.index("\"", start) artist = json[start:end] start = json.index("\"title\":\"") + 9 end = json.index("\"", start) title = json[start:end] if "spotify" in json: #it has a spotify id start = json.index("spotify") json = json[start:] json = json[json.index("track"):] start = json.index("\"id\":\"") + 6 end = json.index("\"", start) songId = json[start:end] print(title + " by " + artist) return songId else: #it does not have a spotify id return "Not on Spotify, but song is " + title + " by " + artist
def identify_audio(file=None, start_sec=0, end_sec=None): """Requests data from ACRCloud and re-formats for manageability""" from acrcloud.recognizer import ACRCloudRecognizer import json import os if end_sec is None: end_sec = start_sec + 30 login = { "access_key": config.ACR.key, "access_secret": config.ACR.secret, "host": "identify-us-west-2.acrcloud.com" } acr = ACRCloudRecognizer(login) try: sample_length = end_sec - start_sec except TypeError: sample_length = timestamptoSec(end_sec) - timestamptoSec(start_sec) try: data = json.loads(acr.recognize_by_file(file, start_sec, sample_length)) os.remove(file) # delete the file since we don't need it anymore except: pass try: title, artists, score, duration, play_offset, acr_id = data["metadata"]["music"][0]["title"], data['metadata']['music'][0]['artists'][0]['name'], \ data['metadata']['music'][0]['score'], data["metadata"]["music"][0]["duration_ms"], \ data["metadata"]["music"][0]["play_offset_ms"], data["metadata"]["music"][0]["acrid"] return { "msg": "success", "title": title, "artists": artists, "score": score, "play_offset": play_offset, "duration": duration, "acr_id": acr_id } except: return {"msg": "error", "score": 0}
def recognize_song(self, file): re = ACRCloudRecognizer(self.config) print('Recognizing song') result = re.recognize_by_file(file, 0, 10) result = json.loads(result) success = result.get('status').get('msg') if success == 'Success': #print(result.get('metadata').get('music')[0]) artist = result.get('metadata').get('music')[0].get( 'artists')[0].get('name') title = result.get('metadata').get('music')[0].get('title') offset = result.get('metadata').get('music')[0].get( 'play_offset_ms') duration = result.get('metadata').get('music')[0].get( 'duration_ms') print("duration_ms=" + str(ACRCloudRecognizer.get_duration_ms_by_file(file))) value = (artist, title, float(offset) / duration, duration) else: value = None print(value) return value
class AudioRecognizer: def __init__( self, sample_rate, duration, channels, filename, audio_format, high_pass_frequency, high_pass_order, acrcloud_config, acrcloud_result_score_threshold, recognizer_start_offset=0, noise_audio_filepath=None, additional_operations=None ): self.sample_rate = sample_rate self.duration = duration self.channels = channels self.filename = filename self.audio_format = audio_format self.high_pass_frequency = high_pass_frequency self.high_pass_order = high_pass_order self.recognizer = ACRCloudRecognizer(acrcloud_config) self.acrcloud_result_score_threshold = acrcloud_result_score_threshold self.recognizer_start_offset = recognizer_start_offset self.noise_audio_filepath = noise_audio_filepath if not additional_operations: additional_operations = [] self.additional_operations = additional_operations def _log_action(self, action, ready=False): print(f"[{datetime.datetime.now()}] {self.filename}: {action} - {'ready' if ready else 'started'}") def record(self): self._log_action(self.record.__name__) recording = sounddevice.rec( int(self.duration * self.sample_rate), samplerate=self.sample_rate, channels=self.channels ) sounddevice.wait() wavfile.write(self.filename, self.sample_rate, recording) self._log_action(self.record.__name__, ready=True) def normalize(self): self._log_action(self.normalize.__name__) raw_sound = AudioSegment.from_file(self.filename, self.audio_format) normalized_sound = effects.normalize(raw_sound) normalized_sound.export(self.filename, format=self.audio_format) self._log_action(self.normalize.__name__, ready=True) def high_pass_filter(self): self._log_action(self.high_pass_filter.__name__) raw_sound = AudioSegment.from_file(self.filename, self.audio_format) high_passed_sound = raw_sound.high_pass_filter( self.high_pass_frequency, order=self.high_pass_order ) high_passed_sound.export(self.filename, format=self.audio_format) self._log_action(self.high_pass_filter.__name__, ready=True) def denoise(self): if self.noise_audio_filepath: self._log_action(self.denoise.__name__) fs, original_sound = wavfile.read(self.filename) fs, noisy_sound = wavfile.read(self.noise_audio_filepath) denoised_sound = noisereduce.reduce_noise( audio_clip=original_sound, noise_clip=noisy_sound ) wavfile.write(self.filename, self.sample_rate, numpy.asarray(denoised_sound, dtype=numpy.float32)) self._log_action(self.denoise.__name__, ready=True) def delete_recording(self): self._log_action(self.delete_recording.__name__) os.remove(self.filename) self._log_action(self.delete_recording.__name__, ready=True) def recognize(self): self._log_action(self.recognize.__name__) result = json.loads( self.recognizer.recognize_by_file( self.filename, self.recognizer_start_offset, rec_length=self.duration ) ) pprint.pprint(result) metadata = result.get("metadata", {}).get("music", [{}])[0] if metadata.get("score", 0) < self.acrcloud_result_score_threshold: metadata = {} else: del result["metadata"] self._log_action(self.recognize.__name__, ready=True) return { "artist": metadata.get("artists", [{}])[0].get("name"), "album": metadata.get("album", {}).get("name"), "title": metadata.get("title"), "__info": result } def record_and_recognize(self): self._log_action(self.record_and_recognize.__name__) result = {} try: self.record() self.denoise() self.high_pass_filter() self.normalize() result = self.recognize() for additional_operation in self.additional_operations: additional_operation(self, result) self.delete_recording() except Exception as e: traceback.print_exc() result = { "error": str(e) } self._log_action(self.record_and_recognize.__name__, ready=True) return result
def recog():file.wav SONG_PATH = 'xxxxxxxxxxxxxxxx' if Path(SONG_PATH).is_file(): SONG_NAME = 'file.wav' config = { 'host':'xxxxxxx', 'access_key':'xxxxxx', 'access_secret':'xxxxxxx', 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_AUDIO, 'debug':False, 'timeout':10 # seconds } re = ACRCloudRecognizer(config) details = json.loads(re.recognize_by_file(SONG_NAME, 0, 10)) if len(details) == 1: print('Error: Could not recognize song') return '' else: artist = details.get('metadata').get('music')[0].get('artists')[0].get('name') title = details.get('metadata').get('music')[0].get('title') return artist + " " + title os.remove(SONG_PATH) else: print('Error: Recording not found') return ''
def setData(): global name # print(request.get_json()) path = "C:/Users/bunne/Desktop/hackathons/musicalNoteRecognition" # name['h'] = request.form. matlabEngine = matlab.engine.start_matlab() # matlabEngine.pyth(float(3),float(5)) #runs matlab function in the MATLAB directory # matlabEngine.quit() config = { 'host':'identify-eu-west-1.acrcloud.com', 'access_key':'945a4fef66492f6361dfb80ce4b00bb0', 'access_secret':'Dl7hpMntRyRBDl6UHNHyKoiGMIgXRn0gvpciDSFQ', 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_AUDIO, # you can replace it with [ACR_OPT_REC_AUDIO,ACR_OPT_REC_HUMMING,ACR_OPT_REC_BOTH], The SDK decide which type fingerprint to create accordings to "recognize_type". 'debug':False, 'timeout':10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) # recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. if request.get_json()['upload'] == 1: name = request.get_json()['name'] song = json.loads(re.recognize_by_file(name, 10, 20)) print(song) title = song['metadata']['music'][0]['title'] # print(json.loads(song)) # print(title) artist = song['metadata']['music'][0]['artists'][0]['name'] # print(title + " by " + artist) matlabEngine.cd(path) notes, octave, time = matlabEngine.convertMP3(name, nargout=3) # print(freq) # print(time) matlabEngine.quit() return {"identify" : title + " by " + artist, "notes" : notes, "time" : list(time._data), "octave" : list(octave._data)} # else: # print(request.files['file']) # f = open("music67.wav", "wb") # rawData = (request.get_json()['data'].split('base64,')[1]).split(' ')[0].encode('utf-8') # print(rawData) # f.write(base64.decodebytes(rawData)) # f.close() # # sound = AudioSegment.from_mp3("music67.mp3") # # sound.export("music67.wav", format="wav") # # # # AudioSegment.from_wav("music67.wav").export("music67.mp3", format="mp3") # song = json.loads(re.recognize_by_file("music67.mp3", 10, 20)) # # print(song) # title = song['metadata']['music'][0]['title'] # artist = song['metadata']['music'][0]['artists'][0]['name'] # matlabEngine.cd(path) # freq, time = matlabEngine.convertMP3("music67.mp3", nargout=2) # # matlabEngine.quit() # return {"identify" : title + " by " + artist, "freq" : list(freq._data), "time" : list(time._data)} return {'hello' : 'hello'}
if __name__ == '__main__': config = { 'host':'XXXXXXXX', 'access_key':'XXXXXXXX', 'access_secret':'XXXXXXXX', 'debug':False, 'timeout':10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. print(re.recognize_by_file(sys.argv[1], 0)) print("duration_ms=" + str(ACRCloudRecognizer.get_duration_ms_by_file(sys.argv[1]))) buf = open(sys.argv[1], 'rb').read() #recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. print(re.recognize_by_filebuffer(buf, 0)) #aa.wav must be (RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 8000 Hz) #buf = open('aa.wav', 'rb').read() #buft = buf[1024000:192000+1024001] #recognize by audio_buffer(RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 8000 Hz) #print re.recognize(buft)
def handler_voice(message): ''' Main function: 1.Length checker (audio files should be from 5 to 30 seconds) 2.file_down - downloading file that suitable for this condition 3.rec - recognizing music using ACRCloud script 4.data_collector - creating list of necessary data from result of recognition :param message: ''' user_id = message.chat.id duration = message.voice.duration message_id = message.message_id bot.send_chat_action(user_id, 'typing') if duration < 5: bot.send_message(user_id, '<i>' 'The file is too short, ' 'type /help to get instructions.' '</i>', parse_mode="HTML") elif duration > 30: bot.send_message(user_id, '<i>' 'The file is too long, ' 'type /help to get instructions' '</i>', parse_mode="HTML") else: inputFile = file_down(message.voice.file_id) rec = ACRCloudRecognizer(config.cfg) result = rec.recognize_by_file(inputFile, 0) os.remove(inputFile) result_p = json.loads(result) mlist = data_collector(result_p) print('NEW RECOGNITION: %s' % (result_p['status']['msg'])) if result_p['status']['msg'] == 'Success': data_income(message.voice.file_id, '1') if mlist[0]: #artist output_0 = mlist[0] print(mlist[0], end='') if mlist[1]: #title print(mlist[1]) if 'output_0' in locals(): output_0 += " - %s" % (mlist[1]) else: output_0 = "%s" % (mlist[1]) if mlist[2]: #album output_2 = "Album: '%s'" % (mlist[2]) if mlist[3]: #lable if 'output_2' in locals(): output_2 += "\nLable: %s" % (mlist[3]) else: output_2 = "Lable: %s" % (mlist[3]) if mlist[4]: #release_date if 'output_2' in locals(): output_2 += "\nReleased: %s" % (mlist[4]) else: output_2 = "Released: %s" % (mlist[4]) if mlist[5]: #youtube if 'output_2' in locals(): output_2 += "\n%s%s" % (config.yt_link, mlist[5]) else: output_2 = "%s%s" % (config.yt_link, mlist[5]) botstore = 'https://storebot.me/bot/tadam_bot' button_rate = telebot.types.InlineKeyboardButton( 'Rate, please', botstore) user_markup = telebot.types.InlineKeyboardMarkup() if mlist[6] and mlist[7]: spotify = config.spotify_link + str(mlist[6]) button_spot = telebot.types.InlineKeyboardButton( 'Buy on Spotify', spotify) deezer = config.deezer_link + str(mlist[7]) button_dez = telebot.types.InlineKeyboardButton( 'Buy on Deezer', deezer) user_markup = telebot.types.InlineKeyboardMarkup() user_markup.row(button_dez, button_spot, button_rate) elif mlist[6] and (not mlist[7]): spotify = config.spotify_link + mlist[6] button_spot = telebot.types.InlineKeyboardButton( 'Buy on Spotify', spotify) user_markup = telebot.types.InlineKeyboardMarkUp() user_markup.row(button_spot, button_rate) elif (not mlist[6]) and mlist[7]: deezer = config.deezer_link + mlist[7] button_dez = telebot.types.InlineKeyboardButton( 'Buy on Deezer', deezer) user_markup = telebot.types.InlineKeyboardMarkup() user_markup.row(button_dez, button_rate) else: tadambutton = telebot.types.InlineKeyboardButton( 'TadamBot website', config.tadamweb) user_markup = telebot.types.InlineKeyboardMarkup(tadambutton) user_markup.row(tadambutton) bot.send_message(user_id, '<b>%s</b>' % (output_0), parse_mode="HTML") bot.send_message(user_id, output_2, reply_markup=user_markup) else: data_income(message.voice.file_id, '0') tadambutton = telebot.types.InlineKeyboardButton( 'TadamBot website', config.tadamweb) user_markup = telebot.types.InlineKeyboardMarkup(tadambutton) user_markup.row(tadambutton) bot.send_message( user_id, 'Sorry, no result. You can try again or leave feedback @tadam_support.', reply_markup=user_markup) return mlist
from acrcloud.recognizer import ACRCloudRecognizeType if __name__ == '__main__': config = { 'host':'identify-ap-southeast-1.acrcloud.com', 'access_key':'450adec73c812fc14e6596f48dd95f70', 'access_secret':'KJwFL18C9UhO7xgqftDAmVGMThieQMdtlDCrU5da', 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_AUDIO, # you can replace it with [ACR_OPT_REC_AUDIO,ACR_OPT_REC_HUMMING,ACR_OPT_REC_BOTH], The SDK decide which type fingerprint to create accordings to "recognize_type". 'debug':False, 'timeout':10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. meta = re.recognize_by_file(sys.argv[1], 0, 3) track = meta[meta.index("artists"):] track = track[track.index(":\"")+2:] track = track[:track.index("\"")] print(track) print("duration_ms=" + str(ACRCloudRecognizer.get_duration_ms_by_file(sys.argv[1]))) #buf = open(sys.argv[1], 'rb').read() #recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. #print(re.recognize_by_filebuffer(buf, 0, 10))
import json if __name__ == '__main__': config = { 'host': 'identify-eu-west-1.acrcloud.com', 'access_key': '945a4fef66492f6361dfb80ce4b00bb0', 'access_secret': 'Dl7hpMntRyRBDl6UHNHyKoiGMIgXRn0gvpciDSFQ', 'recognize_type': ACRCloudRecognizeType. ACR_OPT_REC_AUDIO, # you can replace it with [ACR_OPT_REC_AUDIO,ACR_OPT_REC_HUMMING,ACR_OPT_REC_BOTH], The SDK decide which type fingerprint to create accordings to "recognize_type". 'debug': False, 'timeout': 10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. song = json.loads(re.recognize_by_file("music1.mp3", 10, 20)) title = song['metadata']['music'][0]['title'] # print(json.loads(song)) # print(title) artist = song['metadata']['music'][0]['artists'][0]['name'] print(title + " by " + artist) #print("duration_ms=" + str(ACRCloudRecognizer.get_duration_ms_by_file("music1.mp3"))) buf = open("music1.mp3", 'rb').read() # recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. print(re.recognize_by_filebuffer(buf, 0, 10))
from acrcloud.recognizer import ACRCloudRecognizer import json import eye if __name__ == '__main__': config = { 'host':'XXX', 'access_key':'XXX', 'access_secret':'XXX', 'timeout':10 # seconds } re = ACRCloudRecognizer(config) result= re.recognize_by_file(sys.argv[1], 0) audiof = eyed3.load(sys.argv[1]) result1 = json.loads(result) status = result1['status'] music = (result1['metadata'])['music'] album = ((music[0])['album'])['name'] title = (music[0])['title'] artists = (((music[0])['artists'])[0])['name'] get_image(title) try: image = open(title + ".jpg", "rb").read()
if __name__ == '__main__': config = { 'host':'ap-southeast-1.api.acrcloud.com', 'access_key':'<access_key of your project>', 'access_secret':'<access_secret of your project>', 'debug':False, 'timeout':10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) print "recognizing by file ..." inputFile = sys.argv[1] #recognize by file path, and skip X seconds from from the beginning of inputFile. X = 0 print re.recognize_by_file( inputFile, X) ''' # Another way that recognize by buffer # inputFile must be in format: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 8000 Hz inputFile = sys.argv[1] buf = open( inputFile, 'rb').read() print "recognizing by buffer ..." #recognize by file_audio_buffer that read from file path, and skip X seconds from from the beginning of sys.argv[1]. X = 0 print re.recognize_by_filebuffer(buf, X) '''
class ACRCloud_Scan_Files: def __init__(self, config_file): self.config = { 'host': '', 'access_key': '', 'access_secret': '', 'debug': False, 'timeout': 10 # seconds } self.config_file = config_file self.init_log() self.init_config() def init_log(self): self.dlog = AcrcloudLogger('ACRCloud_ScanF', logging.INFO) if not self.dlog.addFilehandler(logfile="log_scan_files.log", logdir="./", loglevel=logging.WARN): sys.exit(1) if not self.dlog.addStreamHandler(): sys.exit(1) def init_config(self): try: json_config = None with codecs.open(self.config_file, 'r') as f: json_config = json.loads(f.read()) for k in ["host", "access_key", "access_secret"]: if k in json_config and json_config[k].strip(): self.config[k] = str(json_config[k].strip()) else: self.dlog.logger.error( "init_config.not found {0} from config.json, pls check" .format(k)) sys.exit(1) self.re_handler = ACRCloudRecognizer(self.config) if self.re_handler: self.dlog.logger.warn("init_config success!") except Exception as e: self.dlog.logger.error("init_config.error", exc_info=True) def read_file(self, infile, jFirst=True): with open(infile, "rb") as rfile: for line in rfile: if jFirst: jFirst = False continue yield line.strip() def write_error(self, file_path, error_time, error_detail): with open( 'error_scan.txt', 'a', ) as f: msg = file_path + '||' + str(error_time) + '||' + str( error_detail) + '\n' f.write(msg) def empty_error_scan(self): if os.path.exists('error_scan.txt'): os.remove('error_scan.txt') def export_to_csv(self, result_list, export_filename="ACRCloud_ScanFile_Results.csv", export_dir="./"): try: results = [] for item in result_list: filename = item["file"] timestamp = item["timestamp"] jsoninfo = item["result"] if "status" in jsoninfo and jsoninfo["status"]["code"] == 0: row = self.parse_data(jsoninfo) row = [filename, timestamp] + list(row) results.append(row) export_filepath = os.path.join(export_dir, export_filename) with codecs.open(export_filepath, 'w', 'utf-8-sig') as f: head_row = [ 'filename', 'timestamp', 'title', 'artists', 'album', 'acrid', 'played_duration', 'label', 'isrc', 'upc', 'dezzer', 'spotify', 'itunes', 'youtube', 'custom_files_title', 'audio_id' ] dw = csv.writer(f) dw.writerow(head_row) dw.writerows(results) self.dlog.logger.info( "export_to_csv.Save Data to csv: {0}".format( export_filepath)) except Exception as e: self.dlog.logger.error("Error export_to_csv", exc_info=True) def parse_data(self, jsoninfo): try: title, played_duration, isrc, upc, acrid, label, album = [""] * 7 artists, deezer, spotify, itunes, youtube, custom_files_title, audio_id = [ "" ] * 7 metadata = jsoninfo.get('metadata', {}) played_duration = metadata.get("played_duration", "") if "music" in metadata and len(metadata["music"]) > 0: item = metadata["music"][0] title = item.get("title", "") offset = item.get("play_offset_ms", "") isrc = item.get("external_ids", {"isrc": ""}).get("isrc", "") upc = item.get("external_ids", {"upc": ""}).get("upc", "") acrid = item.get("acrid", "") label = item.get("label", "") album = item.get("album", {"name": ""}).get("name", "") artists = ",".join([ ar["name"] for ar in item.get('artists', [{ "name": "" }]) if ar.get("name") ]) deezer = item.get("external_metadata", { "deezer": { "track": { "id": "" } } }).get("deezer", { "track": { "id": "" } }).get("track", { "id": "" }).get("id", "") spotify = item.get("external_metadata", { "spotify": { "track": { "id": "" } } }).get("spotify", { "track": { "id": "" } }).get("track", { "id": "" }).get("id", "") itunes = item.get("external_metadata", { "itunes": { "track": { "id": "" } } }).get("itunes", { "track": { "id": "" } }).get("track", { "id": "" }).get("id", "") youtube = item.get("external_metadata", { "youtube": { "vid": "" } }).get("youtube", { "vid": "" }).get("vid", "") if "custom_files" in metadata and len( metadata["custom_files"]) > 0: custom_item = metadata["custom_files"][0] custom_files_title = custom_item.get("title", "") audio_id = custom_item.get("audio_id", "") except Exception as e: self.dlog.logger.error( "parse_data.error.data:{0}".format(metadata), exc_info=True) res = (title, artists, album, acrid, played_duration, label, isrc, upc, deezer, spotify, itunes, youtube, custom_files_title, audio_id) return res def apply_filter(self, results): fworker = FilterWorker() result_new = fworker.apply_filter(results) return result_new def do_recognize(self, filepath, start_time, rec_length): try: current_time = time.strftime('%d %H:%M:%S', time.gmtime(start_time)) res_data = self.re_handler.recognize_by_file( filepath, start_time, rec_length) return filepath, current_time, res_data except Exception as e: self.dlog.logger.error("do_recognize.error.({0}, {1}, {2})".format( filepath, start_time, rec_length), exc_info=True) return filepath, current_time, None def recognize_file(self, filepath, start_time, stop_time, step, rec_length, with_duration=0): self.dlog.logger.warn("scan_file.start_to_run: {0}".format(filepath)) result = [] for i in range(start_time, stop_time, step): filep, current_time, res_data = self.do_recognize( filepath, i, rec_length) try: jsoninfo = json.loads(res_data) code = jsoninfo['status']['code'] msg = jsoninfo['status']['msg'] if "status" in jsoninfo and jsoninfo["status"]["code"] == 0: result.append({ "timestamp": current_time, "rec_length": rec_length, "result": jsoninfo, "file": filep }) res = self.parse_data(jsoninfo) self.dlog.logger.info( 'recognize_file.(time:{0}, title: {1})'.format( current_time, res[0])) if code == 2005: self.dlog.logger.warn( 'recognize_file.(time:{0}, code:{1}, Done!)'.format( current_time, code)) break elif code == 1001: result.append({ "timestamp": current_time, "rec_length": rec_length, "result": jsoninfo, "file": filep }) self.dlog.logger.info( "recognize_file.(time:{0}, code:{1}, No_Result)". format(current_time, code)) elif code == 3001: self.dlog.logger.error( 'recognize_file.(time:{0}, code:{1}, Missing/Invalid Access Key)' .format(current_time, code)) break elif code == 3003: self.dlog.logger.error( 'recognize_file.(time:{0}, code:{1}, Limit exceeded)'. format(current_time, code)) elif code == 3000: self.dlog.logger.error( 'recognize_file.(time:{0}, {1}, {2})'.format( current_time, code, msg)) self.write_error(filepath, i, 'NETWORK ERROR') i += step except Exception as e: self.dlog.logger.error('recognize_file.error', exc_info=True) self.write_error(filepath, i, 'JSON ERROR') return result def scan_file_main(self, option, start_time, stop_time): try: filepath = option.file_path step = option.step rec_length = option.rec_length with_duration = option.with_duration out_dir = option.out_dir if start_time == 0 and stop_time == 0: file_total_seconds = int( ACRCloudRecognizer.get_duration_ms_by_file(filepath) / 1000) results = self.recognize_file(filepath, start_time, file_total_seconds, step, rec_length, with_duration) else: results = self.recognize_file(filepath, start_time, stop_time, step, rec_length, with_duration) filename = 'result-' + os.path.basename(filepath.strip()) + '.csv' fpath = os.path.join(out_dir, filename) if os.path.exists(fpath): os.remove(fpath) if results: self.export_to_csv(results, filename, out_dir) if with_duration == 1: new_results = [] if results: new_results = self.apply_filter(results) filename_with_duration = 'result-' + os.path.basename( filepath.strip()) + '_with_duration.csv' self.export_to_csv(new_results, filename_with_duration, out_dir) except Exception as e: self.dlog.logger.error("scan_file_main.error", exc_info=True) def scan_folder_main(self, option, start_time, stop_time): try: path = option.folder_path file_list = os.listdir(path) for i in file_list: option.file_path = path + '/' + i self.scan_file_main(option, start_time, stop_time) except Exception as e: self.dlog.logger.error("scan_folder_main.error", exc_info=True)
#-*- coding:utf-8 -*- ''' >>> python test.py test.mp3 ''' import os, sys from acrcloud.recognizer import ACRCloudRecognizer from acrcloud.recognizer import ACRCloudRecognizeType if __name__ == '__main__': config = { 'host': 'XXXXXXXX', 'access_key': 'XXXXXXXX', 'access_secret': 'XXXXXXXX', 'recognize_type': ACRCloudRecognizeType. ACR_OPT_REC_AUDIO, # you can replace it with [ACR_OPT_REC_AUDIO,ACR_OPT_REC_HUMMING,ACR_OPT_REC_BOTH], The SDK decide which type fingerprint to create accordings to "recognize_type". 'debug': False, 'timeout': 10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. print re.recognize_by_file(sys.argv[1], 0, 10) buf = open(sys.argv[1], 'rb').read() #recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. print re.recognize_by_filebuffer(buf, 0, 10)
class ACRCloud_Scan_Files: def __init__(self, config, debug=1): self.config = config self.debug = debug self.init_log() self.re_handler = ACRCloudRecognizer(self.config) def init_log(self): log_level = logging.ERROR if self.debug == 1: log_level = logging.DEBUG shandler = logging.StreamHandler() #shandler.setLevel(log_level) self.log = logging.getLogger("ACRCloud_ScanFile") self.log.setLevel(log_level) self.log.addHandler(shandler) def as_text(self, value): if value is None: return "" return str(value) def get_duration_by_file(self, filepath): return int(ACRCloudRecognizer.get_duration_ms_by_file(filepath)/1000) def export_to_xlsx(self, result_list, export_filename="ACRCloud_ScanFile_Results.xlsx", export_dir="./"): try: results = [] for item in result_list: filename = item["file"] timestamp = item["timestamp"] jsoninfo = item["result"] if "status" in jsoninfo and jsoninfo["status"]["code"] == 0: row = self.parse_data(jsoninfo) row = [filename, timestamp] + list(row) results.append(row) results = sorted(results, key=lambda x:x[1]) wb = Workbook() sheet_music = wb.active sheet_music.title = "ACRCloud_Scan_File" header_row = ['filename', 'timestamp', 'custom_files_title', 'custom_acrid', 'title', 'artists', 'album', 'acrid', 'played_duration', 'label', 'isrc', 'upc', 'dezzer', 'spotify', 'itunes', 'youtube'] sheet_music.append(header_row) for row in results: sheet_music.append(row) for column_cells in sheet_music.columns: length = max(len(self.as_text(cell.value)) for cell in column_cells) if length > 80: length == 80 sheet_music.column_dimensions[column_cells[0].column].width = length export_filepath = os.path.join(export_dir, export_filename) wb.save(export_filepath) if self.debug: self.log.info("export_to_xlsx.Save Data to xlsx: {0}".format(export_filename)) except Exception as e: self.log.error("Error@export_to_xlsx", exc_info=True) def export_to_csv(self, result_list, export_filename="ACRCloud_ScanFile_Results.csv", export_dir="./"): try: results = [] for item in result_list: filename = item["file"] timestamp = item["timestamp"] jsoninfo = item["result"] if "status" in jsoninfo and jsoninfo["status"]["code"] == 0: row = self.parse_data(jsoninfo) row = [filename, timestamp] + list(row) results.append(row) results = sorted(results, key=lambda x:x[1]) export_filepath = os.path.join(export_dir, export_filename) with codecs.open(export_filepath, 'w', 'utf-8-sig') as f: head_row = ['filename', 'timestamp', 'custom_files_title', 'custom_acrid', 'title', 'artists', 'album', 'acrid', 'played_duration', 'label', 'isrc', 'upc', 'dezzer', 'spotify', 'itunes', 'youtube'] dw = csv.writer(f) dw.writerow(head_row) dw.writerows(results) if self.debug: self.log.info("export_to_csv.Save Data to csv: {0}".format(export_filename)) except Exception as e: self.log.error("Error@export_to_csv", exc_info=True) def parse_data(self, jsoninfo): try: title, played_duration, isrc, upc, acrid, label, album = [""]*7 artists, deezer, spotify, itunes, youtube, custom_files_title, audio_id, custom_acrid = [""]*8 metadata = jsoninfo.get('metadata', {}) played_duration = metadata.get("played_duration", "") if "music" in metadata and len(metadata["music"]) > 0: item = metadata["music"][0] title = item.get("title", "") offset = item.get("play_offset_ms", "") isrc = item.get("external_ids", {"isrc":""}).get("isrc","") upc = item.get("external_ids", {"upc":""}).get("upc","") acrid = item.get("acrid","") label = item.get("label", "") album = item.get("album", {"name":""}).get("name", "") artists = ",".join([ ar["name"] for ar in item.get('artists', [{"name":""}]) if ar.get("name") ]) deezer = item.get("external_metadata", {"deezer":{"track":{"id":""}}}).get("deezer", {"track":{"id":""}}).get("track", {"id":""}).get("id", "") spotify = item.get("external_metadata", {"spotify":{"track":{"id":""}}}).get("spotify", {"track":{"id":""}}).get("track", {"id":""}).get("id", "") itunes = item.get("external_metadata", {"itunes":{"track":{"id":""}}}).get("itunes", {"track":{"id":""}}).get("track", {"id":""}).get("id", "") youtube = item.get("external_metadata", {"youtube":{"vid":""}}).get("youtube", {"vid":""}).get("vid", "") if "custom_files" in metadata and len(metadata["custom_files"]) > 0: custom_item = metadata["custom_files"][0] custom_files_title = custom_item.get("title", "") audio_id = custom_item.get("audio_id", "") custom_acrid = custom_item.get("acrid", "") except Exception as e: self.log.error("Error@parse_data") res = (custom_files_title, custom_acrid, title, artists, album, acrid, played_duration, label, isrc, upc, deezer, spotify, itunes, youtube,) return res def apply_filter(self, results): fworker = FilterWorker() result_new = fworker.apply_filter(results) return result_new def do_recognize(self, filepath, start_time, rec_length): current_time = time.strftime('%d %H:%M:%S', time.gmtime(start_time)) res_data = self.re_handler.recognize_by_file(filepath, start_time, rec_length) return filepath, current_time, res_data def for_recognize_file(self, filepath, start_time, stop_time, step, rec_length): try: for i in range(start_time, stop_time, step): filep, current_time, res_data = self.do_recognize(filepath, i, rec_length) if res_data: jsoninfo = json.loads(res_data) if "metadata" in jsoninfo and "timestamp_utc" in jsoninfo["metadata"]: jsoninfo["metadata"]["timestamp_utc"] = current_time else: jsoninfo = {} yield {"timestamp":current_time, "rec_length":rec_length, "result":jsoninfo, "file":filep} except Exception as e: self.log.error("Error@for_recognize_file", exc_info=True) def recognize_file(self, filepath, start_time, stop_time, step, rec_length): try: result_list = [] for i in range(start_time, stop_time, step): filep, current_time, res_data = self.do_recognize(filepath, i, rec_length) if res_data: jsoninfo = json.loads(res_data) try: if "metadata" in jsoninfo and "timestamp_utc" in jsoninfo["metadata"]: jsoninfo["metadata"]["timestamp_utc"] = current_time code = jsoninfo["status"]["code"] msg = jsoninfo["status"]["msg"] if jsoninfo["status"]["code"] not in [0, 1001]: raise Exception("recognize_file.(timestamp: {0}, {1}, {2})".format(current_time, code, msg)) except Exception as e: if self.debug: self.log.error(e) else: print e if code in [3001, 3003, 3013]: break else: continue result_list.append({"timestamp":current_time, "rec_length":rec_length, "result":jsoninfo, "file":filep}) if self.debug: parse_info = self.parse_data(jsoninfo) self.log.info('recognize_file.(timestamp: {0}, title: {1})'.format(current_time, parse_info[0])) except Exception as e: self.log.error("Error@recognize_file", exc_info=True) return result_list
'access_secret': 'n8u8aoLWvqqM5v3Gg6wDPxya8VpnwIpYreq7JrMx', 'recognize_type': ACRCloudRecognizeType. ACR_OPT_REC_AUDIO, # you can replace it with [ACR_OPT_REC_AUDIO,ACR_OPT_REC_HUMMING,ACR_OPT_REC_BOTH], The SDK decide which type fingerprint to create accordings to "recognize_type". 'debug': False, 'timeout': 10 # seconds } print('config ok') '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) print('read config ok') res1 = re.recognize_by_file('new_apple.m4a') #print('recognize ok') res = json.loads(res1, encoding='utf-8') print res number = len(res['metadata']['music']) #print res['metadata']['music'][0] songList = [] for i in range(number): song = {} song["name"] = res['metadata']['music'][i]['title'] song["singer"] = res['metadata']['music'][i]['artists'][0]['name'] songList.append(song) result = {} result["songlist"] = songList
class ACRCloud_Scan_Files: def __init__(self, config_file): self.config = { 'host': '', 'access_key': '', 'access_secret': '', 'debug': False, 'timeout': 10 # seconds } self.config_file = config_file self.init_log() self.init_config() def init_log(self): self.dlog = AcrcloudLogger('ACRCloud_ScanF', logging.INFO) if not self.dlog.addFilehandler(logfile = "log_scan_files.log", logdir = "./", loglevel = logging.WARN): sys.exit(1) if not self.dlog.addStreamHandler(): sys.exit(1) def init_config(self): try: json_config = None with codecs.open(self.config_file, 'r') as f: json_config = json.loads(f.read()) for k in ["host", "access_key", "access_secret"]: if k in json_config and json_config[k].strip(): self.config[k] = str(json_config[k].strip()) else: self.dlog.logger.error("init_config.not found {0} from config.json, pls check".format(k)) sys.exit(1) self.re_handler = ACRCloudRecognizer(self.config) if self.re_handler: self.dlog.logger.warn("init_config success!") except Exception as e: self.dlog.logger.error("init_config.error", exc_info=True) def read_file(self, infile, jFirst=True): with open(infile, "rb") as rfile: for line in rfile: if jFirst: jFirst = False continue yield line.strip() def write_error(self, file_path, error_time, error_detail): with open('error_scan.txt', 'a',) as f: msg = file_path + '||' + str(error_time) + '||' + str(error_detail) + '\n' f.write(msg) def empty_error_scan(self): if os.path.exists('error_scan.txt'): os.remove('error_scan.txt') def export_to_csv(self, result_list, export_filename="ACRCloud_ScanFile_Results.csv", export_dir="./"): try: results = [] for item in result_list: filename = item["file"] timestamp = item["timestamp"] jsoninfo = item["result"] if "status" in jsoninfo and jsoninfo["status"]["code"] == 0: row = self.parse_data(jsoninfo) row = [filename, timestamp] + list(row) results.append(row) export_filepath = os.path.join(export_dir, export_filename) with codecs.open(export_filepath, 'w', 'utf-8-sig') as f: head_row = ['filename', 'timestamp', 'title', 'artists', 'album', 'acrid', 'played_duration', 'label', 'isrc', 'upc', 'dezzer', 'spotify', 'itunes', 'youtube', 'custom_files_title', 'audio_id'] dw = csv.writer(f) dw.writerow(head_row) dw.writerows(results) self.dlog.logger.info("export_to_csv.Save Data to csv: {0}".format(export_filepath)) except Exception as e: self.dlog.logger.error("Error export_to_csv", exc_info=True) def parse_data(self, jsoninfo): try: title, played_duration, isrc, upc, acrid, label, album = [""]*7 artists, deezer, spotify, itunes, youtube, custom_files_title, audio_id = [""]*7 metadata = jsoninfo.get('metadata', {}) played_duration = metadata.get("played_duration", "") if "music" in metadata and len(metadata["music"]) > 0: item = metadata["music"][0] title = item.get("title", "") offset = item.get("play_offset_ms", "") isrc = item.get("external_ids", {"isrc":""}).get("isrc","") upc = item.get("external_ids", {"upc":""}).get("upc","") acrid = item.get("acrid","") label = item.get("label", "") album = item.get("album", {"name":""}).get("name", "") artists = ",".join([ ar["name"] for ar in item.get('artists', [{"name":""}]) if ar.get("name") ]) deezer = item.get("external_metadata", {"deezer":{"track":{"id":""}}}).get("deezer", {"track":{"id":""}}).get("track", {"id":""}).get("id", "") spotify = item.get("external_metadata", {"spotify":{"track":{"id":""}}}).get("spotify", {"track":{"id":""}}).get("track", {"id":""}).get("id", "") itunes = item.get("external_metadata", {"itunes":{"track":{"id":""}}}).get("itunes", {"track":{"id":""}}).get("track", {"id":""}).get("id", "") youtube = item.get("external_metadata", {"youtube":{"vid":""}}).get("youtube", {"vid":""}).get("vid", "") if "custom_files" in metadata and len(metadata["custom_files"]) > 0: custom_item = metadata["custom_files"][0] custom_files_title = custom_item.get("title", "") audio_id = custom_item.get("audio_id", "") except Exception as e: self.dlog.logger.error("parse_data.error.data:{0}".format(metadata), exc_info=True) res = (title, artists, album, acrid, played_duration, label, isrc, upc, deezer, spotify, itunes, youtube, custom_files_title, audio_id) return res def apply_filter(self, results): fworker = FilterWorker() result_new = fworker.apply_filter(results) return result_new def do_recognize(self, filepath, start_time, rec_length): try: current_time = time.strftime('%d %H:%M:%S', time.gmtime(start_time)) res_data = self.re_handler.recognize_by_file(filepath, start_time, rec_length) return filepath, current_time, res_data except Exception as e: self.dlog.logger.error("do_recognize.error.({0}, {1}, {2})".format(filepath,start_time,rec_length),exc_info=True) return filepath, current_time, None def recognize_file(self, filepath, start_time, stop_time, step, rec_length, with_duration=0): self.dlog.logger.warn("scan_file.start_to_run: {0}".format(filepath)) result = [] for i in range(start_time, stop_time, step): filep, current_time, res_data = self.do_recognize(filepath, i, rec_length) try: jsoninfo = json.loads(res_data) code = jsoninfo['status']['code'] msg = jsoninfo['status']['msg'] if "status" in jsoninfo and jsoninfo["status"]["code"] ==0 : result.append({"timestamp":current_time, "rec_length":rec_length, "result":jsoninfo, "file":filep}) res = self.parse_data(jsoninfo) self.dlog.logger.info('recognize_file.(time:{0}, title: {1})'.format(current_time, res[0])) if code == 2005: self.dlog.logger.warn('recognize_file.(time:{0}, code:{1}, Done!)'.format(current_time, code)) break elif code == 1001: self.dlog.logger.info("recognize_file.(time:{0}, code:{1}, No_Result)".format(current_time, code)) elif code == 3001: self.dlog.logger.error('recognize_file.(time:{0}, code:{1}, Missing/Invalid Access Key)'.format(current_time, code)) break elif code == 3003: self.dlog.logger.error('recognize_file.(time:{0}, code:{1}, Limit exceeded)'.format(current_time, code)) elif code == 3000: self.dlog.logger.error('recognize_file.(time:{0}, {1}, {2})'.format(current_time, code, msg)) self.write_error(filepath, i, 'NETWORK ERROR') i += step except Exception as e: self.dlog.logger.error('recognize_file.error', exc_info=True) self.write_error(filepath, i, 'JSON ERROR') return result def scan_file_main(self, option, start_time, stop_time): try: filepath = option.file_path step = option.step rec_length = option.rec_length with_duration = option.with_duration if start_time == 0 and stop_time == 0: file_total_seconds = int(ACRCloudRecognizer.get_duration_ms_by_file(filepath)/1000) results = self.recognize_file(filepath, start_time, file_total_seconds, step, rec_length, with_duration) else: results = self.recognize_file(filepath, start_time, stop_time, step, rec_length, with_duration) filename = 'result-' + os.path.basename(filepath.strip()) + '.csv' if os.path.exists(filename): os.remove(filename) if results: self.export_to_csv(results, filename) if with_duration == 1: new_reuslts = [] if results: new_results = self.apply_filter(results) filename_with_duration = 'result-' + os.path.basename(filepath.strip()) + '_with_duration.csv' self.export_to_csv(new_results, filename_with_duration) except Exception as e: self.dlog.logger.error("scan_file_main.error", exc_info=True) def scan_folder_main(self, option, start_time, stop_time): try: path = option.folder_path file_list = os.listdir(path) for i in file_list: option.file_path = path + '/' + i self.scan_file_main(option, start_time, stop_time) except Exception as e: self.dlog.logger.error("scan_folder_main.error", exc_info=True)
def video_song_finder(): # API vars acr_config = { 'host': os.getenv('ACR_HOST_NAME'), 'access_key': os.getenv('ACR_ACCESS_KEY'), 'access_secret': os.getenv('ACR_ACCESS_SECRET'), 'timeout': 10 } # ACR object acr = ACRCloudRecognizer(acr_config) # recognize, 0s offset from start result = eval(acr.recognize_by_file('video.mp4', 0)) if result['status']['msg'] == 'Success': # Recognized the song print("success") # extract the metadata/details metadata = result['metadata'] all_finds = metadata['music'] best_find = all_finds[0] title = best_find['title'] artist = best_find['artists'][0]['name'] # if more than artist then we need to append if len(best_find['artists']) > 1: for index in range(1, len(best_find['artists'])): artist += ", " + best_find['artists'][index]['name'] # get youtube video link if possible youtube = "" try: for listing in all_finds: if 'youtube' in listing['external_metadata']: youtube = 'https://www.youtube.com/watch?v=' + listing['external_metadata']['youtube']['vid'] except: youtube = "" # get spotify link if possible spotify = "" try: for listing in all_finds: if 'spotify' in listing['external_metadata']: spotify = 'https://open.spotify.com/track/' + listing['external_metadata']['spotify']['track']['id'] except: spotify = "" # create tweet tweet = f"Yay, we found it!\nTitle: {title}\n" if len(best_find['artists']) > 1: tweet += f"Artists: {artist}\n" else: tweet += f"Artist: {artist}\n" if youtube != "": tweet += f"Youtube: {youtube}\n" if spotify != "": tweet += f"Spotify: {spotify}" else: # Failed to recognize print("Failure") tweet = "Cannot recognize this song :(" # return tweet return tweet
#-*- coding:utf-8 -*- ''' >>> python test.py test.mp3 ''' import os, sys from acrcloud.recognizer import ACRCloudRecognizer if __name__ == '__main__': config = { 'host':'XXXXXXXX', 'access_key':'XXXXXXXX', 'access_secret':'XXXXXXXX', 'debug':False, 'timeout':10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. print re.recognize_by_file(sys.argv[1], 0) buf = open(sys.argv[1], 'rb').read() #recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. print re.recognize_by_filebuffer(buf, 0)
class Recognizer: def __init__(self): self.log = Logger().log # Loading Necessary Information from Config File with open("./config/config.json") as config_file: config_data = json.load(config_file) self.ACRCloud_config = {"region": config_data["ACRCloud"]["region"].encode('utf8'), "host": config_data["ACRCloud"]["host"].encode('utf8'), "access_key": config_data["ACRCloud"]["access_key"].encode('utf8'), "access_secret": config_data["ACRCloud"]["access_secret"].encode('utf8'), "timeout": config_data["ACRCloud"]["timeout"]} self.log('info', 'initializing connection to ACR-Cloud service') self.acrcloud = ACRCloudRecognizer(self.ACRCloud_config) def recognize(self, track_location): """ :param track_location: Track Location :return: (True, False) after recognition and editing the track """ metainfo = self.get_metainfo(track_location) if metainfo["status"] != "Success": self.log('error', track_location + ' metadata not found') return False self.edit_metadata(track_location, metainfo) self.log('info', track_location + ' recognized!\tACR-Cloud results:\n' + str(metainfo)) return True def edit_metadata(self, track_location, new_metadata): track_data = MusicMetadata(track_location) metadata_diff = DictDiffer(new_metadata, track_data.metadata()) self.log('info', 'OLD Metadata: ' + str(track_data.metadata())) self.log('info', 'NEW Metadata: ' + str(new_metadata)) if metadata_diff.changed(): self.log('info', 'Fixing Wrong Metadata fields\n') track_data.metadata_setter(metadata_diff.changed()) # Edit Changed Values if metadata_diff.added(): self.log('info', 'New fields adding to metadata\n') track_data.metadata_setter(metadata_diff.added()) # Add New Values def get_metainfo(self, track_location): metainfo = self.get_acrcloud_metainfo(track_location) if metainfo["status"]["code"] == 3000: self.log('error', 'Unknown Error happend for track : ' + track_location + '\nACR-Cloud results:\n' + str(metainfo)) return metainfo else: self.log('info', 'ACR-Cloud Answer for track : ' + track_location + '\nACR-Cloud results:\n' + str(metainfo)) return {"album": metainfo["metadata"]["music"][0]["album"]["name"], "album_artist": metainfo["metadata"]["music"][0]["artists"][0]["name"], "artist": metainfo["metadata"]["music"][0]["artists"][0]["name"], # "genre": metainfo["metadata"]["music"][0]["genres"][0]["name"], "release_date": metainfo["metadata"]["music"][0]["release_date"], "title": metainfo["metadata"]["music"][0]["title"], "status": metainfo["status"]["msg"] } def get_acrcloud_metainfo(self, track_location): self.log('info', 'requesting from ACR-Cloud: ' + track_location) return json.loads(self.acrcloud.recognize_by_file(track_location, 20))
print("Error " + str(e)) f.close() sys.stdout.flush() print("") print("10 seconds from " + url + " have been recorded in " + fname) # Identify the track and return it's unique Spotify id. config = { 'host': 'identify-us-west-2.acrcloud.com', 'access_key': '82640bba7076975b5fcaf79d00795d16', 'access_secret': 'JaLNPFDhjQbAuJyQKU8HfU6xZU2YzwzTFFiPH3Z7', 'debug': True, 'timeout': 10 } acrcloud = ACRCloudRecognizer(config) track_data = json.loads(acrcloud.recognize_by_file(fname, 0)) # Cleanup .wav for f in glob.glob('*.wav'): os.remove(f) try: track_title = track_data['metadata']['music'][0]['external_metadata'][ 'spotify']['track']['name'] track_id = track_data['metadata']['music'][0]['external_metadata'][ 'spotify']['track']['id'] print('Identified track as', '\"' + track_title + '\"', track_id) except: print('Audio could not be identified') sys.exit() # Add the track to a spotify playlist. username = '******'
def get_responce(config, music_file_path, start_seconds=3): recognizer = ACRCloudRecognizer(config) # responce = recognizer.recognize_by_file(file_path='/Users/akupriyanov/Desktop/icon_hack/Oxxxymiron.mp3', start_seconds=3) responce = recognizer.recognize_by_file(file_path=music_file_path, start_seconds=start_seconds) return responce