Exemplo n.º 1
0
def music_extractor(audio_file,
                    sig_file,
                    profile=None,
                    store_frames=False,
                    format='yaml'):
    if profile:
        extractor = MusicExtractor(profile=profile)
    else:
        extractor = MusicExtractor()

    poolStats, poolFrames = extractor(audio_file)

    folder = os.path.dirname(sig_file)

    if not os.path.exists(folder):
        os.makedirs(folder)
    elif os.path.isfile(folder):
        raise EssentiaError(
            'Cannot create directory {} .There exist a file with the same name. Aborting analysis.'
            .format(folder))

    output = YamlOutput(filename=sig_file + '.sig', format=format)
    output(poolStats)
    if store_frames:
        YamlOutput(filename=sig_file + '.frames.sig',
                   format=format)(poolFrames)
Exemplo n.º 2
0
def compute_music_extractor_essentia(y, sr=None):
    """compute_music_extractor_essentia

    Compute features using essentia's MusicExtractor
    """
    # l.debug('compute_tempo_beats_essentia y = {0}'.format(y))
    filename = y
    features, features_frames = MusicExtractor(lowlevelStats=['mean', 'stdev'],
                                               rhythmStats=['mean', 'stdev'],
                                               tonalStats=['mean',
                                                           'stdev'])(filename)

    print(type(features))
    # See all feature names in the pool in a sorted order
    print(sorted(features.descriptorNames()))
    # MusicExtractor

    result = dict([(k, features[k])
                   for k in sorted(features.descriptorNames())])

    # # Compute beat positions and BPM
    # rhythm_extractor = RhythmExtractor2013(method="multifeature")
    # bpm, beats, beats_confidence, _, beats_intervals = rhythm_extractor(audio)

    # # print("    BPM:", bpm)
    # # print("    beat positions (sec.):", len(beats))
    # # print("    beat estimation confidence:", beats_confidence)

    # danceability_extractor = Danceability()
    # danceability_full = danceability_extractor(audio)
    # danceability = danceability_full[0]
    # # print("    danceability:", danceability[0])

    # return {'bpm': bpm, 'beats': beats, 'beats_confidence': beats_confidence, 'beats_intervals': beats_intervals, 'danceability': danceability}
    return result  # {'y': y, }
Exemplo n.º 3
0
    def analyze(path, force_predecode=False):
        analysis = SongAnalysis(path)

        dir = '/usr/share/essentia-extractor-svm_models/'
        history_files = [
            os.path.join(dir, x) for x in os.listdir(dir)
            if x.endswith('.history')
        ]

        extractor = MusicExtractor(highlevel=history_files,
                                   lowlevelSilentFrames='keep',
                                   tonalSilentFrames='keep')
        if not force_predecode and any(path.lower().endswith(x)
                                       for x in essentia_allowed_exts):
            print('Extracting song parameters... ', end='', flush=True)
            analysis.stats, analysis.frames = extractor(path)
        else:
            with (tempfile.NamedTemporaryFile(mode='w',
                                              prefix='bard_raw_audio',
                                              suffix='.wav')) as raw:
                print('Predecoding song ... ', end='', flush=True)
                args = ['ffmpeg', '-y', '-i', path, '-ac', '2', raw.name]
                subprocess.run(args, capture_output=True)
                print('Extracting song parameters... ', end='', flush=True)
                analysis.stats, analysis.frames = extractor(raw.name)

        print('done')
        return analysis
Exemplo n.º 4
0
 def analyze_file(self, audio_file):
     extractor = MusicExtractor()
     print("Analyzing %s" % audio_file)
     try:
         poolStats, poolFrames = extractor(audio_file)
     except Exception, e:
         print("Error processing", audio_file, ":", str(e))
         return str(e)
Exemplo n.º 5
0
def analyze_dir(audio_dir,
                output_json=None,
                output_dir=None,
                audio_types=None,
                profile=None,
                store_frames=False,
                include_descs=None,
                ignore_descs=None,
                skip_analyzed=False):
    """
    if args.include and args.ignore and not set(args.include).isdisjoint(args.ignore):
        print 'You cannot specify the same descriptor patterns in both 'include_descs' and --ignore flags'
        sys.exit() # TODO return None instead in this function
    """
    if not output_json and not output_dir:
        print "Error: Neither output json file nor output directory were specified."
        return

    if skip_analyzed and not output_dir:
        print "--skip-analyzed can be only used together with --output-dir flag"
        return

    if skip_analyzed and output_json:
        print "--skip-analyzed cannot be used together with --output_json flag"
        return

    if output_dir:
        output_dir = os.path.abspath(output_dir)

    if not audio_types:
        audio_types = ['*.wav', '*.aiff', '*.flac', '*.mp3', '*.ogg']
        print "Audio files extensions considered by default: " + ' '.join(
            audio_types)
    else:
        print "Searching for audio files extensions: " + ' '.join(audio_types)
    print

    if profile:
        extractor = MusicExtractor(profile=profile)
    else:
        extractor = MusicExtractor()

    # find all audio files
    os.chdir(audio_dir)
    audio_files = []
    for root, dirnames, filenames in os.walk("."):
        for match in audio_types:
            for filename in fnmatch.filter(filenames, match):
                audio_files.append(
                    os.path.relpath(os.path.join(root, filename)))

    # analyze
    errors = 0
    results = {}
    for audio_file in audio_files:
        print "Analyzing", audio_file

        if output_dir:
            sig_file = os.path.join(output_dir, audio_file)
            if skip_analyzed:
                if os.path.isfile(sig_file + ".sig"):
                    print "Found descriptor file for " + audio_file + ", skipping..."
                    continue

        try:
            poolStats, poolFrames = extractor(audio_file)

        except Exception, e:
            print "Error processing", audio_file, ":", str(e)
            errors += 1
            continue

        if output_json:
            results[audio_file] = {}
            results[audio_file]['stats'] = pool_to_dict(
                poolStats, include_descs, ignore_descs)
            if store_frames:
                results[audio_file]['frames'] = pool_to_dict(
                    poolFrames, include_descs, ignore_descs)

        if output_dir:
            folder = os.path.dirname(sig_file)

            if not os.path.exists(folder):
                os.makedirs(folder)
            elif os.path.isfile(folder):
                print "Cannot create directory", folder
                print "There exist a file with the same name. Aborting analysis."
                sys.exit()

            output = YamlOutput(filename=sig_file + '.sig')
            output(poolStats)
            if store_frames:
                YamlOutput(filename=sig_file + '.frames.sig')(poolFrames)
def ac_highlevel_music_description(audiofile, ac_descriptors):
    logger.debug('{0}: running Essentia\'s MusicExtractor'.format(audiofile))
    me_pool, _ = MusicExtractor(
        profile='music_extractor_profile.yaml')(audiofile)
    ac_descriptors["genre"] = me_pool['highlevel.genre_test.value']
    ac_descriptors["mood"] = me_pool['highlevel.mood_test.value']