continue

    # Pad to multtple
    multitrack.pad_to_multiple(4 * BEAT_RESOLUTION)

    # Binarize the pianoroll
    multitrack.binarize()

    # Sort the tracks according to program number
    multitrack.tracks.sort(key=lambda x: x.program)

    # Bring the drum track to the first track
    multitrack.tracks.sort(key=lambda x: ~x.is_drum)

    # Get the stacked pianoroll
    pianoroll = multitrack.get_stacked_pianorolls()

    # Check length
    if pianoroll.shape[0] < 4 * 4 * BEAT_RESOLUTION:
        continue

    # Keep only the mid-range pitches
    pianoroll = pianoroll[:, 24:108]

    # Reshape and get the phrase pianorolls
    # https://docs.scipy.org/doc/numpy-1.14.2/reference/generated/numpy.ndarray.reshape.html#numpy.ndarray.reshape
    # "One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions."
    try:
        pianoroll = pianoroll.reshape(-1, 4 * BEAT_RESOLUTION, 84, N_TRACKS)
        pianoroll = pianoroll.reshape(-1, 4, 4 * BEAT_RESOLUTION, 84, N_TRACKS)
        results.append(pianoroll)
Beispiel #2
0
import sys
import numpy as np
import matplotlib.pyplot as plt
from pypianoroll import Multitrack
from utils.pypianoroll_utils import pianoroll_to_multitrack

rootpath = os.path.abspath('../')
sys.path.append(rootpath)

TRACK_NAMES = ['drums', 'piano', 'guitar', 'bass', 'strings']
NPZ_FILE = '../data/sample_data/508448c8e2c465d9237dfca9a4c9a265.npz'

# Get Multitrack object and its piano roll
mt = Multitrack(NPZ_FILE, beat_resolution=24)
mt.binarize()
pr = mt.get_stacked_pianorolls()  # shape=(num_time_step, 128, num_track)
# F.Y.I num_time_step = self.beat_resolution * num_beat   # pypianoroll/../multitrack.py line 744
print("Stacked piano-roll matrix: ", np.shape(pr))

# Get piano roll matrix of each track
track_list = mt.tracks
for track in track_list:
    _pr = track.pianoroll
    print("%s of shape: %s" % (track.name, str(list(np.shape(_pr)))))
    # print("  active length of this track: ", track.get_active_length())

# Plot the multi-track piano-roll
fig, axs = mt.plot()
plt.show()

# Convert piano-rolls to Multitrack object
Beispiel #3
0
def test_pre_process_midi():
    print('start to preprocess test midi')
    for music_gerne in music_gerne_selected:
        print("start working on", music_gerne)
        """build path"""
        if not os.path.exists(
                os.path.join(ROOT_PATH,
                             music_gerne + '/' + music_gerne + '_test')):
            os.makedirs(
                os.path.join(ROOT_PATH,
                             music_gerne + '/' + music_gerne + '_test/'))
        if not os.path.exists(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/origin_midi')):
            os.makedirs(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/origin_midi'))
        """1. divide the original set into train and test sets"""
        l = [
            f for f in os.listdir(
                os.path.join(ROOT_PATH, music_gerne + '/' + music_gerne +
                             '_midi'))
        ]
        print(l)
        idx = np.random.choice(len(l), int(test_ratio * len(l)), replace=False)
        print(len(idx))
        for i in idx:
            shutil.move(
                os.path.join(ROOT_PATH,
                             music_gerne + '/' + music_gerne + '_midi', l[i]),
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test' + '/origin_midi',
                    l[i]))
        """2. convert_clean.py"""
        convert_clean.main(music_gerne=music_gerne, mode='test')
        """3. choose the clean midi from original sets"""
        if not os.path.exists(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/cleaner_midi')):
            os.makedirs(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/cleaner_midi'))
        if not os.path.exists(
                os.path.join(ROOT_PATH, music_gerne + '/' + music_gerne +
                             '_test/cleaner')):
            os.makedirs(
                os.path.join(ROOT_PATH, music_gerne + '/' + music_gerne +
                             '_test/cleaner'))
        l = [
            f for f in os.listdir(
                os.path.join(ROOT_PATH, music_gerne + '/' + music_gerne +
                             '_test/cleaner'))
        ]
        print(l)
        print(len(l))
        for i in l:
            shutil.copy(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test' + '/origin_midi',
                    os.path.splitext(i)[0] + '.mid'),
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/cleaner_midi',
                    os.path.splitext(i)[0] + '.mid'))
        """4. merge and crop"""
        if not os.path.exists(
                os.path.join(
                    ROOT_PATH, music_gerne + '/' + music_gerne +
                    '_test/cleaner_midi_gen')):
            os.makedirs(
                os.path.join(
                    ROOT_PATH, music_gerne + '/' + music_gerne +
                    '_test/cleaner_midi_gen'))
        if not os.path.exists(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/cleaner_npy')):
            os.makedirs(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/cleaner_npy'))
        l = [
            f for f in os.listdir(
                os.path.join(
                    ROOT_PATH, music_gerne + '/' + music_gerne +
                    '_test/cleaner_midi'))
        ]
        print(l)
        count = 0
        for i in range(len(l)):
            try:
                multitrack = Multitrack(beat_resolution=4,
                                        name=os.path.splitext(l[i])[0])
                x = pretty_midi.PrettyMIDI(
                    os.path.join(
                        ROOT_PATH,
                        music_gerne + '/' + music_gerne + '_test/cleaner_midi',
                        l[i]))
                multitrack.parse_pretty_midi(x)
                stacked = multitrack.get_stacked_pianorolls()
                print("stacked_shape:", stacked.shape)
                pr = get_bar_piano_roll(stacked)
                print("pr_shape:", pr.shape)
                pr_clip = pr[:, :, 24:108]
                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, 3)

                print("pr_re_shape:", pr_re.shape)
                print(
                    os.path.join(
                        ROOT_PATH, music_gerne + '/' + music_gerne +
                        '_test/cleaner_midi_gen',
                        os.path.splitext(l[i])[0] + '.mid'))
                save_midis(
                    pr_re,
                    os.path.join(
                        ROOT_PATH, music_gerne + '/' + music_gerne +
                        '_test/cleaner_midi_gen',
                        os.path.splitext(l[i])[0] + '.mid'))

                np.save(
                    os.path.join(
                        ROOT_PATH,
                        music_gerne + '/' + music_gerne + '_test/cleaner_npy',
                        os.path.splitext(l[i])[0] + '.npy'), pr_re)
            except:
                count += 1
                print('Wrong', l[i])
                continue
        print('total fails:', count)
        """5. concatenate into a big binary numpy array file"""
        l = [
            f for f in os.listdir(
                os.path.join(
                    ROOT_PATH, music_gerne + '/' + music_gerne +
                    '_test/cleaner_npy'))
        ]
        print(l)
        train = np.load(
            os.path.join(ROOT_PATH,
                         music_gerne + '/' + music_gerne + '_test/cleaner_npy',
                         l[0]))
        print(train.shape, np.max(train))
        for i in range(1, len(l)):
            print(i, l[i])
            t = np.load(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/cleaner_npy',
                    l[i]))
            train = np.concatenate((train, t), axis=0)
        print(train.shape)
        np.save(
            os.path.join(
                ROOT_PATH, music_gerne + '/' + music_gerne + '_test' + '/' +
                music_gerne + '_test.npy'), (train > 0.0))
        """6. separate numpy array file into single phrases"""
        if not os.path.exists(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/phrase_test')):
            os.makedirs(
                os.path.join(
                    ROOT_PATH,
                    music_gerne + '/' + music_gerne + '_test/phrase_test'))
        x = np.load(
            os.path.join(
                ROOT_PATH, music_gerne + '/' + music_gerne + '_test' + '/' +
                music_gerne + '_test.npy'))
        print(x.shape)
        count = 0
        for i in range(x.shape[0]):
            if np.max(x[i]):
                count += 1
                np.save(
                    os.path.join(
                        ROOT_PATH,
                        music_gerne + '/' + music_gerne + '_test/phrase_test' +
                        '/' + music_gerne + '_test_{}.npy'.format(i + 1)),
                    x[i])
                print(x[i].shape)
            # if count == 11216:
            #     break
        print(count)
        """some other codes"""