# -*- coding: utf-8 -*- """MIDI_Images_Solo_Piano_Dataset_Maker.ipynb Automatically generated by Colab. Original file is located at https://colab.research.google.com/drive/15E6o3Y1xPific5RtIZ-1CneHQhts3eEr # MIDI Images Solo Piano Dataset Maker (ver. 1.0) *** Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools *** #### Project Los Angeles #### Tegridy Code 2024 *** # (SETUP ENVIRONMENT) """ # @title Install dependecies !git clone --depth 1 https://github.com/asigalov61/tegridy-tools # Commented out IPython magic to ensure Python compatibility. #@title Import all needed modules print('=' * 70) print('Loading core modules...') print('Please wait...') print('=' * 70) import os import copy import math import statistics import random import pickle import shutil from itertools import groupby from collections import Counter from sklearn.metrics import pairwise_distances from sklearn import metrics from joblib import Parallel, delayed, parallel_config import numpy as np from tqdm import tqdm from PIL import Image import matplotlib.pyplot as plt print('Done!') print('=' * 70) print('Creating I/O dirs...') if not os.path.exists('/content/Dataset'): os.makedirs('/content/Dataset') print('Done!') print('=' * 70) print('Loading tegridy-tools modules...') print('=' * 70) # %cd /content/tegridy-tools/tegridy-tools import TMIDIX import TMELODIES import TPLOTS import HaystackSearch # %cd /content/ print('=' * 70) print('Done!') print('=' * 70) """# (DOWNLOAD SAMPLE MIDI DATASET)""" # Commented out IPython magic to ensure Python compatibility. # @title Download sample MIDI dataset (POP909) # %cd /content/Dataset/ !git clone --depth 1 https://github.com/music-x-lab/POP909-Dataset # %cd /content/ #@title Save file list ########### print('=' * 70) print('Loading MIDI files...') print('This may take a while on a large dataset in particular...') dataset_addr = '/content/Dataset/' # os.chdir(dataset_addr) filez = list() for (dirpath, dirnames, filenames) in os.walk(dataset_addr): filez += [os.path.join(dirpath, file) for file in filenames if file.endswith('.mid') or file.endswith('.midi') or file.endswith('.kar')] print('=' * 70) if filez == []: print('Could not find any MIDI files. Please check Dataset dir...') print('=' * 70) print('Randomizing file list...') random.shuffle(filez) print('Done!') print('=' * 70) print('Total found MIDI files:', len(filez)) print('=' * 70) TMIDIX.Tegridy_Any_Pickle_File_Writer(filez, 'filez') print('=' * 70) """# (LOAD TMIDIX MIDI PROCESSOR)""" #@title Load TMIDIX MIDI processor print('=' * 70) print('TMIDIX MIDI Processor') print('=' * 70) print('Loading...') ########### def TMIDIX_MIDI_Processor(midi_file): fn = os.path.basename(midi_file) fn1 = fn.split('.mid')[0] try: #======================================================= # START PROCESSING raw_score = TMIDIX.midi2single_track_ms_score(midi_file) escore_notes = TMIDIX.advanced_score_processor(raw_score, return_enhanced_score_notes=True)[0] escore_notes = TMIDIX.augment_enhanced_score_notes(escore_notes, timings_divider=256) sp_escore_notes = TMIDIX.recalculate_score_timings(TMIDIX.solo_piano_escore_notes(escore_notes, keep_drums=False)) if sp_escore_notes: bmatrix = TMIDIX.escore_notes_to_binary_matrix(sp_escore_notes) return [fn1, bmatrix] else: return [fn1, []] #======================================================= except Exception as ex: print('WARNING !!!') print('=' * 70) print('Bad MIDI:', midi_file) print('Error detected:', ex) print('=' * 70) return None print('Done!') print('=' * 70) """# (PROCESS MIDIs)""" #@title Process MIDIs with TMIDIX MIDI processor output_folder = "/content/MIDI-Images/" # @param {"type":"string"} NUMBER_OF_PARALLEL_JOBS = 4 # Number of parallel jobs NUMBER_OF_FILES_PER_ITERATION = 4 # Number of files to queue for each parallel iteration SAVE_EVERY_NUMBER_OF_ITERATIONS = 128 # Save every 2560 files print('=' * 70) print('TMIDIX MIDI Processor') print('=' * 70) print('Starting up...') print('=' * 70) ########### melody_chords_f = [] files_count = 0 print('Processing MIDI files...') print('Please wait...') print('=' * 70) for i in tqdm(range(0, len(filez), NUMBER_OF_FILES_PER_ITERATION)): with parallel_config(backend='threading', n_jobs=NUMBER_OF_PARALLEL_JOBS, verbose = 0): output = Parallel(n_jobs=NUMBER_OF_PARALLEL_JOBS, verbose=0)(delayed(TMIDIX_MIDI_Processor)(f) for f in filez[i:i+NUMBER_OF_FILES_PER_ITERATION]) for o in output: if o is not None: melody_chords_f.append(o) if i % (NUMBER_OF_FILES_PER_ITERATION * SAVE_EVERY_NUMBER_OF_ITERATIONS) == 0 and i != 0: print('SAVING !!!') print('=' * 70) print('Saving processed files...') files_count += len(melody_chords_f) print('=' * 70) print('Processed so far:', files_count, 'out of', len(filez), '===', files_count / len(filez), 'good files ratio') print('=' * 70) print('Writing images...') print('Please wait...') for mat in melody_chords_f: if mat[1]: TPLOTS.binary_matrix_to_images(mat[1], 128, 32, output_folder=output_folder+str(mat[0])+'/', output_img_prefix=str(mat[0]), output_img_ext='.png', verbose=False ) print('Done!') print('=' * 70) melody_chords_f = [] print('SAVING !!!') print('=' * 70) print('Saving processed files...') files_count += len(melody_chords_f) print('=' * 70) print('Processed so far:', files_count, 'out of', len(filez), '===', files_count / len(filez), 'good files ratio') print('=' * 70) print('Writing images...') print('Please wait...') for mat in melody_chords_f: if mat[1]: TPLOTS.binary_matrix_to_images(mat[1], 128, 32, output_folder=output_folder+str(mat[0])+'/', output_img_prefix=str(mat[0]), output_img_ext='.png', verbose=False ) print('Done!') print('=' * 70) """# (LOAD IMAGES)""" #@title Load created MIDI images full_path_to_metadata_pickle_files = "/content/MIDI-Images" #@param {type:"string"} print('=' * 70) print('MIDI Images Reader') print('=' * 70) print('Searching for images...') filez = list() for (dirpath, dirnames, filenames) in os.walk(full_path_to_metadata_pickle_files): filez += [os.path.join(dirpath, file) for file in filenames if file.endswith('.png')] print('=' * 70) filez.sort() print('Found', len(filez), 'images!') print('=' * 70) print('Reading images...') print('Please wait...') print('=' * 70) fidx = 0 all_read_images = [] for img in tqdm(filez): img = Image.open(img) img_arr = np.array(img).tolist() all_read_images.append(img_arr) fidx += 1 print('Done!') print('=' * 70) print('Loaded', fidx, 'images!') print('=' * 70) print('Done!') print('=' * 70) """# (TEST IMAGES)""" # @title Test created MIDI images print('=' * 70) image = random.choice(all_read_images) escore = TMIDIX.binary_matrix_to_original_escore_notes(image) output_score, patches, overflow_patches = TMIDIX.patch_enhanced_score_notes(escore) detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score, output_signature = 'MIDI Images', output_file_name = '/content/MIDI-Images-Composition', track_name='Project Los Angeles', list_of_MIDI_patches=patches, timings_multiplier=256 ) print('=' * 70) """# (ZIP IMAGES)""" # @title Zip created MIDI images !zip -9 -r POP909_MIDI_Images_128_128_32_BW.zip MIDI-Images/ > /dev/null """# Congrats! You did it! :)"""