# -*- coding: utf-8 -*- """Los_Angeles_MIDI_Dataset_Maker.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/github/asigalov61/Los-Angeles-MIDI-Dataset/blob/main/Los_Angeles_MIDI_Dataset_Maker.ipynb # Los Angeles MIDI Dataset Maker (ver. 3.1) *** Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools *** #### Project Los Angeles #### Tegridy Code 2023 *** # (SETUP ENVIRONMENT) """ #@title Install all dependencies (run only once per session) !git clone https://github.com/asigalov61/tegridy-tools !pip install tqdm #@title Import all needed modules print('Loading core modules... Please wait...') import os import math import statistics import random from collections import Counter import shutil import hashlib from tqdm import tqdm print('Creating IO dirs...') if not os.path.exists('/content/Dataset'): os.makedirs('/content/Dataset') if not os.path.exists('/content/Output'): os.makedirs('/content/Output') output_dirs_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] for o in output_dirs_list: if not os.path.exists('/content/Output/'+str(o)+'/'): os.makedirs('/content/Output/'+str(o)+'/') print('Loading TMIDIX module...') os.chdir('/content/tegridy-tools/tegridy-tools') import TMIDIX print('Done!') os.chdir('/content/') print('Enjoy! :)') """# (DOWNLOAD SOURCE MIDI DATASET)""" # Commented out IPython magic to ensure Python compatibility. #@title Download original LAKH MIDI Dataset # %cd /content/Dataset/ !wget 'http://hog.ee.columbia.edu/craffel/lmd/lmd_full.tar.gz' !tar -xvf 'lmd_full.tar.gz' !rm 'lmd_full.tar.gz' # %cd /content/ """# (FILE LIST)""" #@title Save file list ########### 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] print('=' * 70) if filez == []: print('Could not find any MIDI files. Please check Dataset dir...') print('=' * 70) print('Randomizing file list...') random.shuffle(filez) TMIDIX.Tegridy_Any_Pickle_File_Writer(filez, '/content/filez') #@title Load file list filez = TMIDIX.Tegridy_Any_Pickle_File_Reader('/content/filez') print('Done!') """# (PROCESS)""" #@title Process MIDIs with TMIDIX MIDI processor print('=' * 70) print('TMIDIX MIDI Processor') print('=' * 70) print('Starting up...') print('=' * 70) ########### START_FILE_NUMBER = 0 LAST_SAVED_BATCH_COUNT = 0 input_files_count = START_FILE_NUMBER files_count = LAST_SAVED_BATCH_COUNT melody_chords_f = [] all_md5_names = [] all_pitches_sums = [] all_pitches_counts = [] all_pitches_and_counts = [] print('Processing MIDI files. Please wait...') print('=' * 70) for f in tqdm(filez[START_FILE_NUMBER:]): try: input_files_count += 1 fn = os.path.basename(f) # Filtering out giant MIDIs file_size = os.path.getsize(f) if file_size <= 1000000: fdata = open(f, 'rb').read() md5sum = hashlib.md5(fdata).hexdigest() md5name = str(md5sum) + '.mid' #======================================================= # START PROCESSING # Convering MIDI to ms score with MIDI.py module score = TMIDIX.midi2score(fdata) events_matrix = [] itrack = 1 while itrack < len(score): for event in score[itrack]: events_matrix.append(event) itrack += 1 events_matrix.sort(key=lambda x: x[1]) notes = [y for y in events_matrix if y[0] == 'note'] if len(notes) >= 256: times = [n[1] for n in notes] durs = [n[2] for n in notes] if min(times) >= 0 and min(durs) >= 0: if len(times) > len(set(times)): if str(md5sum) not in all_md5_names: all_md5_names.append(str(md5sum)) pitches = [n[4] for n in notes] pitches_sum = sum(pitches) if pitches_sum not in all_pitches_sums: all_pitches_sums.append(pitches_sum) pitches_and_counts = sorted([[key, val] for key,val in Counter(pitches).most_common()], reverse=True, key = lambda x: x[1]) pitches_counts = [p[1] for p in pitches_and_counts] #======================================================= if pitches_counts not in all_pitches_counts: # Saving data every 50000 processed files if files_count % 50000 == 0: print('SAVING !!!') print('=' * 70) print('Saving processed data...') print('=' * 70) TMIDIX.Tegridy_Any_Pickle_File_Writer([filez, all_md5_names, all_pitches_sums, all_pitches_and_counts], '/content/Output/all_files_data') print('=' * 70) print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio') print('=' * 70) shutil.copy2(f, '/content/Output/'+str(md5name[0])+'/'+md5name) all_pitches_counts.append(pitches_counts) all_pitches_and_counts.append(pitches_and_counts) if files_count % 1000 == 0: print('=' * 70) print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio') print('=' * 70) # Processed files counter files_count += 1 #======================================================= except KeyboardInterrupt: print('Saving current progress and quitting...') break except Exception as ex: print('WARNING !!!') print('=' * 70) print('Bad MIDI:', f) print('Error detected:', ex) print('=' * 70) continue # Saving last processed data... print('=' * 70) print('Saving processed data...') print('=' * 70) TMIDIX.Tegridy_Any_Pickle_File_Writer([filez, all_md5_names, all_pitches_sums, all_pitches_and_counts], '/content/Output/all_files_data') print('=' * 70) print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio') print('=' * 70) print('Done!') print('=' * 70) print('Resulting Stats:') print('=' * 70) print('Total good processed MIDI files:', files_count) print('=' * 70) """# Congrats! You did it! :)"""