Los-Angeles-MIDI-Dataset / los_angeles_midi_dataset_metadata_maker.py
projectlosangeles's picture
Upload 9 files
3e3cb7a
raw
history blame
11.6 kB
# -*- coding: utf-8 -*-
"""Los_Angeles_MIDI_Dataset_Metadata_Maker.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/asigalov61/Los-Angeles-MIDI-Dataset/blob/main/META-DATA/Los_Angeles_MIDI_Dataset_Metadata_Maker.ipynb
# Los Angeles MIDI Dataset Metadata Maker (ver. 3.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
from tqdm import tqdm
if not os.path.exists('/content/Dataset'):
os.makedirs('/content/Dataset')
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/
#@title Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')
"""# (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/drive/MyDrive/filez')
#@title Load file list
filez = TMIDIX.Tegridy_Any_Pickle_File_Reader('/content/drive/MyDrive/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 = []
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
opus = TMIDIX.midi2opus(open(f, 'rb').read())
opus_events_matrix = []
itrack0 = 1
while itrack0 < len(opus):
for event in opus[itrack0]:
opus_events_matrix.append(event)
itrack0 += 1
#=======================================================
ms_score = TMIDIX.opus2score(TMIDIX.to_millisecs(opus))
ms_events_matrix = []
itrack1 = 1
while itrack1 < len(ms_score):
for event in ms_score[itrack1]:
if event[0] == 'note':
ms_events_matrix.append(event)
itrack1 += 1
ms_events_matrix.sort(key=lambda x: x[1])
#=======================================================
# Convering MIDI to score with MIDI.py module
score = TMIDIX.opus2score(opus)
# INSTRUMENTS CONVERSION CYCLE
events_matrix = []
full_events_matrix = []
itrack = 1
patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
while itrack < len(score):
for event in score[itrack]:
if event[0] == 'note' or event[0] == 'patch_change':
events_matrix.append(event)
full_events_matrix.append(event)
itrack += 1
full_events_matrix.sort(key=lambda x: x[1])
events_matrix.sort(key=lambda x: x[1])
events_matrix1 = []
for event in events_matrix:
if event[0] == 'patch_change':
patches[event[2]] = event[3]
if event[0] == 'note':
event.extend([patches[event[3]]])
events_matrix1.append(event)
if len(events_matrix1) > 32:
events_matrix1.sort(key=lambda x: x[1])
for e in events_matrix1:
if e[0] == 'note':
if e[3] == 9:
e[4] = ((abs(e[4]) % 128) + 128)
else:
e[4] = (abs(e[4]) % 128)
pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix1]).most_common()]
pitches_counts.sort(key=lambda x: x[0], reverse=True)
patches = sorted([y[6] for y in events_matrix1])
patches_counts = [[y[0], y[1]] for y in Counter(patches).most_common()]
patches_counts.sort(key = lambda x: x[0])
midi_patches = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))
if len(midi_patches) == 0:
midi_patches = [0]
times = []
pt = ms_events_matrix[0][1]
start = True
for e in ms_events_matrix:
if (e[1]-pt) != 0 or start == True:
times.append((e[1]-pt))
start = False
pt = e[1]
times_sum = min(10000000, sum(times))
durs = [e[2] for e in ms_events_matrix]
vels = [e[5] for e in ms_events_matrix]
avg_time = int(sum(times) / len(times))
avg_dur = int(sum(durs) / len(durs))
avg_vel = int(sum(vels) / len(vels))
mode_time = statistics.mode(times)
mode_dur = statistics.mode(durs)
mode_vel = statistics.mode(vels)
median_time = int(statistics.median(times))
median_dur = int(statistics.median(durs))
median_vel = int(statistics.median(vels))
text_events_list = ['text_event',
'text_event_08',
'text_event_09',
'text_event_0a',
'text_event_0b',
'text_event_0c',
'text_event_0d',
'text_event_0e',
'text_event_0f']
text_events_count = len([e for e in full_events_matrix if e[0] in text_events_list])
lyric_events_count = len([e for e in full_events_matrix if e[0] == 'lyric'])
chords = []
pe = ms_events_matrix[0]
cho = []
for e in ms_events_matrix:
if (e[1] - pe[1]) == 0:
if e[3] != 9:
if (e[4] % 12) not in cho:
cho.append(e[4] % 12)
else:
if len(cho) > 0:
chords.append(sorted(cho))
cho = []
if e[3] != 9:
if (e[4] % 12) not in cho:
cho.append(e[4] % 12)
pe = e
if len(cho) > 0:
chords.append(sorted(cho))
ms_chords_counts = sorted([[list(key), val] for key,val in Counter([tuple(c) for c in chords if len(c) > 1]).most_common()], reverse=True, key = lambda x: x[1])
if len(ms_chords_counts) == 0:
ms_chords_counts = [[[0, 0], 0]]
total_number_of_chords = len(set([y[1] for y in events_matrix1]))
tempo_change_count = len([f for f in full_events_matrix if f[0] == 'set_tempo'])
thirty_second_note = [e for e in events_matrix1][32]
thirty_second_note_idx = full_events_matrix.index(thirty_second_note)
data = []
data.append(['total_number_of_tracks', itrack])
data.append(['total_number_of_opus_midi_events', len(opus_events_matrix)])
data.append(['total_number_of_score_midi_events', len(full_events_matrix)])
data.append(['average_median_mode_time_ms', [avg_time, median_time, mode_time]])
data.append(['average_median_mode_dur_ms', [avg_dur, median_dur, mode_dur]])
data.append(['average_median_mode_vel', [avg_vel, median_vel, mode_vel]])
data.append(['total_number_of_chords', total_number_of_chords])
data.append(['total_number_of_chords_ms', len(times)])
data.append(['ms_chords_counts', ms_chords_counts])
data.append(['pitches_times_sum_ms', times_sum])
data.append(['total_pitches_counts', pitches_counts])
data.append(['midi_patches', midi_patches])
data.append(['total_patches_counts', patches_counts])
data.append(['tempo_change_count', tempo_change_count])
data.append(['text_events_count', text_events_count])
data.append(['lyric_events_count', lyric_events_count])
data.append(['midi_ticks', score[0]])
data.extend(full_events_matrix[:thirty_second_note_idx])
data.append(full_events_matrix[-1])
melody_chords_f.append([fn1, data])
#=======================================================
# Processed files counter
files_count += 1
# Saving every 5000 processed files
if files_count % 10000 == 0:
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)
count = str(files_count)
TMIDIX.Tegridy_Any_Pickle_File_Writer(melody_chords_f, '/content/drive/MyDrive/LAMD_META_DATA_'+count)
melody_chords_f = []
print('=' * 70)
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)
count = str(files_count)
TMIDIX.Tegridy_Any_Pickle_File_Writer(melody_chords_f, '/content/drive/MyDrive/LAMD_META_DATA_'+count)
# 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! :)"""