File size: 10,920 Bytes
142b9a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Master_MIDI_Dataset_GPU_Search_and_Filter.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/github/asigalov61/Los-Angeles-MIDI-Dataset/blob/main/Extras/Master_MIDI_Dataset_GPU_Search_and_Filter.ipynb

# Master MIDI Dataset GPU Search and Filter (ver. 2.0)

***

Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools

***

#### Project Los Angeles

#### Tegridy Code 2024

***

# (SETUP ENVIRONMENT)

# ( GPU CHECK)
"""

# @title NVIDIA GPU Check
!nvidia-smi

"""# (SETUP ENVIRONMENT)"""

#@title Install all dependencies (run only once per session)

!git clone --depth 1 https://github.com/asigalov61/Los-Angeles-MIDI-Dataset
!pip install huggingface_hub

#@title Import all needed modules

print('Loading core modules... Please wait...')

import os
import copy
from collections import Counter
import random
import pickle
from tqdm import tqdm
import pprint
import statistics
import shutil

import cupy as cp

from huggingface_hub import hf_hub_download

print('Loading TMIDIX module...')
os.chdir('/content/Los-Angeles-MIDI-Dataset')

import TMIDIX

os.chdir('/content/')

print('Creating IO dirs... Please wait...')

if not os.path.exists('/content/Master-MIDI-Dataset'):
    os.makedirs('/content/Master-MIDI-Dataset')

if not os.path.exists('/content/Master-MIDI-Dataset'):
    os.makedirs('/content/Master-MIDI-Dataset')

if not os.path.exists('/content/Output-MIDI-Dataset'):
    os.makedirs('/content/Output-MIDI-Dataset')

print('Done!')
print('Enjoy! :)')

"""# (PREP MAIN MIDI DATASET)"""

#@title Download Los Angeles MIDI Dataset
print('=' * 70)
print('Downloading Los Angeles MIDI Dataset...Please wait...')
print('=' * 70)

hf_hub_download(repo_id='projectlosangeles/Los-Angeles-MIDI-Dataset',
                filename='Los-Angeles-MIDI-Dataset-Ver-4-0-CC-BY-NC-SA.zip',
                repo_type="dataset",
                local_dir='/content/Main-MIDI-Dataset',
                local_dir_use_symlinks=False)
print('=' * 70)
print('Done! Enjoy! :)')
print('=' * 70)

# Commented out IPython magic to ensure Python compatibility.
#@title Unzip Los Angeles MIDI Dataset
# %cd /content/Main-MIDI-Dataset/

print('=' * 70)
print('Unzipping Los Angeles MIDI Dataset...Please wait...')
!unzip 'Los-Angeles-MIDI-Dataset-Ver-4-0-CC-BY-NC-SA.zip'
print('=' * 70)

print('Done! Enjoy! :)')
print('=' * 70)
# %cd /content/

#@title Create Los Angeles MIDI Dataset files list
print('=' * 70)
print('Creating dataset files list...')
dataset_addr = "/content/Main-MIDI-Dataset/MIDIs"

# 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 filez == []:
    print('Could not find any MIDI files. Please check Dataset dir...')
    print('=' * 70)

print('=' * 70)
print('Randomizing file list...')
random.shuffle(filez)
print('=' * 70)

LAMD_files_list = []

for f in tqdm(filez):
  LAMD_files_list.append([f.split('/')[-1].split('.mid')[0], f])
print('Done!')
print('=' * 70)

#@title Load Los Angeles MIDI Dataset Signatures Data

print('=' * 70)
print('Loading LAMDa Signatures Data...')
sigs_data = pickle.load(open('/content/Main-MIDI-Dataset/SIGNATURES_DATA/LAMDa_SIGNATURES_DATA.pickle', 'rb'))
print('=' * 70)

print('Prepping signatures...')
print('=' * 70)

random.shuffle(sigs_data)

signatures_file_names = []
sigs_matrixes = [ [0]*(len(TMIDIX.ALL_CHORDS)+128) for i in range(len(sigs_data))]

idx = 0
for s in tqdm(sigs_data):

  signatures_file_names.append(s[0])

  counts_sum = sum([c[1] for c in s[1]])

  for ss in s[1]:
    sigs_matrixes[idx][ss[0]] = ss[1] / counts_sum

  idx += 1

print('=' * 70)
print('Loading signatures...')
print('=' * 70)

signatures_data = cp.array(sigs_matrixes)

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

"""# (SEARCH AND FILTER)

### DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO "Master-MIDI-Dataset" FOLDER
"""

#@title Master MIDI Dataset Search and Filter

#@markdown NOTE: You can stop the search at any time to render partial results

number_of_top_matches_MIDIs_to_collect = 20 #@param {type:"slider", min:5, max:50, step:1}
search_matching_type = "ratios" # @param ["ratios", "distances"]
distances_norm_order = 3 # @param {type:"slider", min:1, max:10, step:1}
maximum_match_ratio_to_search_for = 0.999 #@param {type:"slider", min:0, max:1, step:0.001}

print('=' * 70)
print('Master MIDI Dataset GPU Search and Filter')
print('=' * 70)

###########

print('Loading MIDI files...')
print('This may take a while on a large dataset in particular.')

dataset_addr = "/content/Master-MIDI-Dataset"

filez = list()

for (dirpath, dirnames, filenames) in os.walk(dataset_addr):
    for file in filenames:
        if file.endswith(('.mid', '.midi', '.kar')):
            filez.append(os.path.join(dirpath, file))

print('=' * 70)

if filez:

  print('Randomizing file list...')
  random.shuffle(filez)
  print('=' * 70)

  ###################

  if not os.path.exists('/content/Output-MIDI-Dataset'):
      os.makedirs('/content/Output-MIDI-Dataset')

  ###################

  input_files_count = 0
  files_count = 0

  for f in filez:
    try:

          input_files_count += 1

          fn = os.path.basename(f)
          fn1 = os.path.splitext(fn)[0]
          ext = os.path.splitext(f)[1]

          print('Processing MIDI File #', files_count+1, 'out of', len(filez))
          print('MIDI file name', fn)
          print('-' * 70)

          #=======================================================

          raw_score = TMIDIX.midi2single_track_ms_score(open(f, 'rb').read())
          escore = TMIDIX.advanced_score_processor(raw_score, return_score_analysis=False, return_enhanced_score_notes=True)[0]

          for e in escore:
            e[1] = int(e[1] / 16)
            e[2] = int(e[2] / 16)

          src_sigs = []

          for i in range(-6, 6):

            escore_copy = copy.deepcopy(escore)

            for e in escore_copy:
              e[4] += i

            cscore = TMIDIX.chordify_score([1000, escore_copy])

            sig = []

            for c in cscore:

              pitches = sorted(set([p[4] for p in c if p[3] != 9]))

              if pitches:
                if len(pitches) > 1:
                  tones_chord = sorted(set([p % 12 for p in pitches]))
                  checked_tones_chord = TMIDIX.check_and_fix_tones_chord(tones_chord)

                  sig_token = TMIDIX.ALL_CHORDS.index(checked_tones_chord) + 128

                elif len(pitches) == 1:
                  sig_token = pitches[0]

                sig.append(sig_token)

            fsig = [list(v) for v in Counter(sig).most_common()]

            src_sig_mat = [0] * (len(TMIDIX.ALL_CHORDS)+128)

            counts_sum = sum([c[1] for c in fsig])

            for s in fsig:

              src_sig_mat[s[0]] = s[1] / counts_sum

            src_sigs.append(src_sig_mat)

          src_signatures = cp.stack(cp.array(src_sigs))

          #=======================================================

          print('Searching for matches...Please wait...')
          print('-' * 70)

          lower_threshold = 0.0
          upper_threshold = maximum_match_ratio_to_search_for
          filter_size = number_of_top_matches_MIDIs_to_collect

          final_ratios = []

          avg_idxs = []

          all_filtered_means = []
          all_filtered_idxs = []
          all_filtered_tvs = []

          tv_idx = -6

          for target_sig in tqdm(src_signatures):

            if search_matching_type == 'ratios':

              ratios = cp.where(target_sig != 0, cp.divide(cp.minimum(signatures_data, target_sig), cp.maximum(signatures_data, target_sig)), 0)
              max_comp_lengths = cp.maximum(cp.repeat(cp.sum(target_sig != 0), signatures_data.shape[0]), cp.sum(signatures_data != 0, axis=1))

              results = cp.divide(cp.sum(ratios, axis=1), max_comp_lengths)

            elif search_matching_type == 'distances':

              distances = cp.power(cp.sum(cp.power(cp.abs(signatures_data - target_sig), distances_norm_order), axis=1), 1 / distances_norm_order)

              results = cp.max(distances) - distances

            unique_means = cp.unique(results)
            sorted_means = cp.sort(unique_means)[::-1]

            filtered_means = sorted_means[(sorted_means >= lower_threshold) & (sorted_means <= upper_threshold)][:filter_size]

            filtered_idxs = cp.where(cp.in1d(results, filtered_means))[0]

            all_filtered_means.extend(results[cp.in1d(results, filtered_means)].tolist())

            all_filtered_idxs.extend(filtered_idxs.tolist())

            filtered_tvs = [tv_idx] * filtered_idxs.shape[0]

            all_filtered_tvs.extend(filtered_tvs)

            tv_idx += 1

          filtered_results = sorted(zip(all_filtered_means, all_filtered_idxs, all_filtered_tvs), key=lambda x: x[0], reverse=True)[:filter_size]

          #=======================================================

          print('Done!')
          print('-' * 70)
          print('Max match ratio:', filtered_results[0][0])
          print('Max match transpose value:', filtered_results[0][2])
          print('Max match signature index:', filtered_results[0][1])
          print('Max match file name:', signatures_file_names[filtered_results[0][1]])
          print('-' * 70)
          print('Copying max ratios MIDIs...')

          for fr in filtered_results:

            max_ratio_index = fr[1]

            ffn = signatures_file_names[fr[1]]
            ffn_idx = [y[0] for y in LAMD_files_list].index(ffn)

            ff = LAMD_files_list[ffn_idx][1]

            #=======================================================

            dir_str = str(fn1)
            copy_path = '/content/Output-MIDI-Dataset/'+dir_str
            if not os.path.exists(copy_path):
                os.mkdir(copy_path)

            fff = str(fr[0] * 100) + '_' + str(fr[2]) + '_' + ffn + '.mid'

            shutil.copy2(ff, copy_path+'/'+fff)

          shutil.copy2(f, copy_path+'/'+fn)

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

          #=======================================================

          # Processed files counter
          files_count += 1

    except KeyboardInterrupt:
        print('Quitting...')
        print('Total number of processed MIDI files', files_count)
        print('=' * 70)
        break

    except Exception as ex:
        print('WARNING !!!')
        print('=' * 70)
        print('Bad file:', f)
        print('Error detected:', ex)
        print('=' * 70)
        continue

    print('Total number of processed MIDI files', files_count)
    print('=' * 70)

else:
  print('Could not find any MIDI files. Please check Dataset dir...')
  print('=' * 70)

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