File size: 12,527 Bytes
3bd77c9
 
 
 
 
 
3e3cb7a
3bd77c9
9543c4a
3bd77c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b04778
3bd77c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b04778
3bd77c9
 
9b04778
3bd77c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9543c4a
3bd77c9
9543c4a
3bd77c9
9543c4a
3bd77c9
9543c4a
3bd77c9
9543c4a
3bd77c9
 
9543c4a
3bd77c9
9543c4a
3bd77c9
 
 
9543c4a
3bd77c9
9543c4a
3bd77c9
9543c4a
3bd77c9
 
 
 
 
9543c4a
3bd77c9
 
 
 
 
3e3cb7a
 
3bd77c9
 
9543c4a
3bd77c9
 
 
 
9543c4a
3bd77c9
 
 
 
9543c4a
3bd77c9
 
9543c4a
3bd77c9
 
 
 
 
 
 
 
 
 
9543c4a
 
3bd77c9
 
 
 
 
 
 
 
 
 
 
9543c4a
3e3cb7a
 
 
9543c4a
3bd77c9
 
3e3cb7a
9543c4a
3bd77c9
 
 
 
 
 
 
 
9543c4a
3e3cb7a
9543c4a
3bd77c9
 
9543c4a
3bd77c9
 
 
9543c4a
3bd77c9
 
 
9543c4a
3bd77c9
 
 
9543c4a
 
 
 
 
 
3e3cb7a
 
 
 
9543c4a
3bd77c9
 
9543c4a
3bd77c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9543c4a
3bd77c9
 
 
 
3e3cb7a
 
9543c4a
3e3cb7a
9543c4a
3bd77c9
9543c4a
3e3cb7a
 
3bd77c9
 
 
 
 
 
 
 
3e3cb7a
3bd77c9
 
 
 
 
3e3cb7a
3bd77c9
 
 
 
3e3cb7a
3bd77c9
9543c4a
3bd77c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e3cb7a
3bd77c9
 
 
 
 
9543c4a
3bd77c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e3cb7a
3bd77c9
 
 
9543c4a
3bd77c9
 
 
 
 
 
 
9b04778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9543c4a
9b04778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bd77c9
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# -*- 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.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 needed modules. Please wait...')
import os

import math
import statistics
import random
from collections import Counter
import pickle

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/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 = []

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)

"""# (BUILD FINAL METADATA FILE)"""

#@title Build final metadata file
full_path_to_metadata_pickle_files = "/content/drive/MyDrive" #@param {type:"string"}

print('=' * 70)
print('Los Angeles MIDI Dataset Metadata File Builder')
print('=' * 70)
print('Searching for files...')

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.split('.')[-1] == 'pickle']
print('=' * 70)

filez.sort()

print('Loading metadata files... Please wait...')
print('=' * 70)

metadata = []

for f in tqdm(filez):

    metadata.extend(pickle.load(open(f, 'rb')))
    print('Done!')
    print('=' * 70)
    print('Loaded file:', f)
    print('=' * 70)

print('Done!')
print('=' * 70)
print('Randomizing metadata entries order...')
random.shuffle(metadata)
print('=' * 70)
print('Writing final metadata pickle file...Please wait...')

with open('/content/LAMDa_META_DATA.pickle', 'wb') as handle:
  pickle.dump(metadata, handle, protocol=pickle.HIGHEST_PROTOCOL)

print('=' * 70)
print('Done!')
print('=' * 70)

#@title Zip final metadata file
print('=' * 70)
print('Zipping... Please wait...')
print('=' * 70)
!zip LAMDa_META_DATA.zip LAMDa_META_DATA.pickle
print('=' * 70)
print('Done!')
print('=' * 70)

"""# Congrats! You did it! :)"""