praca-magisterska/project/midi.py

83 lines
3.2 KiB
Python
Raw Normal View History

2019-05-29 10:36:34 +02:00
#!/usr/bin/env python3
import settings
import pypianoroll as roll
import matplotlib.pyplot as plt
import numpy as np
import os
from tqdm import tqdm
from math import floor
import sys
def to_samples(midi_file_path, midi_res=settings.midi_resolution):
# this function export a samples from midi file:
# and for every track in midi file chopped pianoroll
# for a samples of given beat_lenth (midi_res)
# every track is single line
print('Exporting samples from: {}'.format(midi_file_path))
all_beats = np.empty((0, settings.midi_resolution, 128))
for track in roll.Multitrack(midi_file_path).tracks:
print('Track: {}'.format(track.name))
if not track.is_drum:
number_of_beats = floor(track.pianoroll.shape[0] / midi_res)
track_pianoroll = track.pianoroll[: number_of_beats * midi_res]
track_beats = track_pianoroll.reshape(number_of_beats, midi_res, 128)
all_beats = np.concatenate([track_beats, all_beats], axis=0)
print('Exported {} samples of {}'.format(number_of_beats, settings.midi_program[track.program]))
else:
# add code for drums samples
pass
return all_beats
def to_midi(samples, output_path=settings.generated_midi_path, program=0, tempo=120, beat_resolution=settings.beat_resolution):
tracks = [roll.Track(samples, program=program)]
return_midi = roll.Multitrack(tracks=tracks, tempo=tempo, downbeat=[0, 96, 192, 288], beat_resolution=beat_resolution)
roll.write(return_midi, settings.generated_midi_path)
# todo: this function is running too slow.
2019-05-29 10:36:34 +02:00
def delete_empty_samples(sample_pack):
print('Deleting empty samples...')
temp_sample_pack = sample_pack
index_manipulator = 1
for index, sample in enumerate(sample_pack):
if sample.sum() == 0:
temp_sample_pack = np.delete(temp_sample_pack, index-index_manipulator, axis=0)
index_manipulator = index_manipulator + 1
print('Deleted {} empty samples'.format(index_manipulator-1))
return temp_sample_pack
def main():
if sys.argv[1]=='export':
print('Exporting started...')
sample_pack = np.empty((0,settings.midi_resolution,128))
for midi_file in os.listdir(settings.midi_dir):
midi_file_path = '{}/{}'.format(settings.midi_dir, midi_file)
midi_samples = to_samples(midi_file_path)
if midi_samples is None:
continue
sample_pack = np.concatenate((midi_samples, sample_pack), axis=0)
# I commented out this line, because it was too slow
2019-05-29 10:36:34 +02:00
# sample_pack = delete_empty_samples(sample_pack)
np.savez_compressed(settings.samples_dir, sample_pack)
print('Exported {} samples'.format(sample_pack.shape[0]))
fig, axes = plt.subplots(nrows=10, ncols=10, figsize=(20, 20))
for idx, ax in enumerate(axes.ravel()):
n = np.random.randint(0, sample_pack.shape[0])
sample = sample_pack[n]
ax.imshow(sample, cmap = plt.get_cmap('gray'))
plt.savefig(settings.sample_preview_path)
if __name__ == '__main__':
main()