File size: 8,559 Bytes
e2fb2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- 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! :)"""