def audio_check(file_buffer): config = { 'host': audio_identifier_host, 'access_key': audio_identifier_access_key, 'access_secret': audio_identifier_access_secret, 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_AUDIO, 'debug': False, 'timeout': 10 # seconds } re = ACRCloudRecognizer(config) res_str = re.recognize_by_filebuffer(file_buffer, 0, 10) res_dict = json.loads(res_str) status_code = res_dict["status"]["code"] if status_code == 0: # TO DO # create answer payload metadata = res_dict["metadata"] metadata_music_list = metadata["music"] check_answer = {} for i in range(0, len(metadata_music_list)): title = metadata_music_list[i]["title"] artists = metadata_music_list[i]["artists"] song = {'title': title, 'artists': artists} hashed_val = hashlib.sha1(json.dumps(song, \ sort_keys=True).encode()).hexdigest() if check_answer.get(hashed_val) == None: check_answer[hashed_val] = i answer = song return answer else: status_msg = res_dict["status"]["msg"] err = {'error': status_msg} return err
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 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 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 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 __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 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 __init__(self, config, debug=1): self.openpyxl_version = ".".join( str(openpyxl.__version__).split(".")[:2]) self.config = config self.debug = debug self.init_log() self.re_handler = ACRCloudRecognizer(self.config)
def auth(self, config): recognizer_config = { "host": config["ACRCloud"]["host"], "access_key": config["ACRCloud"]["access_key"], "access_secret": config["ACRCloud"]["secret_key"], "timeout": 10 } self.recognizer = ACRCloudRecognizer(recognizer_config)
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_songs(tiktok_url): config = { 'host': "identify-eu-west-1.acrcloud.com", 'access_key': "8862724c406dc09588b45a0100a6ff14", 'access_secret': "VUZkQ7vDytAxAcizRV1YzgwmZ12Mt57fyCmQkRf2", 'timeout': 10 } re = ACRCloudRecognizer(config) buf = get_mp3_bytes_code(tiktok_url) return re.recognize_by_filebuffer(buf, 0)
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 __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 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_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 __init__(self, config, master=None): super().__init__(master) self.acr_cloud = re = ACRCloudRecognizer(config) self.db = sql.connect('./db.sqlite3') self.cur = self.db.cursor() w, h = 1000, 550 # size of main window # screen size of display ws = self.master.winfo_screenwidth() hs = self.master.winfo_screenheight() # center position x = (ws / 2) - (w / 2) y = (hs / 2) - (h / 2) # configure main window self.master.title('Radio Surveillance System') self.master.geometry('%dx%d+%d+%d' % (w, h, x, y)) self.master.resizable(0, 0) self.config(background='saddle brown') self.pack(fill=tk.BOTH, expand=1) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(1, weight=1) self.master.protocol("WM_DELETE_WINDOW", self.on_closing) # create initial widgets self.create_widget() return
class Recognizer: def auth(self, config): recognizer_config = { "host": config["ACRCloud"]["host"], "access_key": config["ACRCloud"]["access_key"], "access_secret": config["ACRCloud"]["secret_key"], "timeout": 10 } self.recognizer = ACRCloudRecognizer(recognizer_config) def recognize(self, url): response = requests.get(url, stream=True) buffer = io.BytesIO(response.content).read() response = self.recognizer.recognize_by_filebuffer(buffer, 0) data = json.loads(response) status = data["status"]["msg"] if status == "Success": title = data["metadata"]["music"][0]["title"] artist = data["metadata"]["music"][0]["artists"][0]["name"] song = "{} - {}".format(artist, title) return song else: return False
def hum(filePath): config = config_hum '''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]. #re.recognize_by_file(filePath, 0, 10) logger.info('ACR: Processing request...') buf = open(filePath, 'rb').read() #recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. data = re.recognize_by_filebuffer(buf, 0, 10) data = json.loads(data) logger.info('ACR: Processing complete!') return data
def createAuthObject(): f_secrets = open('secrets.txt', 'r') twitch_client_id = f_secrets.readline().strip() twitch_client_secret = f_secrets.readline().strip() acr_host = f_secrets.readline().strip() acr_key = f_secrets.readline().strip() acr_secret = f_secrets.readline().strip() yt_key = f_secrets.readline().strip() f_secrets.close() oauth_endpoint = "https://id.twitch.tv/oauth2/token?client_id={}&client_secret={}&grant_type={}".format( twitch_client_id, twitch_client_secret, "client_credentials") oauth_reply = requests.post(oauth_endpoint).json() twitch_token = oauth_reply['access_token'] ACR_config = { 'host': acr_host, 'access_key': acr_key, 'access_secret': acr_secret, 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_AUDIO, 'debug': False, 'timeout': 10 # seconds } copyright_recognizer = ACRCloudRecognizer(ACR_config) return Auth(twitch_token, twitch_client_id, copyright_recognizer, yt_key)
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 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 audio_file(audio): config = { 'host': 'ap-southeast-1.api.acrcloud.com', 'access_key': 'f1840ce5b0603e9db3ec8c526eea65e5', 'access_secret': '1NfVJoxoREbGlO9HVqG4QNkSiMT86Lvs3Geogov9', 'debug': True, 'timeout': 30 # 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]. buf = open(audio, 'rb').read() # recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. return re.recognize_by_filebuffer(buf, 1)
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 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 identify_audio(): config = { 'host': cc.audio_acr_host, 'access_key': cc.audio_acr_access_key, 'access_secret': cc.audio_access_secret, 'timeout': 5 # seconds } re = ACRCloudRecognizer(config) print('Recognizing...') acr_res = re.recognize_by_file(wav_path, 0) return json.loads(acr_res)
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 setup(): 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 } re = ACRCloudRecognizer(config) return re
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 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 recognize_music(music_file, host, key, secret): config = { 'host': host.encode('utf-8'), 'access_key': key.encode('utf-8'), 'access_secret': secret.encode('utf-8'), '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(music_file, 0, 10) buf = open(music_file, '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) result = re.recognize_by_filebuffer(buf, 0, 10) return result
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
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)
#-*- 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)
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)) 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)
if __name__ == '__main__': config = { 'host': """<Your host>""", 'access_key': """<You ACRCloud access key>""", 'access_secret': """<Your ACRCloud access secret>""", 'debug': False, 'timeout': 40 # seconds } flag = 1 while flag: '''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) # Use file from arguments and if there is no file, then record music from mic if len(sys.argv) > 1: buf = open(sys.argv[1], 'rb').read() flag = 0 else: Record() buf = open("output.wav", 'rb').read() # Recognize by file_audio_buffer that read from file path or mic, and skip 0 seconds from the beginning. data_content = re.recognize_by_filebuffer(buf, 0) # Transform received json to object data = json.loads(data_content)
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)
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
import os, sys from acrcloud.recognizer import ACRCloudRecognizer 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)
def __init__(self, config, debug=1): self.config = config self.debug = debug self.init_log() self.re_handler = ACRCloudRecognizer(self.config)
def get_duration_by_file(self, filepath): return int(ACRCloudRecognizer.get_duration_ms_by_file(filepath)/1000)