File size: 7,154 Bytes
83dac28 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# -*- coding: utf-8 -*-
"""Los_Angeles_MIDI_Dataset_Maker.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1OF5Ag1GHu-KNPzeI_2V-A5P2AF7F8Kue
# Los Angeles MIDI Dataset Maker (ver. 1.0)
***
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 needed modules. Please wait...')
import os
import math
import statistics
import random
from collections import Counter
import shutil
import difflib
from tqdm import tqdm
if not os.path.exists('/content/Dataset'):
os.makedirs('/content/Dataset')
if not os.path.exists('/content/Output'):
os.makedirs('/content/Output')
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 = []
pitches_sums = []
pitches_counts = []
pitches_data = []
stats = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
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)
fn1 = fn.split('.mid')[0]
#=======================================================
# START PROCESSING
# Convering MIDI to ms score with MIDI.py module
score = TMIDIX.midi2ms_score(open(f, 'rb').read())
events_matrix = []
itrack = 1
while itrack < len(score):
for event in score[itrack]:
if event[0] == 'note':
if event[3] == 9:
event[4] = (event[4] % 128)+128
else:
event[4] = (event[4] % 128)
events_matrix.append(event)
itrack += 1
if len(events_matrix) >= 256:
events_matrix.sort(key=lambda x: x[1])
times = [e[1] for e in events_matrix]
durs = [e[2] for e in events_matrix]
if min(times) >= 0 and min(durs) >= 0:
if len([k for k,v in Counter(times).items() if v>1]) != 0:
pitches = [e[4] for e in events_matrix]
pitches_sum = sum(pitches)
pitches_number = len(pitches)
if pitches_sum not in pitches_sums:
pitches_count = sorted([[key, val] for key,val in Counter(pitches).most_common()], reverse=True)
#=======================================================
if [y[1] for y in pitches_count] not in pitches_counts:
# Saving every 5000 processed files
if files_count % 50000 == 0:
dir_count = ((files_count // 50000)+1) * 50000
dir_count_str = str(dir_count).zfill(7)
copy_path = '/content/Output/'+dir_count_str
if not os.path.exists(copy_path):
os.mkdir(copy_path)
print('SAVING !!!')
print('=' * 70)
print('Saving processed files...')
print('=' * 70)
print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')
print('=' * 70)
if files_count % 5000 == 0:
print('=' * 70)
print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')
print('=' * 70)
TMIDIX.Tegridy_Any_Pickle_File_Writer(pitches_data, '/content/Output/pitches_data')
shutil.copy2(f, copy_path+'/'+fn)
# Processed files counter
files_count += 1
data = []
data = [fn.split('.mid')[0], times[-1], len(set(times))]
for p in pitches_count:
data.extend(p)
pitches_data.append(data)
pitches_sums.append(pitches_sum)
pitches_counts.append([y[1] for y in pitches_count])
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 files...
print('=' * 70)
print('Saving processed files...')
print('=' * 70)
print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')
print('=' * 70)
TMIDIX.Tegridy_Any_Pickle_File_Writer(pitches_data, '/content/Output/pitches_data')
# Displaying resulting processing stats...
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! :)""" |