Exemplo n.º 1
0
def converter(file):
    phrase_size = BAR_SIZE * PHRASE_SIZE
    try:
        midi_md5 = os.path.splitext(
            os.path.basename(os.path.join(MIDI_FILE_PATH, file)))[0]
        multitrack = Multitrack(beat_resolution=BEAT_RESOLUTION, name=midi_md5)

        pm = pretty_midi.PrettyMIDI(os.path.join(MIDI_FILE_PATH, file))
        multitrack.parse_pretty_midi(pm)
        midi_info = get_midi_info(pm)

        length = multitrack.get_max_length()
        padding_size = phrase_size - (
            length % phrase_size) if length % phrase_size else 0
        tmp = length // phrase_size + (1 if length % phrase_size else 0)

        multitrack.clip(0, 127)
        data = multitrack.get_merged_pianoroll(mode='max')

        if padding_size:
            data = np.concatenate((data,
                                   np.array([[0 for _ in range(128)]
                                             for _ in range(padding_size)])),
                                  axis=0)

        data.astype(np.float64)
        data = data / 127.
        data[data < 0.35] = 0.
        data[data >= 0.35] = 1.

        data_by_phrase = []
        phrase_number = [330] + [i for i in range(tmp - 2, -1, -1)]
        for i in range(0, len(data), phrase_size):
            data_by_phrase.append(data[i:i + phrase_size])

        with open(
                os.path.join(NP_FILE_PATH, '{}_{}.pkl'.format(tmp, midi_md5)),
                'wb') as fp:
            pickle.dump([np.array(data_by_phrase), phrase_number], fp)

        return (midi_md5, midi_info)

    except Exception as e:
        print(e)
        return None
def midi2Pianoroll(filepath,
                   merge=True,
                   velocity=False,
                   ):
    """Convert a MIDI file to a multi-track piano-roll and save the
    resulting multi-track piano-roll to the destination directory. Return a
    tuple of `midi_md5` and useful information extracted from the MIDI file.
    """
    midi_md5 = os.path.splitext(os.path.basename(filepath))[0]
    # prettyMIDI = PrettyMIDI(filepath)
    # time_signiture = ""
    # if len(prettyMIDI.time_signature_changes)>0:
    #     time_signiture = "{}/{}".format(prettyMIDI.time_signature_changes[0].numerator,
    #                                     prettyMIDI.time_signature_changes[0].denominator)
    # if time_signiture == "":
    #     raise ValueError(midi_md5 + " no timesigniture")

    # if time_signiture != CONFIG['time_signatures']:
    #     warnings.warn(midi_md5 + "'s timesiniture is " + time_signiture + " != " + CONFIG['time_signatures'])
    #     return None

    multitrack = Multitrack(filepath, beat_resolution=CONFIG['beat_resolution'], name=midi_md5)
    if merge:
        result = multitrack.get_merged_pianoroll(mode="max")
    else:
        result = multitrack.get_stacked_pianoroll()
        right = None
        left = None
        for each_track in multitrack.tracks:
            if each_track.name.strip().lower() == 'piano right':
                right = each_track.pianoroll
            if each_track.name.strip().lower() == 'piano left':
                left = each_track.pianoroll
        if right is None or left is None:
            return None
        result = np.stack([right, left], axis=2)

    if not velocity:
        result = np.where(result > 0, 1, 0)
    else:
        result = result / CONFIG['velocity_high']
    return result
Exemplo n.º 3
0
def midiToPianoroll(filepath,
              merge=True,
              velocity=False,
              ):
    """Convert a MIDI file to a multi-track piano-roll and save the
    resulting multi-track piano-roll to the destination directory. Return a
    tuple of `midi_md5` and useful information extracted from the MIDI file.
    """
    midi_md5 = os.path.splitext(os.path.basename(filepath))[0]
    multitrack = Multitrack(filepath, beat_resolution=CONFIG['beat_resolution'], name=midi_md5)
    if merge:
        result = multitrack.get_merged_pianoroll(mode="max")
    else:
        result = multitrack.get_stacked_pianoroll()

    if not velocity:
        result = np.where(result > 0, 1, 0)
    else:
        result = result / CONFIG['velocity_high']
    return result
Exemplo n.º 4
0
def get_chord_progression_from_file(f_name, debug=False):
    """
    Takes a file name returns a chord progression

    :return ChordProgression
    """

    if debug:
        print("processing: {}".format(f_name))
    mlt = Multitrack()
    try:
        mlt.parse_midi(filename=f_name, binarized=True)
        merged_mlt = mlt.get_merged_pianoroll(mode='max')
    except:
        print("unable to parse. skipping: {}".format(f_name))
        return ChordProgression()  # empty progression

    chord_progression = ChordProgression([])
    last_chord_change = 0
    for i, x in enumerate(merged_mlt):
        # print(x)
        notes = np.where(x)
        num_notes = np.sum(x)
        if num_notes:
            if num_notes > 1:
                chord_notes = INT_TO_NOTE[notes[0] % 12]
                chord_name = note_to_chord(chord_notes.tolist())
                if chord_name:
                    chord = chord_name[0]
                    if len(chord_progression.chords
                           ) == 0 or chord_progression.chords[-1] != chord:
                        # print("chord: ", notes[0], chord_notes, chord_name)
                        chord_progression.append(chord)
            # else:
            #     print("note: ", notes[0])
    # print(chord_progression)
    return chord_progression
Exemplo n.º 5
0
for i in range(len(l)):
    try:
        #time.sleep(3)
        multitrack = Multitrack(beat_resolution=4, name=os.path.splitext(l[i])[0])
        x = pretty_midi.PrettyMIDI(os.path.join('./Jazz/', l[i]))
        multitrack.parse_pretty_midi(x)
        category_list = {'Piano': [], 'Drums': []}
        program_dict = {'Piano': 0, 'Drums': 0}
        for idx, track in enumerate(multitrack.tracks):
            if track.is_drum:
                category_list['Drums'].append(idx)
            else:
                category_list['Piano'].append(idx)
        tracks = []
        merged = multitrack[category_list['Piano']].get_merged_pianoroll()
        merged = multitrack.get_merged_pianoroll()
        #print('ok')
        #print(merged.shape + ' merged shape')
        tracks = [(Track(merged, program=0, is_drum=False, name=os.path.splitext(l[i])[0]))]
        mt = Multitrack(None, tracks, multitrack.tempo, multitrack.downbeat, multitrack.beat_resolution, multitrack.name)
        #mt.write(os.path.join(ROOT_PATH, '-Study No.2 opus.105.mid'))
        pr = get_bar_piano_roll(merged)
        #print(pr.shape + ' pr shape')
        pr_clip = pr[:, :, 24:108]
        #print(pr_clip.shape)
        #print(pr_clip.shape + ' pr clip shape')
        if int(pr_clip.shape[0] % 4) != 0:
            pr_clip = np.delete(pr_clip, np.s_[-int(pr_clip.shape[0] % 4):], axis=0)
        pr_re = pr_clip.reshape(-1, 64, 84, 1)
        #print(pr_re.shape)
        #print(pr_re.shape + ' pr re shape')