projectlosangeles commited on
Commit
0c995cd
1 Parent(s): e422503

Upload 9 files

Browse files
Master_MIDI_Dataset_Search_and_Filter.ipynb ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "gradient": {
7
+ "editing": false,
8
+ "id": "ac5a4cf0-d9d2-47b5-9633-b53f8d99a4d2",
9
+ "kernelId": ""
10
+ },
11
+ "id": "SiTIpPjArIyr"
12
+ },
13
+ "source": [
14
+ "# Master MIDI Dataset Search and Filter (ver. 1.0)\n",
15
+ "\n",
16
+ "***\n",
17
+ "\n",
18
+ "Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools\n",
19
+ "\n",
20
+ "***\n",
21
+ "\n",
22
+ "#### Project Los Angeles\n",
23
+ "\n",
24
+ "#### Tegridy Code 2023\n",
25
+ "\n",
26
+ "***"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "markdown",
31
+ "metadata": {
32
+ "gradient": {
33
+ "editing": false,
34
+ "id": "fa0a611c-1803-42ae-bdf6-a49b5a4e781b",
35
+ "kernelId": ""
36
+ },
37
+ "id": "gOd93yV0sGd2"
38
+ },
39
+ "source": [
40
+ "# (SETUP ENVIRONMENT)"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "execution_count": null,
46
+ "metadata": {
47
+ "cellView": "form",
48
+ "gradient": {
49
+ "editing": false,
50
+ "id": "a1a45a91-d909-4fd4-b67a-5e16b971d179",
51
+ "kernelId": ""
52
+ },
53
+ "id": "fX12Yquyuihc"
54
+ },
55
+ "outputs": [],
56
+ "source": [
57
+ "#@title Install all dependencies (run only once per session)\n",
58
+ "\n",
59
+ "!git clone https://github.com/asigalov61/tegridy-tools\n",
60
+ "!pip install huggingface_hub\n",
61
+ "!pip install tqdm"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "metadata": {
68
+ "gradient": {
69
+ "editing": false,
70
+ "id": "b8207b76-9514-4c07-95db-95a4742e52c5",
71
+ "kernelId": ""
72
+ },
73
+ "id": "z7n9vnKmug1J",
74
+ "cellView": "form"
75
+ },
76
+ "outputs": [],
77
+ "source": [
78
+ "#@title Import all needed modules\n",
79
+ "\n",
80
+ "print('Loading core modules... Please wait...')\n",
81
+ "import os\n",
82
+ "import copy\n",
83
+ "from collections import Counter\n",
84
+ "import random\n",
85
+ "import pickle\n",
86
+ "from tqdm import tqdm\n",
87
+ "import pprint\n",
88
+ "import statistics\n",
89
+ "import shutil\n",
90
+ "\n",
91
+ "print('Creating IO dirs... Please wait...')\n",
92
+ "\n",
93
+ "if not os.path.exists('/content/Main-MIDI-Dataset'):\n",
94
+ " os.makedirs('/content/Main-MIDI-Dataset')\n",
95
+ "\n",
96
+ "if not os.path.exists('/content/Master-MIDI-Dataset'):\n",
97
+ " os.makedirs('/content/Master-MIDI-Dataset')\n",
98
+ "\n",
99
+ "if not os.path.exists('/content/Output-MIDI-Dataset'):\n",
100
+ " os.makedirs('/content/Output-MIDI-Dataset')\n",
101
+ "\n",
102
+ "print('Loading TMIDIX module...')\n",
103
+ "os.chdir('/content/tegridy-tools/tegridy-tools')\n",
104
+ "\n",
105
+ "import TMIDIX\n",
106
+ "\n",
107
+ "print('Done!')\n",
108
+ "\n",
109
+ "from huggingface_hub import hf_hub_download\n",
110
+ "\n",
111
+ "os.chdir('/content/')\n",
112
+ "print('Enjoy! :)')"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "markdown",
117
+ "metadata": {
118
+ "gradient": {
119
+ "editing": false,
120
+ "id": "20b8698a-0b4e-4fdb-ae49-24d063782e77",
121
+ "kernelId": ""
122
+ },
123
+ "id": "ObPxlEutsQBj"
124
+ },
125
+ "source": [
126
+ "# (PREP MAIN MIDI DATASET)"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "source": [
132
+ "#@title Download main MIDI dataset\n",
133
+ "print('=' * 70)\n",
134
+ "print('Downloading Los Angeles MIDI Dataset...Please wait...')\n",
135
+ "print('=' * 70)\n",
136
+ "\n",
137
+ "hf_hub_download(repo_id='projectlosangeles/Los-Angeles-MIDI-Dataset', \n",
138
+ " filename='Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip',\n",
139
+ " repo_type=\"dataset\",\n",
140
+ " local_dir='/content/Main-MIDI-Dataset', \n",
141
+ " local_dir_use_symlinks=False)\n",
142
+ "print('=' * 70)\n",
143
+ "print('Done! Enjoy! :)')\n",
144
+ "print('=' * 70)"
145
+ ],
146
+ "metadata": {
147
+ "cellView": "form",
148
+ "id": "7aItlhq9cRxZ"
149
+ },
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "source": [
156
+ "#@title Unzip main MIDI dataset\n",
157
+ "%cd /content/Main-MIDI-Dataset/\n",
158
+ "\n",
159
+ "print('=' * 70)\n",
160
+ "print('Unzipping Los Angeles MIDI Dataset...Please wait...')\n",
161
+ "!unzip 'Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip'\n",
162
+ "print('=' * 70)\n",
163
+ "\n",
164
+ "print('Done! Enjoy! :)')\n",
165
+ "print('=' * 70)\n",
166
+ "%cd /content/"
167
+ ],
168
+ "metadata": {
169
+ "cellView": "form",
170
+ "id": "zMF4vdMNDYYg"
171
+ },
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "source": [
178
+ "#@title Create main MIDI dataset files list\n",
179
+ "print('=' * 70)\n",
180
+ "print('Creating dataset files list...')\n",
181
+ "dataset_addr = \"/content/Main-MIDI-Dataset/MIDIs\"\n",
182
+ "\n",
183
+ "# os.chdir(dataset_addr)\n",
184
+ "filez = list()\n",
185
+ "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n",
186
+ " filez += [os.path.join(dirpath, file) for file in filenames]\n",
187
+ "\n",
188
+ "if filez == []:\n",
189
+ " print('Could not find any MIDI files. Please check Dataset dir...')\n",
190
+ " print('=' * 70)\n",
191
+ "\n",
192
+ "print('=' * 70)\n",
193
+ "print('Randomizing file list...')\n",
194
+ "random.shuffle(filez)\n",
195
+ "print('=' * 70)\n",
196
+ "\n",
197
+ "LAMD_files_list = []\n",
198
+ "\n",
199
+ "for f in tqdm(filez):\n",
200
+ " LAMD_files_list.append([f.split('/')[-1].split('.mid')[0], f])\n",
201
+ "print('Done!')\n",
202
+ "print('=' * 70)"
203
+ ],
204
+ "metadata": {
205
+ "cellView": "form",
206
+ "id": "btrUDk8MDfdw"
207
+ },
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "source": [
214
+ "#@title Load main MIDI dataset metadata\n",
215
+ "print('=' * 70)\n",
216
+ "print('Loading LAMDa data...Please wait...')\n",
217
+ "print('=' * 70)\n",
218
+ "print('Loading LAMDa META-DATA...')\n",
219
+ "meta_data = pickle.load(open('/content/Main-MIDI-Dataset/META_DATA/LAMDa_META_DATA.pickle', 'rb'))\n",
220
+ "print('Done!')"
221
+ ],
222
+ "metadata": {
223
+ "cellView": "form",
224
+ "id": "Mv-pjxbrIqi2"
225
+ },
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "markdown",
231
+ "source": [
232
+ "# (SEARCH AND FILTER)\n",
233
+ "\n",
234
+ "### DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO \"Master-MIDI-Dataset\" FOLDER"
235
+ ],
236
+ "metadata": {
237
+ "id": "iaeqXuIHI0_T"
238
+ }
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "source": [
243
+ "#@title Master MIDI Dataset Search and Filter\n",
244
+ "\n",
245
+ "#@markdown NOTE: You can stop the search at any time to render partial results\n",
246
+ "\n",
247
+ "number_of_top_ratios_MIDIs_to_collect = 10 #@param {type:\"slider\", min:1, max:20, step:1}\n",
248
+ "\n",
249
+ "#@markdown Match ratio control option\n",
250
+ "\n",
251
+ "maximum_match_ratio_to_search_for = 1 #@param {type:\"slider\", min:0, max:1, step:0.01}\n",
252
+ "\n",
253
+ "#@markdown MIDI pitches search options\n",
254
+ "\n",
255
+ "pitches_counts_cutoff_threshold_ratio = 0 #@param {type:\"slider\", min:0, max:1, step:0.05}\n",
256
+ "search_transposed_pitches = False #@param {type:\"boolean\"}\n",
257
+ "skip_exact_matches = False #@param {type:\"boolean\"}\n",
258
+ "\n",
259
+ "#@markdown Additional search options\n",
260
+ "\n",
261
+ "add_pitches_counts_ratios = True #@param {type:\"boolean\"}\n",
262
+ "add_timings_ratios = False #@param {type:\"boolean\"}\n",
263
+ "add_durations_ratios = False #@param {type:\"boolean\"}\n",
264
+ "\n",
265
+ "print('=' * 70)\n",
266
+ "print('Master MIDI Dataset Search and Filter')\n",
267
+ "print('=' * 70)\n",
268
+ "\n",
269
+ "###########\n",
270
+ "\n",
271
+ "print('Loading MIDI files...')\n",
272
+ "print('This may take a while on a large dataset in particular.')\n",
273
+ "\n",
274
+ "dataset_addr = \"/content/Master-MIDI-Dataset\"\n",
275
+ "# os.chdir(dataset_addr)\n",
276
+ "filez = list()\n",
277
+ "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n",
278
+ " filez += [os.path.join(dirpath, file) for file in filenames]\n",
279
+ "print('=' * 70)\n",
280
+ "\n",
281
+ "if filez == []:\n",
282
+ " print('Could not find any MIDI files. Please check Dataset dir...')\n",
283
+ " print('=' * 70)\n",
284
+ "\n",
285
+ "print('Randomizing file list...')\n",
286
+ "random.shuffle(filez)\n",
287
+ "print('=' * 70)\n",
288
+ "###################\n",
289
+ "\n",
290
+ "input_files_count = 0\n",
291
+ "files_count = 0\n",
292
+ "\n",
293
+ "for f in filez:\n",
294
+ " try:\n",
295
+ " \n",
296
+ " input_files_count += 1\n",
297
+ "\n",
298
+ " fn = os.path.basename(f)\n",
299
+ " fn1 = fn.split('.mid')[0]\n",
300
+ " ext = fn.split('.')[-1]\n",
301
+ "\n",
302
+ " if ext == 'mid' or ext == 'midi' or ext == 'kar':\n",
303
+ "\n",
304
+ " print('Processing MIDI File #', files_count+1, 'out of', len(filez))\n",
305
+ " print('MIDI file name', fn)\n",
306
+ " print('-' * 70) \n",
307
+ "\n",
308
+ " #=======================================================\n",
309
+ "\n",
310
+ " score = TMIDIX.midi2ms_score(open(f, 'rb').read())\n",
311
+ "\n",
312
+ " events_matrix = []\n",
313
+ "\n",
314
+ " itrack = 1\n",
315
+ "\n",
316
+ " while itrack < len(score):\n",
317
+ " for event in score[itrack]: \n",
318
+ " events_matrix.append(event)\n",
319
+ " itrack += 1\n",
320
+ "\n",
321
+ " # Sorting...\n",
322
+ " events_matrix.sort(key=lambda x: x[1])\n",
323
+ "\n",
324
+ " # recalculating timings\n",
325
+ " for e in events_matrix:\n",
326
+ " e[1] = int(e[1] / 10)\n",
327
+ " if e[0] == 'note':\n",
328
+ " e[2] = int(e[2] / 20)\n",
329
+ "\n",
330
+ " # final processing...\n",
331
+ "\n",
332
+ " melody_chords = []\n",
333
+ "\n",
334
+ " patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n",
335
+ "\n",
336
+ " pe = events_matrix[0]\n",
337
+ " for e in events_matrix:\n",
338
+ "\n",
339
+ " if e[0] == 'note':\n",
340
+ " # ['note', start_time, duration, channel, note, velocity]\n",
341
+ " time = max(0, min(255, e[1]-pe[1]))\n",
342
+ " duration = max(1, min(255, e[2]))\n",
343
+ " channel = max(0, min(15, e[3]))\n",
344
+ "\n",
345
+ " if e[3] != 9:\n",
346
+ " instrument = max(0, min(127, patches[e[3]]))\n",
347
+ " else:\n",
348
+ " instrument = max(128, min(255, patches[e[3]]+128))\n",
349
+ "\n",
350
+ " if e[3] != 9:\n",
351
+ "\n",
352
+ " pitch = max(1, min(127, e[4]))\n",
353
+ " else:\n",
354
+ " pitch = max(129, min(255, e[4]+128))\n",
355
+ "\n",
356
+ " if e[3] != 9:\n",
357
+ " velocity = max(1, min(127, e[5]))\n",
358
+ " else:\n",
359
+ " velocity = max(129, min(255, e[5]+128))\n",
360
+ "\n",
361
+ " melody_chords.append([time, duration, channel, instrument, pitch, velocity])\n",
362
+ "\n",
363
+ " if e[0] == 'patch_change':\n",
364
+ " # ['patch_change', dtime, channel, patch]\n",
365
+ " time = max(0, min(127, e[1]-pe[1]))\n",
366
+ " channel = max(0, min(15, e[2]))\n",
367
+ " patch = max(0, min(127, e[3]))\n",
368
+ "\n",
369
+ " patches[channel] = patch\n",
370
+ "\n",
371
+ " pe = e # Previous event\n",
372
+ "\n",
373
+ " MATRIX = [[0]*256 for i in range(38)]\n",
374
+ "\n",
375
+ " for m in melody_chords:\n",
376
+ "\n",
377
+ " MATRIX[0][m[0]] += 1\n",
378
+ " MATRIX[1][m[1]] += 1\n",
379
+ " MATRIX[2][m[2]] += 1 \n",
380
+ " MATRIX[3][m[3]] += 1\n",
381
+ " MATRIX[4][m[4]] += 1\n",
382
+ " MATRIX[5][m[5]] += 1\n",
383
+ " MATRIX[m[2]+6][m[3]] += 1\n",
384
+ " MATRIX[m[2]+22][m[4]] += 1\n",
385
+ "\n",
386
+ " #==================================================\n",
387
+ "\n",
388
+ " score = TMIDIX.midi2score(open(f, 'rb').read())\n",
389
+ "\n",
390
+ " events_matrix = []\n",
391
+ "\n",
392
+ " track_count = 0\n",
393
+ "\n",
394
+ " for s in score:\n",
395
+ " \n",
396
+ " if track_count > 0:\n",
397
+ " track = s\n",
398
+ " track.sort(key=lambda x: x[1])\n",
399
+ " events_matrix.extend(track)\n",
400
+ " else:\n",
401
+ " midi_ticks = s\n",
402
+ "\n",
403
+ " track_count += 1\n",
404
+ " \n",
405
+ " events_matrix.sort(key=lambda x: x[1])\n",
406
+ "\n",
407
+ " mult_pitches_counts = []\n",
408
+ "\n",
409
+ " for i in range(-6, 6):\n",
410
+ "\n",
411
+ " events_matrix1 = []\n",
412
+ "\n",
413
+ " for e in events_matrix:\n",
414
+ "\n",
415
+ " ev = copy.deepcopy(e)\n",
416
+ "\n",
417
+ " if e[0] == 'note':\n",
418
+ " if e[3] == 9:\n",
419
+ " ev[4] = ((e[4] % 128) + 128)\n",
420
+ " else:\n",
421
+ " ev[4] = ((e[4] % 128) + i)\n",
422
+ "\n",
423
+ " events_matrix1.append(ev)\n",
424
+ "\n",
425
+ " pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix1 if y[0] == 'note']).most_common()]\n",
426
+ " pitches_counts.sort(key=lambda x: x[0], reverse=True)\n",
427
+ " \n",
428
+ " mult_pitches_counts.append(pitches_counts)\n",
429
+ "\n",
430
+ " patches_list = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))\n",
431
+ "\n",
432
+ " #==================================================\n",
433
+ "\n",
434
+ " ms_score = TMIDIX.midi2ms_score(open(f, 'rb').read())\n",
435
+ "\n",
436
+ " ms_events_matrix = []\n",
437
+ "\n",
438
+ " itrack1 = 1\n",
439
+ "\n",
440
+ " while itrack1 < len(ms_score):\n",
441
+ " for event in ms_score[itrack1]: \n",
442
+ " if event[0] == 'note':\n",
443
+ " ms_events_matrix.append(event)\n",
444
+ " itrack1 += 1\n",
445
+ "\n",
446
+ " ms_events_matrix.sort(key=lambda x: x[1])\n",
447
+ "\n",
448
+ "\n",
449
+ " chords = []\n",
450
+ " pe = ms_events_matrix[0]\n",
451
+ " cho = []\n",
452
+ " for e in ms_events_matrix:\n",
453
+ " if (e[1] - pe[1]) == 0:\n",
454
+ " if e[3] != 9:\n",
455
+ " if (e[4] % 12) not in cho:\n",
456
+ " cho.append(e[4] % 12)\n",
457
+ " else:\n",
458
+ " if len(cho) > 0:\n",
459
+ " chords.append(sorted(cho))\n",
460
+ " cho = []\n",
461
+ " if e[3] != 9:\n",
462
+ " if (e[4] % 12) not in cho:\n",
463
+ " cho.append(e[4] % 12)\n",
464
+ "\n",
465
+ " pe = e\n",
466
+ " \n",
467
+ " if len(cho) > 0:\n",
468
+ " chords.append(sorted(cho))\n",
469
+ "\n",
470
+ " 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])\n",
471
+ "\n",
472
+ " times = []\n",
473
+ " pt = ms_events_matrix[0][1]\n",
474
+ " start = True\n",
475
+ " for e in ms_events_matrix:\n",
476
+ " if (e[1]-pt) != 0 or start == True:\n",
477
+ " times.append((e[1]-pt))\n",
478
+ " start = False\n",
479
+ " pt = e[1]\n",
480
+ " \n",
481
+ " durs = [e[2] for e in ms_events_matrix]\n",
482
+ " vels = [e[5] for e in ms_events_matrix]\n",
483
+ "\n",
484
+ " avg_time = int(sum(times) / len(times))\n",
485
+ " avg_dur = int(sum(durs) / len(durs))\n",
486
+ "\n",
487
+ " mode_time = statistics.mode(times)\n",
488
+ " mode_dur = statistics.mode(durs)\n",
489
+ "\n",
490
+ " median_time = int(statistics.median(times))\n",
491
+ " median_dur = int(statistics.median(durs))\n",
492
+ "\n",
493
+ " #=======================================================\n",
494
+ "\n",
495
+ " print('Searching for matches...Please wait...')\n",
496
+ " print('-' * 70)\n",
497
+ "\n",
498
+ " final_ratios = []\n",
499
+ "\n",
500
+ " for d in tqdm(meta_data):\n",
501
+ "\n",
502
+ " p_counts = d[1][10][1]\n",
503
+ " p_counts.sort(reverse = True, key = lambda x: x[1])\n",
504
+ " max_p_count = p_counts[0][1]\n",
505
+ " trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)]\n",
506
+ " total_p_counts = sum([y[1] for y in trimmed_p_counts])\n",
507
+ " \n",
508
+ " if search_transposed_pitches:\n",
509
+ " search_pitches = mult_pitches_counts\n",
510
+ " else:\n",
511
+ " search_pitches = [mult_pitches_counts[6]]\n",
512
+ "\n",
513
+ " #===================================================\n",
514
+ "\n",
515
+ " ratios_list = []\n",
516
+ "\n",
517
+ " #===================================================\n",
518
+ "\n",
519
+ " atrat = [0]\n",
520
+ "\n",
521
+ " if add_timings_ratios:\n",
522
+ "\n",
523
+ " source_times = [avg_time, \n",
524
+ " median_time, \n",
525
+ " mode_time]\n",
526
+ "\n",
527
+ " match_times = meta_data[0][1][3][1]\n",
528
+ "\n",
529
+ " times_ratios = []\n",
530
+ "\n",
531
+ " for i in range(len(source_times)):\n",
532
+ " maxtratio = max(source_times[i], match_times[i])\n",
533
+ " mintratio = min(source_times[i], match_times[i])\n",
534
+ " times_ratios.append(mintratio / maxtratio)\n",
535
+ "\n",
536
+ " avg_times_ratio = sum(times_ratios) / len(times_ratios)\n",
537
+ "\n",
538
+ " atrat[0] = avg_times_ratio\n",
539
+ "\n",
540
+ " #===================================================\n",
541
+ "\n",
542
+ " adrat = [0]\n",
543
+ "\n",
544
+ " if add_durations_ratios:\n",
545
+ "\n",
546
+ " source_durs = [avg_dur,\n",
547
+ " median_dur,\n",
548
+ " mode_dur]\n",
549
+ "\n",
550
+ " match_durs = meta_data[0][1][4][1]\n",
551
+ "\n",
552
+ " durs_ratios = []\n",
553
+ "\n",
554
+ " for i in range(len(source_durs)):\n",
555
+ " maxtratio = max(source_durs[i], match_durs[i])\n",
556
+ " mintratio = min(source_durs[i], match_durs[i])\n",
557
+ " durs_ratios.append(mintratio / maxtratio)\n",
558
+ "\n",
559
+ " avg_durs_ratio = sum(durs_ratios) / len(durs_ratios)\n",
560
+ "\n",
561
+ " adrat[0] = avg_durs_ratio\n",
562
+ "\n",
563
+ " #===================================================\n",
564
+ "\n",
565
+ " for m in search_pitches:\n",
566
+ "\n",
567
+ " sprat = []\n",
568
+ "\n",
569
+ " m.sort(reverse = True, key = lambda x: x[1])\n",
570
+ " max_pitches_count = m[0][1]\n",
571
+ " trimmed_pitches_counts = [y for y in m if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)]\n",
572
+ " total_pitches_counts = sum([y[1] for y in trimmed_pitches_counts])\n",
573
+ "\n",
574
+ " same_pitches = set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts])\n",
575
+ " num_same_pitches = len(same_pitches)\n",
576
+ " same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in trimmed_p_counts]+[T[0] for T in trimmed_pitches_counts])))\n",
577
+ "\n",
578
+ " if skip_exact_matches:\n",
579
+ " if same_pitches_ratio == 1:\n",
580
+ " same_pitches_ratio = 0\n",
581
+ "\n",
582
+ " sprat.append(same_pitches_ratio)\n",
583
+ "\n",
584
+ " #===================================================\n",
585
+ "\n",
586
+ " spcrat = [0]\n",
587
+ "\n",
588
+ " if add_pitches_counts_ratios:\n",
589
+ "\n",
590
+ " same_trimmed_p_counts = sorted([T for T in trimmed_p_counts if T[0] in same_pitches], reverse = True)\n",
591
+ " same_trimmed_pitches_counts = sorted([T for T in trimmed_pitches_counts if T[0] in same_pitches], reverse = True)\n",
592
+ "\n",
593
+ " same_trimmed_p_counts_ratios = [[s[0], s[1] / total_p_counts] for s in same_trimmed_p_counts]\n",
594
+ " same_trimmed_pitches_counts_ratios = [[s[0], s[1] / total_pitches_counts] for s in same_trimmed_pitches_counts]\n",
595
+ "\n",
596
+ " same_pitches_counts_ratios = []\n",
597
+ "\n",
598
+ " for i in range(len(same_trimmed_p_counts_ratios)):\n",
599
+ " mincratio = min(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])\n",
600
+ " maxcratio = max(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])\n",
601
+ " same_pitches_counts_ratios.append([same_trimmed_p_counts_ratios[i][0], mincratio / maxcratio])\n",
602
+ "\n",
603
+ " same_counts_ratios = [s[1] for s in same_pitches_counts_ratios]\n",
604
+ "\n",
605
+ " if len(same_counts_ratios) > 0:\n",
606
+ " avg_same_pitches_counts_ratio = sum(same_counts_ratios) / len(same_counts_ratios)\n",
607
+ " else:\n",
608
+ " avg_same_pitches_counts_ratio = 0\n",
609
+ "\n",
610
+ " spcrat[0] = avg_same_pitches_counts_ratio\n",
611
+ "\n",
612
+ " #===================================================\n",
613
+ "\n",
614
+ " r_list = [sprat[0]]\n",
615
+ "\n",
616
+ " if add_pitches_counts_ratios:\n",
617
+ " r_list.append(spcrat[0])\n",
618
+ " \n",
619
+ " if add_timings_ratios:\n",
620
+ " r_list.append(atrat[0])\n",
621
+ " \n",
622
+ " if add_durations_ratios:\n",
623
+ " r_list.append(adrat[0])\n",
624
+ "\n",
625
+ " ratios_list.append(r_list)\n",
626
+ "\n",
627
+ " #===================================================\n",
628
+ " \n",
629
+ " avg_ratios_list = []\n",
630
+ "\n",
631
+ " for r in ratios_list:\n",
632
+ " avg_ratios_list.append(sum(r) / len(r))\n",
633
+ "\n",
634
+ " #===================================================\n",
635
+ " \n",
636
+ " final_ratio = max(avg_ratios_list)\n",
637
+ " \n",
638
+ " if final_ratio > maximum_match_ratio_to_search_for:\n",
639
+ " final_ratio = 0\n",
640
+ "\n",
641
+ " final_ratios.append(final_ratio)\n",
642
+ "\n",
643
+ " #=======================================================\n",
644
+ "\n",
645
+ " print('-' * 70)\n",
646
+ "\n",
647
+ " max_ratios = sorted(final_ratios, reverse=True)[:number_of_top_ratios_MIDIs_to_collect]\n",
648
+ "\n",
649
+ " print('Max match ratio', max_ratios[0])\n",
650
+ " print('-' * 70)\n",
651
+ " print('Copying max ratios MIDIs...')\n",
652
+ "\n",
653
+ " for i in range(number_of_top_ratios_MIDIs_to_collect):\n",
654
+ "\n",
655
+ " max_ratio = max_ratios[i]\n",
656
+ " max_ratio_index = final_ratios.index(max_ratio)\n",
657
+ "\n",
658
+ " ffn = meta_data[max_ratio_index][0]\n",
659
+ " ffn_idx = [y[0] for y in LAMD_files_list].index(ffn)\n",
660
+ "\n",
661
+ " ff = LAMD_files_list[ffn_idx][1]\n",
662
+ "\n",
663
+ " #=======================================================\n",
664
+ " \n",
665
+ " dir_str = str(fn1)\n",
666
+ " copy_path = '/content/Output-MIDI-Dataset/'+dir_str\n",
667
+ " if not os.path.exists(copy_path):\n",
668
+ " os.mkdir(copy_path)\n",
669
+ "\n",
670
+ " shutil.copy2(f, copy_path+'/'+fn)\n",
671
+ "\n",
672
+ " fff = str(max_ratio * 100) + '_' + ffn\n",
673
+ "\n",
674
+ " shutil.copy2(ff, copy_path+'/'+fff)\n",
675
+ " \n",
676
+ " #=======================================================\n",
677
+ " \n",
678
+ " print('Done!')\n",
679
+ " print('=' * 70)\n",
680
+ "\n",
681
+ " #=======================================================\n",
682
+ "\n",
683
+ " # Processed files counter\n",
684
+ " files_count += 1\n",
685
+ " \n",
686
+ " except KeyboardInterrupt:\n",
687
+ " print('Quitting...')\n",
688
+ " print('Total number of processed MIDI files', files_count)\n",
689
+ " print('=' * 70)\n",
690
+ " break \n",
691
+ "\n",
692
+ " except Exception as ex:\n",
693
+ " print('WARNING !!!')\n",
694
+ " print('=' * 70)\n",
695
+ " print('Bad file:', f)\n",
696
+ " print('Error detected:', ex)\n",
697
+ " print('=' * 70)\n",
698
+ " continue\n",
699
+ "\n",
700
+ "print('Total number of processed MIDI files', files_count)\n",
701
+ "print('=' * 70)"
702
+ ],
703
+ "metadata": {
704
+ "cellView": "form",
705
+ "id": "M0JWCPzBGNvh"
706
+ },
707
+ "execution_count": null,
708
+ "outputs": []
709
+ },
710
+ {
711
+ "cell_type": "markdown",
712
+ "metadata": {
713
+ "id": "YzCMd94Tu_gz"
714
+ },
715
+ "source": [
716
+ "# Congrats! You did it! :)"
717
+ ]
718
+ }
719
+ ],
720
+ "metadata": {
721
+ "colab": {
722
+ "machine_shape": "hm",
723
+ "private_outputs": true,
724
+ "provenance": []
725
+ },
726
+ "gpuClass": "standard",
727
+ "kernelspec": {
728
+ "display_name": "Python 3 (ipykernel)",
729
+ "language": "python",
730
+ "name": "python3"
731
+ },
732
+ "language_info": {
733
+ "codemirror_mode": {
734
+ "name": "ipython",
735
+ "version": 3
736
+ },
737
+ "file_extension": ".py",
738
+ "mimetype": "text/x-python",
739
+ "name": "python",
740
+ "nbconvert_exporter": "python",
741
+ "pygments_lexer": "ipython3",
742
+ "version": "3.9.7"
743
+ }
744
+ },
745
+ "nbformat": 4,
746
+ "nbformat_minor": 0
747
+ }
master_midi_dataset_search_and_filter.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Master_MIDI_Dataset_Search_and_Filter.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1bHH8LjCdE2nhYOfBv4TdCltvW2PWxGol
8
+
9
+ # Master MIDI Dataset Search and Filter (ver. 1.0)
10
+
11
+ ***
12
+
13
+ Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools
14
+
15
+ ***
16
+
17
+ #### Project Los Angeles
18
+
19
+ #### Tegridy Code 2023
20
+
21
+ ***
22
+
23
+ # (SETUP ENVIRONMENT)
24
+ """
25
+
26
+ #@title Install all dependencies (run only once per session)
27
+
28
+ !git clone https://github.com/asigalov61/tegridy-tools
29
+ !pip install huggingface_hub
30
+ !pip install tqdm
31
+
32
+ #@title Import all needed modules
33
+
34
+ print('Loading core modules... Please wait...')
35
+ import os
36
+ import copy
37
+ from collections import Counter
38
+ import random
39
+ import pickle
40
+ from tqdm import tqdm
41
+ import pprint
42
+ import statistics
43
+ import shutil
44
+
45
+ print('Creating IO dirs... Please wait...')
46
+
47
+ if not os.path.exists('/content/Main-MIDI-Dataset'):
48
+ os.makedirs('/content/Main-MIDI-Dataset')
49
+
50
+ if not os.path.exists('/content/Master-MIDI-Dataset'):
51
+ os.makedirs('/content/Master-MIDI-Dataset')
52
+
53
+ if not os.path.exists('/content/Output-MIDI-Dataset'):
54
+ os.makedirs('/content/Output-MIDI-Dataset')
55
+
56
+ print('Loading TMIDIX module...')
57
+ os.chdir('/content/tegridy-tools/tegridy-tools')
58
+
59
+ import TMIDIX
60
+
61
+ print('Done!')
62
+
63
+ from huggingface_hub import hf_hub_download
64
+
65
+ os.chdir('/content/')
66
+ print('Enjoy! :)')
67
+
68
+ """# (PREP MAIN MIDI DATASET)"""
69
+
70
+ #@title Download main MIDI dataset
71
+ print('=' * 70)
72
+ print('Downloading Los Angeles MIDI Dataset...Please wait...')
73
+ print('=' * 70)
74
+
75
+ hf_hub_download(repo_id='projectlosangeles/Los-Angeles-MIDI-Dataset',
76
+ filename='Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip',
77
+ repo_type="dataset",
78
+ local_dir='/content/Main-MIDI-Dataset',
79
+ local_dir_use_symlinks=False)
80
+ print('=' * 70)
81
+ print('Done! Enjoy! :)')
82
+ print('=' * 70)
83
+
84
+ # Commented out IPython magic to ensure Python compatibility.
85
+ #@title Unzip main MIDI dataset
86
+ # %cd /content/Main-MIDI-Dataset/
87
+
88
+ print('=' * 70)
89
+ print('Unzipping Los Angeles MIDI Dataset...Please wait...')
90
+ !unzip 'Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip'
91
+ print('=' * 70)
92
+
93
+ print('Done! Enjoy! :)')
94
+ print('=' * 70)
95
+ # %cd /content/
96
+
97
+ #@title Create main MIDI dataset files list
98
+ print('=' * 70)
99
+ print('Creating dataset files list...')
100
+ dataset_addr = "/content/Main-MIDI-Dataset/MIDIs"
101
+
102
+ # os.chdir(dataset_addr)
103
+ filez = list()
104
+ for (dirpath, dirnames, filenames) in os.walk(dataset_addr):
105
+ filez += [os.path.join(dirpath, file) for file in filenames]
106
+
107
+ if filez == []:
108
+ print('Could not find any MIDI files. Please check Dataset dir...')
109
+ print('=' * 70)
110
+
111
+ print('=' * 70)
112
+ print('Randomizing file list...')
113
+ random.shuffle(filez)
114
+ print('=' * 70)
115
+
116
+ LAMD_files_list = []
117
+
118
+ for f in tqdm(filez):
119
+ LAMD_files_list.append([f.split('/')[-1].split('.mid')[0], f])
120
+ print('Done!')
121
+ print('=' * 70)
122
+
123
+ #@title Load main MIDI dataset metadata
124
+ print('=' * 70)
125
+ print('Loading LAMDa data...Please wait...')
126
+ print('=' * 70)
127
+ print('Loading LAMDa META-DATA...')
128
+ meta_data = pickle.load(open('/content/Main-MIDI-Dataset/META_DATA/LAMDa_META_DATA.pickle', 'rb'))
129
+ print('Done!')
130
+
131
+ """# (SEARCH AND FILTER)
132
+
133
+ ### DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO "Master-MIDI-Dataset" FOLDER
134
+ """
135
+
136
+ #@title Master MIDI Dataset Search and Filter
137
+
138
+ #@markdown NOTE: You can stop the search at any time to render partial results
139
+
140
+ number_of_top_ratios_MIDIs_to_collect = 10 #@param {type:"slider", min:1, max:20, step:1}
141
+
142
+ #@markdown Match ratio control option
143
+
144
+ maximum_match_ratio_to_search_for = 1 #@param {type:"slider", min:0, max:1, step:0.01}
145
+
146
+ #@markdown MIDI pitches search options
147
+
148
+ pitches_counts_cutoff_threshold_ratio = 0 #@param {type:"slider", min:0, max:1, step:0.05}
149
+ search_transposed_pitches = False #@param {type:"boolean"}
150
+ skip_exact_matches = False #@param {type:"boolean"}
151
+
152
+ #@markdown Additional search options
153
+
154
+ add_pitches_counts_ratios = True #@param {type:"boolean"}
155
+ add_timings_ratios = False #@param {type:"boolean"}
156
+ add_durations_ratios = False #@param {type:"boolean"}
157
+
158
+ print('=' * 70)
159
+ print('Master MIDI Dataset Search and Filter')
160
+ print('=' * 70)
161
+
162
+ ###########
163
+
164
+ print('Loading MIDI files...')
165
+ print('This may take a while on a large dataset in particular.')
166
+
167
+ dataset_addr = "/content/Master-MIDI-Dataset"
168
+ # os.chdir(dataset_addr)
169
+ filez = list()
170
+ for (dirpath, dirnames, filenames) in os.walk(dataset_addr):
171
+ filez += [os.path.join(dirpath, file) for file in filenames]
172
+ print('=' * 70)
173
+
174
+ if filez == []:
175
+ print('Could not find any MIDI files. Please check Dataset dir...')
176
+ print('=' * 70)
177
+
178
+ print('Randomizing file list...')
179
+ random.shuffle(filez)
180
+ print('=' * 70)
181
+ ###################
182
+
183
+ input_files_count = 0
184
+ files_count = 0
185
+
186
+ for f in filez:
187
+ try:
188
+
189
+ input_files_count += 1
190
+
191
+ fn = os.path.basename(f)
192
+ fn1 = fn.split('.mid')[0]
193
+ ext = fn.split('.')[-1]
194
+
195
+ if ext == 'mid' or ext == 'midi' or ext == 'kar':
196
+
197
+ print('Processing MIDI File #', files_count+1, 'out of', len(filez))
198
+ print('MIDI file name', fn)
199
+ print('-' * 70)
200
+
201
+ #=======================================================
202
+
203
+ score = TMIDIX.midi2ms_score(open(f, 'rb').read())
204
+
205
+ events_matrix = []
206
+
207
+ itrack = 1
208
+
209
+ while itrack < len(score):
210
+ for event in score[itrack]:
211
+ events_matrix.append(event)
212
+ itrack += 1
213
+
214
+ # Sorting...
215
+ events_matrix.sort(key=lambda x: x[1])
216
+
217
+ # recalculating timings
218
+ for e in events_matrix:
219
+ e[1] = int(e[1] / 10)
220
+ if e[0] == 'note':
221
+ e[2] = int(e[2] / 20)
222
+
223
+ # final processing...
224
+
225
+ melody_chords = []
226
+
227
+ patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
228
+
229
+ pe = events_matrix[0]
230
+ for e in events_matrix:
231
+
232
+ if e[0] == 'note':
233
+ # ['note', start_time, duration, channel, note, velocity]
234
+ time = max(0, min(255, e[1]-pe[1]))
235
+ duration = max(1, min(255, e[2]))
236
+ channel = max(0, min(15, e[3]))
237
+
238
+ if e[3] != 9:
239
+ instrument = max(0, min(127, patches[e[3]]))
240
+ else:
241
+ instrument = max(128, min(255, patches[e[3]]+128))
242
+
243
+ if e[3] != 9:
244
+
245
+ pitch = max(1, min(127, e[4]))
246
+ else:
247
+ pitch = max(129, min(255, e[4]+128))
248
+
249
+ if e[3] != 9:
250
+ velocity = max(1, min(127, e[5]))
251
+ else:
252
+ velocity = max(129, min(255, e[5]+128))
253
+
254
+ melody_chords.append([time, duration, channel, instrument, pitch, velocity])
255
+
256
+ if e[0] == 'patch_change':
257
+ # ['patch_change', dtime, channel, patch]
258
+ time = max(0, min(127, e[1]-pe[1]))
259
+ channel = max(0, min(15, e[2]))
260
+ patch = max(0, min(127, e[3]))
261
+
262
+ patches[channel] = patch
263
+
264
+ pe = e # Previous event
265
+
266
+ MATRIX = [[0]*256 for i in range(38)]
267
+
268
+ for m in melody_chords:
269
+
270
+ MATRIX[0][m[0]] += 1
271
+ MATRIX[1][m[1]] += 1
272
+ MATRIX[2][m[2]] += 1
273
+ MATRIX[3][m[3]] += 1
274
+ MATRIX[4][m[4]] += 1
275
+ MATRIX[5][m[5]] += 1
276
+ MATRIX[m[2]+6][m[3]] += 1
277
+ MATRIX[m[2]+22][m[4]] += 1
278
+
279
+ #==================================================
280
+
281
+ score = TMIDIX.midi2score(open(f, 'rb').read())
282
+
283
+ events_matrix = []
284
+
285
+ track_count = 0
286
+
287
+ for s in score:
288
+
289
+ if track_count > 0:
290
+ track = s
291
+ track.sort(key=lambda x: x[1])
292
+ events_matrix.extend(track)
293
+ else:
294
+ midi_ticks = s
295
+
296
+ track_count += 1
297
+
298
+ events_matrix.sort(key=lambda x: x[1])
299
+
300
+ mult_pitches_counts = []
301
+
302
+ for i in range(-6, 6):
303
+
304
+ events_matrix1 = []
305
+
306
+ for e in events_matrix:
307
+
308
+ ev = copy.deepcopy(e)
309
+
310
+ if e[0] == 'note':
311
+ if e[3] == 9:
312
+ ev[4] = ((e[4] % 128) + 128)
313
+ else:
314
+ ev[4] = ((e[4] % 128) + i)
315
+
316
+ events_matrix1.append(ev)
317
+
318
+ pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix1 if y[0] == 'note']).most_common()]
319
+ pitches_counts.sort(key=lambda x: x[0], reverse=True)
320
+
321
+ mult_pitches_counts.append(pitches_counts)
322
+
323
+ patches_list = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))
324
+
325
+ #==================================================
326
+
327
+ ms_score = TMIDIX.midi2ms_score(open(f, 'rb').read())
328
+
329
+ ms_events_matrix = []
330
+
331
+ itrack1 = 1
332
+
333
+ while itrack1 < len(ms_score):
334
+ for event in ms_score[itrack1]:
335
+ if event[0] == 'note':
336
+ ms_events_matrix.append(event)
337
+ itrack1 += 1
338
+
339
+ ms_events_matrix.sort(key=lambda x: x[1])
340
+
341
+
342
+ chords = []
343
+ pe = ms_events_matrix[0]
344
+ cho = []
345
+ for e in ms_events_matrix:
346
+ if (e[1] - pe[1]) == 0:
347
+ if e[3] != 9:
348
+ if (e[4] % 12) not in cho:
349
+ cho.append(e[4] % 12)
350
+ else:
351
+ if len(cho) > 0:
352
+ chords.append(sorted(cho))
353
+ cho = []
354
+ if e[3] != 9:
355
+ if (e[4] % 12) not in cho:
356
+ cho.append(e[4] % 12)
357
+
358
+ pe = e
359
+
360
+ if len(cho) > 0:
361
+ chords.append(sorted(cho))
362
+
363
+ 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])
364
+
365
+ times = []
366
+ pt = ms_events_matrix[0][1]
367
+ start = True
368
+ for e in ms_events_matrix:
369
+ if (e[1]-pt) != 0 or start == True:
370
+ times.append((e[1]-pt))
371
+ start = False
372
+ pt = e[1]
373
+
374
+ durs = [e[2] for e in ms_events_matrix]
375
+ vels = [e[5] for e in ms_events_matrix]
376
+
377
+ avg_time = int(sum(times) / len(times))
378
+ avg_dur = int(sum(durs) / len(durs))
379
+
380
+ mode_time = statistics.mode(times)
381
+ mode_dur = statistics.mode(durs)
382
+
383
+ median_time = int(statistics.median(times))
384
+ median_dur = int(statistics.median(durs))
385
+
386
+ #=======================================================
387
+
388
+ print('Searching for matches...Please wait...')
389
+ print('-' * 70)
390
+
391
+ final_ratios = []
392
+
393
+ for d in tqdm(meta_data):
394
+
395
+ p_counts = d[1][10][1]
396
+ p_counts.sort(reverse = True, key = lambda x: x[1])
397
+ max_p_count = p_counts[0][1]
398
+ trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)]
399
+ total_p_counts = sum([y[1] for y in trimmed_p_counts])
400
+
401
+ if search_transposed_pitches:
402
+ search_pitches = mult_pitches_counts
403
+ else:
404
+ search_pitches = [mult_pitches_counts[6]]
405
+
406
+ #===================================================
407
+
408
+ ratios_list = []
409
+
410
+ #===================================================
411
+
412
+ atrat = [0]
413
+
414
+ if add_timings_ratios:
415
+
416
+ source_times = [avg_time,
417
+ median_time,
418
+ mode_time]
419
+
420
+ match_times = meta_data[0][1][3][1]
421
+
422
+ times_ratios = []
423
+
424
+ for i in range(len(source_times)):
425
+ maxtratio = max(source_times[i], match_times[i])
426
+ mintratio = min(source_times[i], match_times[i])
427
+ times_ratios.append(mintratio / maxtratio)
428
+
429
+ avg_times_ratio = sum(times_ratios) / len(times_ratios)
430
+
431
+ atrat[0] = avg_times_ratio
432
+
433
+ #===================================================
434
+
435
+ adrat = [0]
436
+
437
+ if add_durations_ratios:
438
+
439
+ source_durs = [avg_dur,
440
+ median_dur,
441
+ mode_dur]
442
+
443
+ match_durs = meta_data[0][1][4][1]
444
+
445
+ durs_ratios = []
446
+
447
+ for i in range(len(source_durs)):
448
+ maxtratio = max(source_durs[i], match_durs[i])
449
+ mintratio = min(source_durs[i], match_durs[i])
450
+ durs_ratios.append(mintratio / maxtratio)
451
+
452
+ avg_durs_ratio = sum(durs_ratios) / len(durs_ratios)
453
+
454
+ adrat[0] = avg_durs_ratio
455
+
456
+ #===================================================
457
+
458
+ for m in search_pitches:
459
+
460
+ sprat = []
461
+
462
+ m.sort(reverse = True, key = lambda x: x[1])
463
+ max_pitches_count = m[0][1]
464
+ trimmed_pitches_counts = [y for y in m if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)]
465
+ total_pitches_counts = sum([y[1] for y in trimmed_pitches_counts])
466
+
467
+ same_pitches = set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts])
468
+ num_same_pitches = len(same_pitches)
469
+ same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in trimmed_p_counts]+[T[0] for T in trimmed_pitches_counts])))
470
+
471
+ if skip_exact_matches:
472
+ if same_pitches_ratio == 1:
473
+ same_pitches_ratio = 0
474
+
475
+ sprat.append(same_pitches_ratio)
476
+
477
+ #===================================================
478
+
479
+ spcrat = [0]
480
+
481
+ if add_pitches_counts_ratios:
482
+
483
+ same_trimmed_p_counts = sorted([T for T in trimmed_p_counts if T[0] in same_pitches], reverse = True)
484
+ same_trimmed_pitches_counts = sorted([T for T in trimmed_pitches_counts if T[0] in same_pitches], reverse = True)
485
+
486
+ same_trimmed_p_counts_ratios = [[s[0], s[1] / total_p_counts] for s in same_trimmed_p_counts]
487
+ same_trimmed_pitches_counts_ratios = [[s[0], s[1] / total_pitches_counts] for s in same_trimmed_pitches_counts]
488
+
489
+ same_pitches_counts_ratios = []
490
+
491
+ for i in range(len(same_trimmed_p_counts_ratios)):
492
+ mincratio = min(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])
493
+ maxcratio = max(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])
494
+ same_pitches_counts_ratios.append([same_trimmed_p_counts_ratios[i][0], mincratio / maxcratio])
495
+
496
+ same_counts_ratios = [s[1] for s in same_pitches_counts_ratios]
497
+
498
+ if len(same_counts_ratios) > 0:
499
+ avg_same_pitches_counts_ratio = sum(same_counts_ratios) / len(same_counts_ratios)
500
+ else:
501
+ avg_same_pitches_counts_ratio = 0
502
+
503
+ spcrat[0] = avg_same_pitches_counts_ratio
504
+
505
+ #===================================================
506
+
507
+ r_list = [sprat[0]]
508
+
509
+ if add_pitches_counts_ratios:
510
+ r_list.append(spcrat[0])
511
+
512
+ if add_timings_ratios:
513
+ r_list.append(atrat[0])
514
+
515
+ if add_durations_ratios:
516
+ r_list.append(adrat[0])
517
+
518
+ ratios_list.append(r_list)
519
+
520
+ #===================================================
521
+
522
+ avg_ratios_list = []
523
+
524
+ for r in ratios_list:
525
+ avg_ratios_list.append(sum(r) / len(r))
526
+
527
+ #===================================================
528
+
529
+ final_ratio = max(avg_ratios_list)
530
+
531
+ if final_ratio > maximum_match_ratio_to_search_for:
532
+ final_ratio = 0
533
+
534
+ final_ratios.append(final_ratio)
535
+
536
+ #=======================================================
537
+
538
+ print('-' * 70)
539
+
540
+ max_ratios = sorted(final_ratios, reverse=True)[:number_of_top_ratios_MIDIs_to_collect]
541
+
542
+ print('Max match ratio', max_ratios[0])
543
+ print('-' * 70)
544
+ print('Copying max ratios MIDIs...')
545
+
546
+ for i in range(number_of_top_ratios_MIDIs_to_collect):
547
+
548
+ max_ratio = max_ratios[i]
549
+ max_ratio_index = final_ratios.index(max_ratio)
550
+
551
+ ffn = meta_data[max_ratio_index][0]
552
+ ffn_idx = [y[0] for y in LAMD_files_list].index(ffn)
553
+
554
+ ff = LAMD_files_list[ffn_idx][1]
555
+
556
+ #=======================================================
557
+
558
+ dir_str = str(fn1)
559
+ copy_path = '/content/Output-MIDI-Dataset/'+dir_str
560
+ if not os.path.exists(copy_path):
561
+ os.mkdir(copy_path)
562
+
563
+ shutil.copy2(f, copy_path+'/'+fn)
564
+
565
+ fff = str(max_ratio * 100) + '_' + ffn
566
+
567
+ shutil.copy2(ff, copy_path+'/'+fff)
568
+
569
+ #=======================================================
570
+
571
+ print('Done!')
572
+ print('=' * 70)
573
+
574
+ #=======================================================
575
+
576
+ # Processed files counter
577
+ files_count += 1
578
+
579
+ except KeyboardInterrupt:
580
+ print('Quitting...')
581
+ print('Total number of processed MIDI files', files_count)
582
+ print('=' * 70)
583
+ break
584
+
585
+ except Exception as ex:
586
+ print('WARNING !!!')
587
+ print('=' * 70)
588
+ print('Bad file:', f)
589
+ print('Error detected:', ex)
590
+ print('=' * 70)
591
+ continue
592
+
593
+ print('Total number of processed MIDI files', files_count)
594
+ print('=' * 70)
595
+
596
+ """# Congrats! You did it! :)"""