def recognizeAudio(): djv = Dejavu(config) djv.fingerprint_directory("songs", [".mp3"], 3) print "starting recognition" song = djv.recognize(MicrophoneRecognizer, seconds=5) print "finished recognition" print(song) return song['song_name']
def msearch(self): types = ('audio/wav', 'audio/mp3') for aud in self.request.files: print aud aud = self.request.files[aud] if len(aud) < 1: return u'上传失败' _t = aud[0]['content_type'] if _t not in types: return u'上传文件有误,请回去重新上传' print fname = md5(aud[0]['filename'] + str(time.time())).hexdigest() fname += '.wav' fname = os.path.join('temp', fname) # print type() with open(fname, 'wb') as f: f.write(aud[0]['body']) try: djv = Dejavu(config) print 'begint recognize...' song = djv.recognize(FileRecognizer, fname) except Exception as e: song = str(e) finally: # os.remove(fname) pass print 'recognize: ', song return song
def init(): # load config from a JSON file (or anything outputting a python dictionary) with open("dejavu.cnf") as f: config = json.load(f) # create a Dejavu instance return Dejavu(config)
def crbt(): result = "" if request.method == 'POST': print request if 'file' not in request.files: print('No file part') file = request.files['file'] if file.filename == '': print('No selected file') file = request.files['file'] filename = secure_filename(file.filename) # os.path.join is used so that paths work in every operating system file.save(os.path.join("temp", filename)) # You should use os.path.join here too. with open("dejavu.cnf.SAMPLE") as f: config = json.load(f) djv = Dejavu(config) song = djv.recognize(FileRecognizer, "temp/" + filename) path = "temp/" + filename os.remove(path) title = song["song_name"].replace('_', ' ') confidence = song["confidence"] if (confidence < 50): result = {'title': "Unknown Song"} else: result = {'title': title} return jsonify(result)
def findSong(): global confidence, song djv = Dejavu(config) song_internal = djv.recognize(FileRecognizer, "voice.wav") print(song_internal) confidence = song_internal['confidence'] song = song_internal
def mp_worker(urldata): url = None station_name = None song = None name = None try: url, station_name = urldata name = station_name + '.mp3' except ValueError: pass try: u = urllib.request.urlopen(url) data = u.read(150000) with open(name, 'wb') as file: file.write(data) time.sleep(1) except Exception as e: print(e) #try: djv = Dejavu(config) song = djv.recognize(FileRecognizer, name) # print("From Stream we recognized: {}\n".format(song)) if song is None: print("NONE") elif song['confidence'] >= 40: file_data = None try: with open(station_name + ".txt", 'r') as file: file_data = file.read() except Exception as e: with open(station_name + ".txt", 'w') as file: pass if file_data == song["song_name"]: print('ad already recorded') with open('log_date.txt', 'a') as writeFile: writeFile.write( "\n Duplicate recognition with confidence %d %s " % (song["confidence"], song["song_name"])) else: with open(station_name + ".txt", 'w') as file: file.write(song["song_name"]) db_cls = get_database(config.get("database_type", None)) db = db_cls(**config.get("database", {})) db.setup() # count = db.get_song_count_by_name(song["song_name"]) # db.update_song_count(song["song_name"],count['count']+1) d_local = datetime.datetime.now(pytz.timezone("Asia/Kathmandu")) db.insert_radio_song(station_name, song["song_name"], 'Begari Guys', int(song['confidence']), d_local) print("From file we recognized: {}\n".format(song["song_name"])) with open('log_date.txt', 'a') as writeFile: writeFile.write("\n Identified with high confidence %d %s" % (song['confidence'], song['song_name'])) else: with open('log_date.txt', 'a') as writeFile: writeFile.write("\n Identified with very less confidence %d %s" % (song['confidence'], song["song_name"])) print("From file we recognized: {} {} \n".format( song["song_name"], song['confidence']))
def fingerprint(args): print args (surahDirectory, surahFile) = args surahFile = surahDirectory.rstrip('/') + "/" + surahFile databaseName = "dejavu" + os.path.basename(surahFile)[:3] # MySQL database config # Dejavu stores fingerprints in MySQL using the config provided below. config = { "database": { "host": DATABASE_HOST, "user": DATABASE_USER, "passwd": DATABASE_PASSWORD, "db": databaseName, } } print surahFile.split("/")[-1] # Create a database for the current surah db1 = mysql.connect(host=config["database"]["host"], user=config["database"]["user"], passwd=config["database"]["passwd"]) cursor = db1.cursor() sql = 'CREATE DATABASE IF NOT EXISTS ' + config["database"]["db"] cursor.execute(sql) # Pass the MySQL config to dejavu to fingerprint the surah djv = Dejavu(config) djv.fingerprint_file(surahFile)
def main(): djv = Dejavu(config) if request.method == 'GET': file_log = open("hashes_samples.log", "r") array_hashes = file_log.readlines() elif request.method == 'POST': json_local = request.get_json() if len(json_local['hashes']) == 0: return jsonify({'error': 'invalid input'}) string_hashes = json_local['hashes'] string_hashes = string_hashes.replace("[", "") string_hashes = string_hashes.replace("]", "") array_hashes = string_hashes.rstrip().split(', ') hashes = dict() samples_indexes = [] for string_hash in array_hashes: sample_index, hash_local, offset = string_hash.rstrip().split('|') if sample_index in hashes: hashes[sample_index].append((hash_local, int(offset))) else: hashes[sample_index] = [] if sample_index not in samples_indexes: samples_indexes.append(sample_index) matches = [] for sample_index in samples_indexes: matches.extend(djv.rest_find_matches(hashes[sample_index])) return jsonify(djv.align_matches(matches))
def run(): print("Running digest") for filename in os.listdir(path): print(path + filename) djv = Dejavu(config) response = djv.recognize(FileRecognizer, path + filename) print(response) print("*" * 30) if response: save_record(filename, response) os.remove(path + filename) print("Matched and record saved") return "2" else: #No match was found if "_attempt1" in filename: response = { 'offset': 0, 'confidence': 0, 'offset_seconds': 0, 'match_time': 0, 'song_name': 'None', 'dejavu_log': '' } save_record(filename, response) os.remove(path + filename) print("Did not match and record saved") return "0" else: new_filename = filename.split('.')[0] + "_attempt1.wav" os.rename(path + filename, path + new_filename) print("Did not match, will try again") return "1"
def mon_super_test(request): print("=" * 50) print(request.data) files = request.data.get("uploaded_file") # Read song from parameters -> download it as mp3 file files.file.seek(0) b = io.BytesIO(files.file.read()) song = AudioSegment.from_file(b, format="3gp") song.export("temp/test.mp3", format="mp3") # create a Dejavu instance djv = Dejavu(config) # Recognize audio from a file song_found = djv.recognize(FileRecognizer, "temp/test.mp3") if song_found: song_name = song_found.get('song_name').split("--") artist = song_name[0] title = song_name[1] else: artist = "" title = "" return JsonResponse({'artist': artist, 'title': title})
def init(configpath): try: with open(configpath) as f: config = json.load(f) except IOError as err: print("Cannot open configuration: %s. Exiting" % (str(err))) sys.exit(1) return Dejavu(config)
def fingerprintAndComputeAccuracy(fingerprintReduction, peakSort, defaultOverlapRatio, defaultFanValue, defaultAmpMin, peakNeighbourhoodSize): # create a Dejavu instance djv = Dejavu(config) # Fingerprint all the mp3's in the directory we give it djv.fingerprint_directory("mp3", [".mp3"])
def runDejavu(): # create a Dejavu instance djv = Dejavu(config) # service.py executed as script # do something activateMic.micStart() results = djv.recognize(FileRecognizer, "mp3/recording.wav") print(f"From file we recognized: {results}\n")
def run_client(): """ runs all the patches """ run() directory_path = raw_input("enter the directory path") djv = Dejavu(config) djv.fingerprint_directory(directory_path, [".mp3"], 3)
def check_dejavu(path): dburl = 'sqlite:///new.db' djv = Dejavu(dburl=dburl) recognizer = FileRecognizer(djv) song = recognizer.recognize_file(path) if song['confidence'] < DEJAVU_THRESHOLD: return ("Not found", False) return (song['song_id'], True)
def start(event): if __name__ == '__main__': djv = Dejavu(config) secs = 8 song = djv.recognize(MicrophoneRecognizer, seconds=secs) if song is None: print "Nothing recognized -- did you play the song out loud so your mic could hear it?" else: print "From mic with %d seconds we recognized: %s\n" % (secs, song)
def __init__(self, config, filename, video_id): """ usage: fingerprinter = Lilo('/path/to/video/file','unique_video_id') """ self.djv = Dejavu(config) self.filename = filename self.video_id = video_id # cache these after first fingerprint self.hashes = None
def createDJV(): config = { "database": { "host": "127.0.0.1", "user": "******", "password": '******', "database": 'dejavu', } } djv = Dejavu(config) return djv
def initDejavu(self, config): params = { 'window_size': 4096, 'overlap_ratio': 0.5, 'fan_value': 15, 'amp_min': 10, 'neighborhood_size': 20, 'max_hash_time_delta': 200 } self.djv = Dejavu(params, config) self.secs = 5 self.params = params
def init(config_file): """ Load config from a JSON file or anything outputting a python dictionary """ try: with open(config_file) as f: config = json.load(f) except IOError as err: print("Cannot open configuration: %s. Exiting" % (str(err))) sys.exit(1) # create a Dejavu instance return Dejavu(config)
def init(configpath): """ Load config from a JSON file """ try: with open(configpath) as f: config = json.load(f) except IOError as err: print(("Cannot open configuration: %s. Exiting" % (str(err)))) sys.exit(1) # create a Dejavu instance return Dejavu(config)
def recognize_audio(): # load config # check if the post request has the audio part if "audio" not in request.files: data = {'message': 'Audio to fingerprint is missing.'} return jsonify(data), 400 else: print("bat dau xu ly file upload") audio = request.files["audio"] #filename = request.form["info"] if audio.filename == "": data = {'message': 'Audio to fingerprint is missing.'} return jsonify(data), 400 else: # Save file in a temporary location try: name, ext = os.path.splitext(audio.filename) print("Save file...") if ext not in ('.mp3'): return {'message': 'File extension not allowed.'} audio.save(os.path.join(path, name + ext)) except Exception as ex: template = "An 1 exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) data = {'message': message} return data # Create a Dejavu instance print("Create instance") djv = Dejavu(config) # Recognize audio from a file try: print("recognize audio is starting") song = djv.recognize(FileRecognizer, os.path.join(path, name + ext)) print(song) data = {'message': 'successful', 'result': song} os.remove(os.path.join(path, name + ext)) if song: return jsonify(data) else: return {'message': 'None'} except Exception as ex: template = "An 2 exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) data = {'message': message} return data return Response(status=200)
def audio_test(test_files_root=None, extensions=None): djv = Dejavu(config) file_list = get_dir_files(test_files_root, extensions) true_num = 0 offsets = [] statistics_off = {} avg_offsets = 0.0 for index, filename in enumerate(file_list): music_name = filename.split('/')[-1].split('.')[0] song = djv.recognize(FileRecognizer, test_files_root + "/" + filename.split('/')[-1]) flag = 'False' pos = 'False' if not song: continue if find_lcsubstr(song['song_name'], music_name)[1] >= 2: true_num += 1 flag = 'True' music_start_pos = float(music_name.split('_')[-2]) result_pos = song['song_name'].split('_')[-2] tempos = float(result_pos) + float(song['offset_seconds']) offset = tempos - music_start_pos offsets.append(offset) if statistics_off.has_key(str(int(offset))): statistics_off[str(int(offset))] += 1 else: statistics_off[str(int(offset))] = 1 print "%03d: %3d/%-3d %s offset:%02.3f %-30s search_result:%-20s detail_info:%s" % ( (index + 1), true_num, len(file_list), flag, offset, music_name, song['song_name'], song) max_key = '0' max_value = -1 for key, value in statistics_off.items(): if int(statistics_off[key]) > int(max_value): max_value = value max_key = key sum_pos = 0 for off in offsets: if abs(int(off) - int(max_key)) <= 1: sum_pos += 1 print "%d/%-3d pos_true_num:%d" % (true_num, len(file_list), sum_pos)
def start_febreze(): djv = Dejavu(config) for ele in learn_music: djv.fingerprint_file('mp3/' + str(ele) + '.mp3') print('Sleeping for 5 seconds') time.sleep(5) print('Listening for sounds') song = djv.recognize(MicrophoneRecognizer, seconds=10) print(song) if song['song_name'] in learn_music and song['confidence'] > 500: response = requests.request("PUT", url, data=payload, headers=headers) temp = json.loads(response.text) if str(temp['status']) == 'OK': print('Dispensed Febreze')
def upload_file(): if request.method == 'POST': file = request.files['file'] brand = request.form['brand'] offertitle = request.form['offertitle'] offercontent = request.form['offercontent'] image = request.files['offerimage'] offerlink = request.form['offerlink'] if file and allowed_file(file.filename) and image and allowed_file( image.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # Can also rename the uploaded file if you want #os.rename(UPLOAD_FOLDER + filename, UPLOAD_FOLDER+'niloofar.jpg') FILEPATH = UPLOAD_FOLDER + filename imagename = secure_filename(image.filename) image.save( os.path.join(app.config['UPLOAD_FOLDER'] + "images/", imagename)) imagepath = UPLOAD_FOLDER + "images/" + imagename #Initializing Dejavu object with config djv = Dejavu(config) #Insert clip and its fingerprint in DB sid = djv.fingerprint_file(FILEPATH) #Insert related AdContent to DB # Create db connection to add data db = mysql.connect() cursor = db.cursor() cursor.execute( "INSERT INTO adcontent (sid, brand, offertitle, offercontent, imagepath, offerlink) VALUES (%s,%s,%s,%s,%s,%s)", (sid, brand, offertitle, offercontent, imagepath, offerlink)) db.commit() db.close() #Data object for html template data = {"sid": sid} print( "\nSuccessfully added clip and adcontent to DB and recorded Fingerprint!" ) return render_template('upload.html', data=data) return render_template('upload.html')
def main(): config = { "database": { "host": "127.0.0.1", "user": "******", "passwd": "root", "db": "Philadelphia" } } djv = Dejavu(config) # start fingerprint djv.fingerprint_directory("../../Seattle/data/songs", [".mp3"], 4) print djv.db.get_num_fingerprints()
def __init__(self, video_name, sourceid=None, region=None, programname=None, programid=None, scheduleid=None): """ Takes the video name. Creates a Dejavu object. Also obtains the duration and number of frames in the video. """ self.video_name = video_name self.djv = Dejavu(CONFIG) self.sourceid = sourceid self.region= region self.programname = programname self.programid = programid self.scheduleid = scheduleid
def fingerprint_audio(): # check if the post request has the audio part if ('audio') not in request.files: data = {'message': 'Audio to fingerprint is missing.'} return jsonify(data), 400 elif ('info') not in request.form: data = {'message': 'Info of file is missing'} return jsonify(data), 400 else: print("bat dau xu ly file upload") audio = request.files["audio"] filename = request.form["info"] if audio.filename == "": data = {'message': 'Audio to fingerprint is missing.'} return jsonify(data), 400 else: # Save file in a temporary location try: name, ext = os.path.splitext(audio.filename) print("Save file...") if ext not in ('.mp3'): return {'message': 'File extension not allowed.'} audio.save(os.path.join(path2, str(filename) + ext)) except Exception as ex: template = "An 1 exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) data = {'message': message} return data # Create a Dejavu instance print("Create instance") djv = Dejavu(config) # Fingerprinting audio from a file try: print("recognize audio is starting") song = djv.fingerprint_file( os.path.join(path2, str(filename) + ext)) data = {'message': 'completed'} print(song) os.remove(os.path.join(path2, str(filename) + ext)) return jsonify(data) except Exception as ex: template = "An 2 exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) data = {'message': message} return data return Response(status=200)
def fingerprintFile(fileName): config = { "database": { "host": "127.0.0.1", "user": MYSQL_USER, "passwd": MYSQL_PASS, "db": "dejavu", }, "database_type": "mysql", "fingerprint_limit": -1 } djv = Dejavu(config) djv.fingerprint_file(fileName + ".wav", fileName)
def mp_worker(urldata): url = None number = None song = None name = None try: url, number = urldata name = 'recording' + number + '.mp3' except ValueError: pass try: u = urllib.request.urlopen(url) data = u.read(100000) with open(name, 'wb') as file: file.write(data) time.sleep(1) except Exception as e: print(e) try: djv = Dejavu(config) song = djv.recognize(FileRecognizer, name) if song is None: print("NONE") elif song['confidence'] >= 100: db_cls = get_database(config.get("database_type", None)) db = db_cls(**config.get("database", {})) db.setup() # count = db.get_song_count_by_name(song["song_name"]) # db.update_song_count(song["song_name"],count['count']+1) d = datetime.datetime.now() timezone = pytz.timezone("Asia/Katmandu") d_local = timezone.localize(d) db.insert_radio_song(number, song["song_name"], 'Begari Guys', int(song['confidence']), d_local) print("From file we recognized: {} {}\n".format(song["song_name"])) with open('log.txt', 'a') as writeFile: writeFile.write("\n Identified with high confidence %d %s" % (song['confidence'], song["song_name"])) else: with open('log.txt', 'a') as writeFile: writeFile.write( "\n Identified with very less confidence %d %s" % (song['confidence'], song["song_name"])) print("From file we recognized: {} {} {}\n".format( song["song_name"], song['confidence'])) except Exception as e: print(e)