Esempio n. 1
1
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']
Esempio n. 2
0
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})
Esempio n. 3
0
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"
Esempio n. 4
0
    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
Esempio n. 5
0
    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
Esempio n. 6
0
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']))
Esempio n. 7
0
class DejavuPlainDBTestCases(unittest.TestCase):
    def setUp(self):
        self.djv = Dejavu(config_plain)

    def tearDown(self):
        self.djv.db.empty()
        del self.djv

    def test_fingerprint_1_file(self):
        self.djv.fingerprint_file("tests/test1.mp3")
        # should be the only fingerprinted file
        self.assertEqual(1, self.djv.db.get_num_songs())

        self.assertEqual(5279, self.djv.db.get_num_fingerprints())

    def test_fingerprint_directory(self):
        list_dir = [f for f in os.listdir("tests") if f[-4:] == ".mp3"]
        self.djv.fingerprint_directory("tests", [".mp3"])
        self.assertEqual(len(list_dir), self.djv.db.get_num_songs())

    def test_fingerprint_1_file_10secs(self):
        self.djv.limit = 10
        self.djv.fingerprint_file("tests/test1.mp3")
        # should be the only fingerprinted file
        self.assertEqual(1, self.djv.db.get_num_songs())
        # fingerprinting the first 10 secs of this test file,
        # shouldn't get more than 3000 hashes.
        self.assertEqual(2554, self.djv.db.get_num_fingerprints())

    def test_recognize_1_file(self):
        self.djv.fingerprint_file("tests/test1.mp3")
        self.djv.fingerprint_file("tests/test2.mp3")
        song = self.djv.recognize(FileRecognizer, "tests/test2.mp3")
        self.assertEqual(song["song_name"], "tests/test2.mp3")
Esempio n. 8
0
class _Recognizer:
    def __init__(self, index: int, callback: Callable[[Sound, int], None]):
        self._logger = create_logger(f"Recognizer{index}")
        self._barrier = Barrier(2)
        self._index = index
        self._callback = callback
        self._stop = False
        Thread(target=self._run).start()

    def _run(self):
        self._dejavu = Dejavu(dburl=f"sqlite:///bells{self._index}.sqlite")
        while not self._stop:
            self._barrier.wait()
            self._recognize()

    def recognize(self):
        self._barrier.wait()

    def _recognize(self):
        song = self._dejavu.recognize(MicrophoneRecognizer,
                                      seconds=_listen_seconds,
                                      channels=1)
        if song:
            sound = Sound(song['song_id'])
            confidence = song['confidence']
            self._callback(sound, confidence)

    def close(self):
        self._stop = True
        self._barrier.abort()
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
Esempio n. 10
0
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)
Esempio n. 11
0
class Lilo():
    """
    The class for JamJar which will be used to identify video matches and add fingerprints to the database
    """

    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 recognize_track(self):
        # Try to match the song to the existing database
        hashes, songs = self.djv.recognize(FileRecognizer, self.filename)

        self.hashes = hashes

        return songs

    def fingerprint_song(self):
        # Now let's add this song to the DB
        data = self.djv.fingerprint_file(self.filename, self.video_id, cached_hashes=self.hashes)
        return data

    def check_if_fingerprinted(self):
        video_hash = unique_hash(self.filename)
        # Set self.djv.songhashes_set
        fingerprinted_video_hashes = self.djv.get_fingerprinted_songs()
        return video_hash in self.djv.songhashes_set
Esempio n. 12
0
def recognise_microphone():
    djv = Dejavu(config)
    secs = 10
    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)
Esempio n. 13
0
def main():
    # Set up our commang line arguments
    parser = argparse.ArgumentParser(description="Take in a folder of video and/or audio files and find the alignment"
                                                 "of them all.")
    parser.add_argument("folder",type=str,help="The folder containing your audio and video files, relative to the current directory.")
    args = parser.parse_args()

    # Our DB settings
    config = {
        "database": {
            "host": "127.0.0.1",
            "user": "******",
            "passwd": "root",
            "db": "dejavu"
        }
    }


    # Get the files in our folder
    dir = os.path.expanduser(args.folder)
    files = os.listdir(dir)


    # Set up our dejavu instance
    djv = Dejavu(config)


    # Generate our corpus name - we'll add this functionality later.
    corpus = dir.replace(" ","")
    corpus = corpus.lower()

    # For now, let's just empty the DB before the experiment
    djv.db.empty()

    # Iterate through the files
    for filename in files:
        full_path = os.path.join(dir,filename)

        # For now we'll assume all the files are valid audio or video
        if (os.path.isfile(full_path)):

            print "Attempting to match {0}...".format(filename)

            # Try to match the song to the existing database
            songs = djv.recognize(FileRecognizer, full_path)

            if songs:
                for song in songs:
                    print song
            else:
                print "No matches found."

            print "Adding {0} to database...".format(filename)

            # Now let's add this song to the DB
            djv.fingerprint_file(full_path)

            print djv.db.get_num_fingerprints()
Esempio n. 14
0
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")
Esempio n. 15
0
 def dejavu(self, select_song):
     # config = {"database": {"host": "127.0.0.1", "user": "******", "passwd": "", "db": "dejavu"}}
     config = {"database": {"host": "10.66.31.157", "user": "******", "passwd": "662813", "db": "dejavu"}}
     djv = Dejavu(config)
     # djv.fingerprint_directory("mp3/Piano/", [".mp3"])
     # djv.fingerprint_directory("mp3/Violin/", [".mp3"])
     song = djv.recognize(FileRecognizer, select_song)
     # print(song)
     return song
Esempio n. 16
0
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)
class RecognizerService:
    def __init__(self, database_path):
        self.database_path = database_path
        self.dburl = os.getenv('DATABASE_URL',
                               'sqlite:///' + self.database_path)
        self.djv = Dejavu(dburl=self.dburl)

    def recognize(self, filename, dir='uploads/'):
        str_path = dir + filename
        return self.recognize_file_path(str_path)

    def finger_print(self, filename_path):
        self.djv.fingerprint_file(filename_path)
        return self.recognize_file_path(filename_path)

    def recognize_file_path(self, file_path):
        match_list = self.djv.recognize(FileRecognizer, file_path)
        result = list(match_list)
        return result

    def recognize_stream(self, filename, dir='uploads/'):
        str_path = dir + filename
        return self.stream_recognize_file_path(str_path)

    def stream_recognize_file_path(self, file_path):
        match_list = self.djv.recognize(FileRecognizer, file_path)
        return match_list
        # for match in match_list:
        #     yield match

    def nonblocking_recognize_file_path(self, file_path, ws):
        r = FileRecognizer(self.djv)
        frames, r.Fs = decoder.read_chunks(file_path, r.dejavu.limit)
        for i, val in enumerate(frames):
            match = r._recognize(*val)
            if match is not None:
                match['segment_id'] = i
                match['start_time'] = i * ChunksTime / 1000
                ws.write_message(json.dumps(match))
            else:
                ws.write_message(json.dumps({}))
Esempio n. 18
0
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)
Esempio n. 19
0
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)
Esempio n. 20
0
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')
Esempio n. 21
0
def __main1():
    # create a Dejavu instance
    djv = Dejavu(config)

    # Fingerprint all the mp3's in the directory we give it
    djv.fingerprint_directory("seed", [".wav"])

    #print djv.db.get_num_fingerprints()
    #print "----------------------------17---------"

    fp = open('result'+'.dat','w+')
    # Recognize audio from a file

    prefix ='mp3'

    start =  time.clock()
    totalNumSong = 0
    rightNum = 0
    missNum = 0
#     for root, dirs, files in os.walk(prefix):
#         for dirx in dirs:
#             fp.write('%s\n'%dirx)
    print "-------------------------------------"
    fp.write("--Recognizing-----------------------------------\n")
    for filename in glob.glob(prefix+'/*.wav'):
        #print filename
#         filenamex= os.path.basename(filename).replace('.wav','')
        song = djv.recognize(FileRecognizer, filename)
        totalNumSong += 1
        if not song is None:
            txtBuffer = "%s; %s"%(filename, filter(str.isalpha, song['song_name']))
            if filename[5:7] in filter(str.isalpha, song['song_name']):
                rightNum += 1
        else:
            txtBuffer =  "%s; None"%(filename)
            missNum +=1 
        fp.write(txtBuffer+'\n')
        print txtBuffer
        

    end=time.clock()
    
    fp.write("--Performance-----------------------------------\n")
    fp.write("Prediction time duration: %f seconds\n"%(end-start))
    fp.write("Total number of predicted songs: %d \n"%totalNumSong)
    fp.write("Prediction duration per song: %f seconds\n"%(float(end-start)/float(totalNumSong)))
    fp.write("Correct rate: %f %% \n"%(float(rightNum)/float(totalNumSong)*100))
    fp.write("No result rate: %f %%\n"%(float(missNum)/float(totalNumSong)*100))
    fp.close()
Esempio n. 22
0
def scan_directory(directory, extension):
    if extension.endswith('.mp3'):
        print('scanning directory...'.format(directory))
        djv = Dejavu(config)
        djv.fingerprint_directory(directory, [extension], 3)  # 3 is processes
    elif extension.endswith('.m4a'):
        print('scanning directory...'.format(directory))
        djv = Dejavu(config)
        djv.fingerprint_directory(directory, [extension], 3)  # 3 is processes
    else:
        print("file format '{0}' not coded yet".format(extension))

# recognise mp3
    song = djv.recognize(FileRecognizer, "/home/jonas/Downloads/dejavu/CC.mp3")
    print("found song '%s\n'" % song)
Esempio n. 23
0
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)
Esempio n. 24
0
class Tagger:
    def __init__(self):
        if config.TAG:
            self.djv = Dejavu(config.CONFIG)
            self.sp = SpotifyManager()
            while not self.sp.is_authenticated():
                self.sp.auth()

    def tag(self, dir):
        for filename in os.listdir(dir):
            if os.path.isdir(dir + filename):
                self.tag(dir + filename + '/')
                continue
            if config.TAG:
                if config.VERBOSE:
                    print("Tagging: " + dir + filename)
                song = self.djv.recognize(FileRecognizer, dir + filename)
                song = self.sp.sp.search(q=song['song_name'],
                                         type='track',
                                         limit=1)
                try:
                    song_artist = song['tracks']['items'][0]['artists'][0][
                        'name']
                    song_name = song['tracks']['items'][0]['name']
                    pprint(song_artist + ' - ' + song_name)
                    self.apply_tags(dir + filename, song_artist, song_name)
                except IndexError:
                    print(bcolors.FAIL + "unable to get tags for " + filename +
                          bcolors.ENDC)
                    pass
                except:
                    print(bcolors.FAiL + "Wrong file type: " + filename +
                          bcolors.ENDC)
                    pass
            if config.RENAME:
                r = Renamer()
                r.rename(dir + filename, dir)
        pass

    def apply_tags(self, song, artist, name):
        try:
            f = mutagen.File(song)
            f.tags.get('TPE1').text[0] = artist
            f.tags.get('TIT2').text[0] = name
            f.save()
        except AttributeError as e:
            print(bcolors.FAIL + e.message + bcolors.ENDC)
Esempio n. 25
0
def detectar_sonido(nombre_archivo):

    # load config from a JSON file (or anything outputting a python dictionary)
    with open(settings.BASE_DIR + "/dejavu.cnf.SAMPLE") as f:
        config = json.load(f)

    djv = Dejavu(config)

    # # Fingerprint all the mp3's in the directory we give it
    # djv.fingerprint_directory("mp3", [".mp3"])

    # Recognize audio from a file
    song = djv.recognize(
        FileRecognizer,
        settings.BASE_DIR + "/archivos_reconocer/" + nombre_archivo + ".mp3")
    print "From file we recognized: %s\n" % song

    ####una vez detectado hay que eliminar el archivo
    archivo = settings.BASE_DIR + "/archivos_reconocer/" + nombre_archivo + ".mp3"
    os.remove(archivo)

    ##debo notificar al afiliado sobre su nueva cancion por medio de una notificacion push
    push_service = FCMNotification(api_key=settings.FCM_APIKEY)
    token, datos = nombre_archivo.split('_')

    try:
        usuario = Token.objects.get(key=token)

        usuario_token = TokensFCM.objects.get(usuario=usuario.user)

        registration_id = usuario_token.token
        message_title = "Nueva canción detectada"
        message_body = "Hola " + usuario.user.username + " la canción que estabas escuchando es " + song[
            'song_name']
        result = push_service.notify_single_device(
            registration_id=registration_id,
            message_title=message_title,
            message_body=message_body)

    except Token.DoesNotExist:
        pass
    except TokensFCM.DoesNotExist:
        pass

    return song
Esempio n. 26
0
def match_file():

    if request.method == 'POST':
        print(str(request))
        file = request.files['uploaded_file']

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['TEMP_FOLDER'], filename))

            FILEPATH = TEMP_FOLDER + filename

            #Initializing Dejavu object with config
            djv = Dejavu(config)

            #Passing sample clip for retrieving the original track
            matched_track = djv.recognize(FileRecognizer, FILEPATH)
            print(matched_track)

            #Retrieve AdContent of the matched_track
            adcontent = getAdContent(matched_track['song_id'])

            response = {
                "song_id": matched_track['song_id'],
                "song_name": matched_track['song_name'],
                "match_time": matched_track['match_time'],
                "confidence": matched_track['confidence'],
                "brand": adcontent[3],
                "offertitle": adcontent[2],
                "offercontent": adcontent[4],
                "offerimage": adcontent[5],
                "offerlink": adcontent[6],
                "offerid": adcontent[0]
            }

            print(jsonify(response))
            #Delete temporary sample clip
            os.remove(FILEPATH)

            #Return response to API caller in JSON format
            return jsonify(response)

    return render_template('match.html')
Esempio n. 27
0
def song_rater(rec_audio):
    """
	Receive recorded audio and returns song name and confidence level
	"""
    # Create a Dejavu instance
    djv = Dejavu(config)

    # Create the directory if not found
    if not os.path.exists(BASE_DIR + "/rater/mp3"):
        os.makedirs(BASE_DIR + "/rater/mp3")

    file_dir = BASE_DIR + "/rater/mp3"

    # Fingerprint all the mp3's in the directory given which is mp3
    djv.fingerprint_directory(file_dir, [".mp4"])

    song = djv.recognize(FileRecognizer, rec_audio)
    print("From file we recognized: %s\n" % song)

    return song['song_name'], song['confidence']
Esempio n. 28
0
def dejavu_match_service(file_path):

    config= {
        "database": {
            "host": "127.0.0.1",
            "user": "******",
            "passwd": "root",
            "db": "dejavu2"
        }
    }

    djv = Dejavu(config)
    song = djv.recognize(FileRecognizer, file_path)
    result = {}
    if song != None:
    # {'guanghuisuiyue': {'end_pos': 96160, 'match_rate': 0.804, 'match_times': 181, 'start_pos': 91660, 'samedis': 820}}
    # {'song_id': 1, 'song_name': 'guanghuisuiyue', 'file_sha1': '3349023A0823907E12DC7CD76A20817C5DF977A8', 'confidence': 186, 'offset_seconds': 0.04644, 'match_time': 0.5880670547485352, 'offset': 1}
        result={song['song_name']:{'end_pos': -1, 'match_rate': -1, 'match_times': -1, 'start_pos': int ("%d" % song['offset_seconds']), 'samedis': -1}}

    print file_path.split('/')[-1]+":",song
    return result
Esempio n. 29
0
def mp_worker(urldata):
    url=None
    number=None
    song=None
    name =None
    try:
        url, number=urldata
        name= number+'.mp3'
    except ValueError:
        pass
    try:
        u=urllib.request.urlopen(url)
        data=u.read(90000)
        with open(os.path.join(save_path,name),'wb') as file:
            file.write(data)
        time.sleep(1)
    except Exception as e:
        print (e)
    try:
        djv = Dejavu(config)
        song = djv.recognize(FileRecognizer, os.path.join(save_path,name))
        # print("From Stream we recognized: {}\n".format(song))
        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)
            print("From file we recognized: {} {}\n".format(song["song_name"], count))
            with open(os.path.join(save_path,'log2.txt'),'a') as writeFile:
                writeFile.write("\n High confidence %d %s FileName=%s" %(song['confidence'],song["song_name"],name))
        else:
            print("Low confidence %d" %song['confidence'])
            with open(os.path.join(save_path,'log2.txt'),'a') as writeFile:
                writeFile.write("\n Low confidence %d %s FileName=%s" %(song['confidence'],song["song_name"],name))
    except Exception as e:
        print(e)
Esempio n. 30
0
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)

    if song["song_id"] == 1:
        id = Label(frm, text='Your song:  ' + song['song_name'])
        id.pack(side=TOP)
        recommend = Label(frm, text='Recommended songs:')
        recommend.pack(side=TOP)
        recommend1 = Label(frm, text='Stressed Out - Twenty One Pilots')
        recommend1.pack(side=TOP)
        recommend2 = Label(frm, text='Closer - The Chainsmokers')
        recommend2.pack(side=TOP)
Esempio n. 31
0
def recognize():
    if request.method == 'POST':
        app.logger.debug('A POST request was made')
        file = request.files['file']
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            app.logger.debug('file was nil')
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(UPLOADS_PATH, filename))

            djv = Dejavu(config)
            song = djv.recognize(FileRecognizer, UPLOADS_PATH + '/' + filename)
            return "%s" % song

    app.logger.debug('A GET request was made')
    return '''
def recognize_song():
    print("=" * 50)
    print("List uploaded files: {}".format(request.files.getlist('uploaded_file')))
    files = request.files.getlist('uploaded_file')

    artist = ""
    title = ""

    if files and len(files) > 0:
        print("\t Reading song uploaded ...")        
        # Read song from parameters -> download it as mp3 file    
        b = io.BytesIO(files[0].read())
        song = AudioSegment.from_file(b, format="3gp")

        song.export(FILE_PATH, format="mp3")

        print("\t File song read\n\t Song recognition started...")        
        # create a Dejavu instance
        djv = Dejavu(config)

        # Recognize audio from a file
        song_found = djv.recognize(FileRecognizer, FILE_PATH)

        print("\t Song recognition finished")

        if song_found: 
            song_name = song_found.get('song_name').split("--")
            artist = song_name[0]
            title = song_name[1]
            print("\t Song:\n\t\t - Music: {}\n\t\t - Artist: {}".format(title, artist))        


    print("\t Return response")        
    print("=" * 50)
    return jsonify({
        'artist': artist,
        'title': title
        })
Esempio n. 33
0
    def recognize(self, samples_patch, downloads_patch, file_format):
        self.samples_patch = samples_patch
        self.downloads_patch = downloads_patch
        self.file_format = file_format
        self.var_check()
        warnings.filterwarnings('ignore')
        with open('dejavu.conf') as f:
            config = json.load(f)
        djv = Dejavu(config)

        # -= updating audio fingerprint base =-
        print ('%s > Updating fingerprints...' % datetime.datetime.now())
        djv.fingerprint_directory(self.samples_patch, [self.file_format])

        # -= recognizing downloaded files =-
        print ('%s > Recognizing files...' % datetime.datetime.now())
        for i in range(len(names)):
            file = self.downloads_patch + '/' + names[i]
            print ('%s > Now recognizing: %s' % (datetime.datetime.now(), names[i]))
            song = djv.recognize(FileRecognizer, file)
            recognized.append(song['song_name'])
            print ('%s > From file we recognized: %s' % (datetime.datetime.now(), recognized[i]))
        print ('%s > Finished!' % datetime.datetime.now())
Esempio n. 34
0
class Lilo():
    """
    The class for JamJar which will be used to identify video matches and add fingerprints to the database
    """
    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 recognize_track(self):
        # Try to match the song to the existing database
        hashes, songs = self.djv.recognize(FileRecognizer, self.filename)

        self.hashes = hashes

        return songs

    def fingerprint_song(self):
        # Now let's add this song to the DB
        data = self.djv.fingerprint_file(self.filename,
                                         self.video_id,
                                         cached_hashes=self.hashes)
        return data

    def check_if_fingerprinted(self):
        video_hash = unique_hash(self.filename)
        # Set self.djv.songhashes_set
        fingerprinted_video_hashes = self.djv.get_fingerprinted_songs()
        return video_hash in self.djv.songhashes_set
Esempio n. 35
0
def __main(action):
    # create a Dejavu instance
    djv = Dejavu(config)

    # Fingerprint all the mp3's in the directory we give it
    djv.fingerprint_directory("mp3", [".wav"])

    #print djv.db.get_num_fingerprints()
    #print "----------------------------17---------"

    fp = open(action+'.dat','w+')
    # Recognize audio from a file
    #prefix ='..\sdl\%s'%action
    prefix ='mp3\%s'%action
    files = prefix +'\*.mp3'
    totalNumSong = 0
    start =  time.clock()
    for filename in glob.glob(files):
        #print filename
        filenamex= filename.split('\\')[-1]
        filenamex=filenamex[7:-4]
        song = djv.recognize(FileRecognizer, filename)
        totalNumSong += 1
        if not song is None:
            txtBuffer = "%s;%s"%(filenamex, song['song_name'])
        else:
            txtBuffer =  "%s;None"%(filenamex)
        fp.write(txtBuffer+'\n')
        print txtBuffer

    end=time.clock()
    fp.write("----------------------------60---------\n")
    fp.write("Prediction time duration: %f \n"%(end-start))
    fp.write("Total number of predicted songs: %d \n"%totalNumSong)
    fp.write("Prediction duration for per song: %f \n"%(float(end-start)/float(totalNumSong)))
    fp.close()
Esempio n. 36
0
# create a Dejavu instance
djv = Dejavu(config)

# Recognize audio from a file
from dejavu.recognize import FileRecognizer
#filename = "20141106_204003"
filename = sys.argv[1]
import globP
if globP._XDEBUG == True:
    import pdb
    pdb.set_trace()
#txtFileName = 'songList.txt'
#prefix ='./mp3t/Living_'
prefix ='./mp3t/'
suffix ='.mp3'
fullFilename=prefix+filename+suffix
#print fullFilename
if os.path.exists(fullFilename):
    song = djv.recognize(FileRecognizer, fullFilename)
    if not song is None:
        print "36 --  %s \t %s "%(filename, song['song_name'] )
    else:
        print "38 --  %s \t None "%(filename)

print song

print "----------------------------39-- dbInfor()-------"
from dbRefresh import dbInfor
dbInfor()
Esempio n. 37
0
__author__ = 'Mark'
from dejavu import Dejavu
from dejavu.recognize import MicrophoneRecognizer

if __name__ == '__main__':
    config = {
        "database": {
            "host": "127.0.0.1",
            "user": "******",
            "passwd": "root",
            "db": "dejavu"
        }
    }

    djv = Dejavu(config)

    song = djv.recognize(MicrophoneRecognizer, seconds=5) # Defaults to 10 seconds.

    print song
Esempio n. 38
0
import warnings
import json
warnings.filterwarnings("ignore")

from dejavu import Dejavu
from dejavu.recognize import FileRecognizer, MicrophoneRecognizer

# load config from a JSON file (or anything outputting a python dictionary)
with open("dejavu.cnf.SAMPLE") as f:
    config = json.load(f)

if __name__ == '__main__':

	# create a Dejavu instance
	djv = Dejavu(config)

	# Recognize audio from a file
	song = djv.recognize(FileRecognizer, "mp3/Sean-Fournier--Falling-For-You.mp3")
	print "From file we recognized: %s\n" % song
Esempio n. 39
0
# -*- coding: utf-8 -*-

import json
import warnings
from dejavu import Dejavu
from dejavu.recognize import FileRecognizer

warnings.filterwarnings('ignore')
with open('dejavu.conf') as f:
    config = json.load(f)
djv = Dejavu(config)

song = djv.recognize(FileRecognizer, 'mp3_downloads/At Vance - Flight Of The Bumblebee.mp3')

print (song['song_name'])

"""
# user-agent randomizer

from random import randint

patch = 'user-agent.list'
i = 0
f = open(patch, 'r')
for line in f:
    i += 1
f.close()
line_number = randint(0, i-1)
f = open(patch, 'r')
tmp = f.readlines()[line_number]
f.close()
Esempio n. 40
0
class Recognize(object):
    
    """
        This class runs the audio fingerprinting algorithm to find matches of commercials in the audio.
    """

    def __init__(self, video_name):
        
        """
           Takes the video name. Creates a Dejavu object.
           Also obtains the duration and number of frames in the video.
        """
        
        file_type = mimetypes.guess_type(video_name)[0]
        
        if file_type[:3] != "vid":#The file is not a video file
            print "No video file found"
            raise Exception(INCORRECT_VIDEO_FILE_ERROR)
        
        self.video_name = video_name
        self.djv = Dejavu(CONFIG)
        
        #We create the audio of the video given to us
        ffmpeg.create_audio(self.video_name, TEMP_AUDIO)
        self.frames, self.Fs, hash_val = decoder.read(TEMP_AUDIO)
        self.frames = self.frames[0] #Since we always create single channel audio
        self.duration = int(self.frames.shape[0] / (self.Fs*1.0)) #Duration of the entire video in seconds
        
    def find_commercial(self, start, span=VIDEO_SPAN):
        
        """
            Uses audio fingerprinting to detect known commercials
            Returns:
                If commercial is detected it returns the following:
                    [end_time, [actual_start of commercial, duration of commercial]]
                If no commercial is found
                    [start(the value that was passed), []]
        """
        
        data = np.copy(self.frames[start*self.Fs:(start+span)*self.Fs]) #Obtain frames between the desired locations
        song = self.djv.recognize(DataRecognizer, [data]) #Call dejavu to audio fingerprint it and find a match
        
        if song is None:
            #No match was found in the db
            return [start, []] #We can safely skip
            
        if song[DJV_CONFIDENCE] >= CONFIDENCE_THRESH:
            #A high confidence match was found
            
            if song[DJV_OFFSET] < 0:
                #Offset can never be greater than duration of detected commercial
                return [start, []]
            
            #song[DJV_OFFSET] contains the time duration of the original song, which the segment matched
                            
            #obtain the start of the commercial
            start -= song[DJV_OFFSET]
            start = int(start)
            
            #Read the database to obtain the end time of the commercial
            #This is the line containing the db details
            #We subtract 1, since by default audio/ and video/ have .temp folder in them
            
            index = int(song[DJV_SONG_NAME]) - 1 
            
            #Obtain the name and duration of the detected segment
            name, duration = DatabaseFile(DBNAME).get_line(index)
            
            if duration < song[DJV_OFFSET]:
                #The offset where it is found cannot exceed the duration of the song
                return [start, []]
            
            end = start + duration
                      
            return [end, [start, name]]
        else:
            #A match was found, but not a confident match
            return [start, []]
            
    def recognize(self):
        
        labels = LabelsFile(outfile=OUTPUT) 
        print "Now detecting commercials.."
        i = 0
        prev = 0
        while i < self.duration:
            
            #Pretty printing
            remaining_time = self.duration - i
            sys.stdout.write('\r')
            sys.stdout.write("Duration of video pending analysis: %s" % timeFunc.get_time_string(remaining_time))
            sys.stdout.flush()
            
            next, data = self.find_commercial(i)
            
            #data is an empty list when there is no commercial            
            if len(data) != 0:
                #If commercial is detected
                start = data[0]
                name = data[1]
                i = next + (VIDEO_GAP / 2)
                
                #prev = the end time of the last add that was detected
                if (start - prev) >= VIDEO_SPAN:
                    #If greater than the amount to scan, has to be marked unclassified
                    labels.write_labels([timeFunc.get_time_string(prev), timeFunc.get_time_string(start), UNCLASSIFIED_CONTENT])
                else:
                    start = prev #We safely skip
                
                prev = next   
                
                #We mark the commercial detected
                labels.write_labels([timeFunc.get_time_string(start), timeFunc.get_time_string(next), name])                     
            
            else:
                #No commercial, proceed scanning
                i += VIDEO_GAP
        print
                
        if (self.duration - prev) > 1: #Atleast one second
            labels.write_labels([timeFunc.get_time_string(prev), timeFunc.get_time_string(self.duration), UNCLASSIFIED_CONTENT])
                                    
    def __del__(self):
        
        print "Removing the audio generated for the video.."
        os.remove(TEMP_AUDIO)
Esempio n. 41
0
warnings.filterwarnings("ignore")

# load config from a JSON file (or anything outputting a python dictionary)
with open("dejavu.cnf.SAMPLE") as f:
    config = json.load(f)


if __name__ == '__main__':
    # create a Dejavu instance
    djv = Dejavu(config)

    # Fingerprint all the mp3's in the directory we give it
    djv.fingerprint_directory("mp3", [".mp3"])

    # Recognize audio from a file
    song = djv.recognize(FileRecognizer, "mp3/microwave.mp3")
    print "From file we recognized: {}".format(song)

    # Or recognize audio from your microphone for `secs` seconds
    # secs = 3
    # 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 {} seconds we recognized: {}".format(secs, song)

    # Or use a recognizer without the shortcut, in anyway you would like
    # recognizer = FileRecognizer(djv)
    # song = recognizer.recognize_file("mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
    # print "No shortcut, we recognized: {}".format(song)
Esempio n. 42
0
from dejavu import Dejavu
import warnings
import json
warnings.filterwarnings("ignore")

# 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
djv = Dejavu(config)
# Fingerprint all the mp3's in the directory we give it
djv.fingerprint_directory("mp3", [".mp3"])

# Recognize audio from a file
from dejavu.recognize import FileRecognizer
song = djv.recognize(FileRecognizer, "mp3/beware.mp3")

# Or recognize audio from your microphone for 10 seconds
from dejavu.recognize import MicrophoneRecognizer
song = djv.recognize(MicrophoneRecognizer, seconds=2)

# Or use a recognizer without the shortcut, in anyway you would like
from dejavu.recognize import FileRecognizer
recognizer = FileRecognizer(djv)
song = recognizer.recognize_file("mp3/sail.mp3")
Esempio n. 43
0
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                yield filename

# gather files to fingerprint /configura el directorio donde estaran alojadas las pistas a comparar
# UNLABELED_AUDIO_DIR = "./lockon/"
#UNLABELED_AUDIO_DIR = "./mp3/http:/216.55.186.61:8071"
UNLABELED_AUDIO_DIR = "/home/nego/Escritorio/mp3/"
PATTERN = "*.mp3"
audio_paths = find_files(UNLABELED_AUDIO_DIR, PATTERN)

# recognize them one at a time
original_file_to_song = {}
for path in audio_paths:
    print "Attempting to recognize %s..." % path
    song = djv.recognize(FileRecognizer, path)
    original_file_to_song[path] = song

#print "Audio file at: %s was recognized as %s" % (path, song)
# see the songs you've recognized
for path, song in original_file_to_song.iteritems():
    print "Audio file at: %s was recognized as %s \n" % (path, song)

#resultado para reporte
cadenaReporte='Pista objetivo, Firma Identificada, Id de pista, Confianza, Inicio de firma, Alineacion \n'

# path es la llave del diccionario en original_file... cuyo valor corresponde al nombre de la cancion escaneada, y song es el valor de la llave del mismo diccionario cuyo valor corresponde al resultado del reconocimiento 
for objetivo,result in original_file_to_song.iteritems():
	
	# pista objetivo
	songObj='%s,' % objetivo
Esempio n. 44
0
__author__ = 'Mark'
from dejavu import Dejavu
from dejavu.recognize import FileRecognizer

if __name__ == '__main__':
    config = {
        "database": {
            "host": "127.0.0.1",
            "user": "******",
            "passwd": "root",
            "db": "dejavu",
        }
    }

    djv = Dejavu(config)

    songs = djv.recognize(FileRecognizer,
                          "../../../Desktop/media/jeff_alliy_clipped.wav")

    for song in songs:
        print song
from dejavu.logic.recognizer.microphone_recognizer import MicrophoneRecognizer

# load config from a JSON file (or anything outputting a python dictionary)
with open("dejavu.cnf.SAMPLE") as f:
    config = person.load(f)

if __name__ == '__main__':

    # create a Dejavu instance
    djv = Dejavu(config)

    # Fingerprint all the mp3's in the directory we give it
    djv.fingerprint_directory("test", [".wav"])

    # Recognize audio from a file
    results = djv.recognize(FileRecognizer, "mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
    print(f"From file we recognized: {results}\n")

    # Or recognize audio from your microphone for `secs` seconds
    secs = 5
    results = djv.recognize(MicrophoneRecognizer, seconds=secs)
    if results is None:
        print("Nothing recognized -- did you play the audio out loud so your mic could hear it? :)")
    else:
        print(f"From mic with {secs} seconds we recognized: {results}\n")

    # Or use a recognizer without the shortcut, in anyway you would like
    recognizer = FileRecognizer(djv)
    results = recognizer.recognize_file("mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
    print(f"No shortcut, we recognized: {results}\n")
Esempio n. 46
0
        "-s",
        "--secs",
        help="how many seconds to fingerprint for recognition",
        type=int)

args = parser.parse_args()

# load config from a JSON file (or anything outputting a python dictionary)
config = {
    "database": {
        "host": "127.0.0.1",
        "user": "******",
        "passwd": "", 
        "db": "dejavu"
    }
}

if args.secs:
    config["fingerprint_limit"] = args.secs

if __name__ == '__main__':

        # create a Dejavu instance
        djv = Dejavu(config)

        # Recognize audio from a file
        print("start recognizing")
        with Timer("djv.recognize") as t:
            song = djv.recognize(FileRecognizer, args.file)
        print("From file we recognized: %s\n" % song)
Esempio n. 47
0
}

# load config from a JSON file (or anything outputting a python dictionary)
#with open("dejavu.cnf.SAMPLE") as f:
#    config = json.load(f)

if __name__ == '__main__':

	# create a Dejavu instance
	djv = Dejavu(config)

	# Fingerprint all the mp3's in the directory we give it
	djv.fingerprint_directory("mp3", [".mp3"])

	# Recognize audio from a file
	song = djv.recognize(FileRecognizer, "mp3/Sean-Fournier--Falling-For-You.mp3")
	print "From file we recognized: %s\n" % song

	# Or recognize audio from your microphone for `secs` seconds
	secs = 5
	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)

	# Or use a recognizer without the shortcut, in anyway you would like
	recognizer = FileRecognizer(djv)
	song = recognizer.recognize_file("mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
	print "No shortcut, we recognized: %s\n" % song
Esempio n. 48
0
import warnings
import json
warnings.filterwarnings("ignore")

from dejavu import Dejavu
from dejavu.recognize import FileRecognizer, MicrophoneRecognizer

# load config from a JSON file (or anything outputting a python dictionary)
with open("dejavu.cnf.SAMPLE") as f:
    config = json.load(f)

if __name__ == '__main__':

	# create a Dejavu instance
	djv = Dejavu(config)

	# Fingerprint all the mp3's in the directory we give it
	#djv.fingerprint_directory("./firmas", [".mp3"])

	# Recognize audio from a file.
	song = djv.recognize(FileRecognizer, "/home/nego/Escritorio/mp3/2016-mie-abr-27-1807.mp3")
	print "From file we recognized: %s\n" % song

	# Or recognize audio from your microphone for `secs` seconds

Esempio n. 49
0
__author__ = 'Mark'
from dejavu import Dejavu
from dejavu.recognize import FileRecognizer

if __name__ == '__main__':
    config = {
        "database": {
            "host": "127.0.0.1",
            "user": "******",
            "passwd": "root",
            "db": "dejavu",
        }
    }

    djv = Dejavu(config)

    songs = djv.recognize(FileRecognizer, "../../../Desktop/media/jeff_alliy_clipped.wav")

    for song in songs:
        print song
Esempio n. 50
0
from dejavu import Dejavu
from dejavu.recognize import MicrophoneRecognizer

config = {
    "database": {
        "host": "127.0.0.1",
        "user": "******",
        "passwd": '',
        "db": 'songpop',
    }
}
djv = Dejavu(config)

djv.fingerprint_directory("mp3", [".mp3"])

song = djv.recognize(MicrophoneRecognizer, seconds=10)
print(song)
Esempio n. 51
0
    blinkLed(10)
    if check_vpn() is not None:
        config = getConguration()
        djv = Dejavu(config)
        djv.create_session(config["fingerprint"]["id"], config["vpn_ip"], config["remote_ip"])
        djv.log_event("action", "boot")
        atexit.register(exit_handler, djv)
        if __name__ == "__main__":
            a = datetime.now()
            listen = 1
            pause = 0.5
            it = 1
            try:
                while True:
                    blinkLed(2)
                    song = djv.recognize(MicrophoneRecognizer, seconds=listen)
                    if song is not None:
                        djv.log_event("match", str(song["song_id"]))
                        print "Recognized %s\n" % (song)
                        blinkLed(5)
                    it += 1
                    time.sleep(pause)
            except KeyboardInterrupt:
                pass
    else:
        print "No vpn connection"

except MySQLdb.Error, e:
    djv.log_event("mysql_error", str(e.args[1]))
    sys.exit(1)
Esempio n. 52
0
# load config from a JSON file (or anything outputting a python dictionary)
config = {
    "database": {
        "host": "db",
        "user": "******",
        "password": "******",
        "database": "dejavu"
    },
    "database_type": "postgres"
}

if __name__ == '__main__':

    # create a Dejavu instance
    djv = Dejavu(config)

    # Fingerprint all the mp3's in the directory we give it
    djv.fingerprint_directory("test", [".wav"])

    # Recognize audio from a file
    results = djv.recognize(
        FileRecognizer,
        "mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
    print(f"From file we recognized: {results}\n")

    # Or use a recognizer without the shortcut, in anyway you would like
    recognizer = FileRecognizer(djv)
    results = recognizer.recognize_file(
        "mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
    print(f"No shortcut, we recognized: {results}\n")
Esempio n. 53
0
# mysql: 'mysql+mysqldb://scott:tiger@localhost/foo'
# postgresql: 'postgresql://*****:*****@localhost/mydatabase'
# sqlite: 'sqlite:///foo.db'
# in memory sqlite:  'sqlite://'

config = {
    "database_backend" : "orm",
    "database_uri": "sqlite:///fingerprints.sqlite",
    "fingerprint_limit" : 10,
}

# previous backend can still be used:
# config = {
#     "database_backend" : "plain",
#     "database": {
#         "host": "127.0.0.1",
#         "user": "",
#         "passwd": "",
#         "db": "",
#     },
#     "fingerprint_limit": 10,
# }


# create a Dejavu instance
djv = Dejavu(config)

# Recognize audio from a file
song = djv.recognize(FileRecognizer, "tests/test1.mp3")
print song
Esempio n. 54
0
def main():
    # Set up our commang line arguments
    parser = argparse.ArgumentParser(
        description=
        "Take in a folder of video and/or audio files and find the alignment"
        "of them all.")
    parser.add_argument(
        "folder",
        type=str,
        help=
        "The folder containing your audio and video files, relative to the current directory."
    )
    args = parser.parse_args()

    # Our DB settings
    config = {
        "database": {
            "host": "127.0.0.1",
            "user": "******",
            "passwd": "root",
            "db": "dejavu"
        }
    }

    # Get the files in our folder
    dir = os.path.expanduser(args.folder)
    files = os.listdir(dir)

    # Set up our dejavu instance
    djv = Dejavu(config)

    # Generate our corpus name - we'll add this functionality later.
    corpus = dir.replace(" ", "")
    corpus = corpus.lower()

    # For now, let's just empty the DB before the experiment
    djv.db.empty()

    # Iterate through the files
    for filename in files:
        full_path = os.path.join(dir, filename)

        # For now we'll assume all the files are valid audio or video
        if (os.path.isfile(full_path)):

            print "Attempting to match {0}...".format(filename)

            # Try to match the song to the existing database
            songs = djv.recognize(FileRecognizer, full_path)

            if songs:
                for song in songs:
                    print song
            else:
                print "No matches found."

            print "Adding {0} to database...".format(filename)

            # Now let's add this song to the DB
            djv.fingerprint_file(full_path)

            print djv.db.get_num_fingerprints()
Esempio n. 55
0
class songListener(threading.Thread):
    """This class listens for songs in a background thread using the Dejavu audio 
    fingerprinter. When it hears a song it sets global flags"""

    global chickenDance
    global robotDance
    global discoDance
    global egyptianDance
    global ymcaDance
    global danceStop

    def __init__(self, config):
        threading.Thread.__init__(self)
        #Initialize the dejavu listener
        self.djv = Dejavu(config) 
        self.running = True

    def run(self):
        global chickenDance
        global robotDance
        global discoDance
        global egyptianDance
        global ymcaDance
        global danceStop
        #do the listening
        while(self.running):

            response = self.djv.recognize(MicrophoneRecognizer, seconds=5)
            if(response == None):
                continue

            if(response["confidence"] > 30 and response["song_name"] == "chickenDance") and (not (robotDance or discoDance or egyptianDance or ymcaDance)):
                print "Found " + response["song_name"]
                print "Confidence: " + str(response["confidence"]) + " units"
                chickenDance = True
                danceStop = False
                

            elif(response["confidence"] > 30 and response["song_name"] == "technologic") and (not (chickenDance or discoDance or egyptianDance or ymcaDance)):
                print "Found " + response["song_name"]
                print "Confidence: " + str(response["confidence"]) + " units"
                robotDance = True
                danceStop = False

            elif(response["confidence"] > 30 and response["song_name"] == "stayingAlive") and (not (chickenDance or robotDance or egyptianDance or ymcaDance)):
                print "Found " + response["song_name"]
                print "Confidence: " + str(response["confidence"]) + " units"
                discoDance = True
                danceStop = False

            elif(response["confidence"] > 30 and response["song_name"] == "walkLikeAnEgyptian") and (not (chickenDance or robotDance or discoDance or ymcaDance)):
                print "Found " + response["song_name"]
                print "Confidence: " + str(response["confidence"]) + " units"
                egyptianDance = True
                danceStop = False

            elif(response["confidence"] > 30 and response["song_name"] == "YMCA") and (not (chickenDance or robotDance or discoDance or egyptianDance)):
                print "Found " + response["song_name"]
                print "Confidence: " + str(response["confidence"]) + " units"
                ymcaDance = True
                danceStop = False

            else:
                chickenDance = False
                robotDance = False
                discoDance = False
                egyptianDance = False
                ymcaDance = False

    def stop(self):
        self.running = False