projectlosangeles commited on
Commit
ae0d7ea
1 Parent(s): 47a452f

Upload Los_Angeles_MIDI_Dataset_Search_and_Explore.ipynb

Browse files
Los_Angeles_MIDI_Dataset_Search_and_Explore.ipynb ADDED
@@ -0,0 +1,1199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "# Los Angeles MIDI Dataset: Search and Explore (ver. 2.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
+ "gradient": {
48
+ "editing": false,
49
+ "id": "a1a45a91-d909-4fd4-b67a-5e16b971d179",
50
+ "kernelId": ""
51
+ },
52
+ "id": "fX12Yquyuihc",
53
+ "cellView": "form"
54
+ },
55
+ "outputs": [],
56
+ "source": [
57
+ "#@title Install all dependencies (run only once per session)\n",
58
+ "!git clone --depth 1 https://github.com/asigalov61/Los-Angeles-MIDI-Dataset\n",
59
+ "!pip install huggingface_hub\n",
60
+ "!pip install matplotlib\n",
61
+ "!pip install sklearn\n",
62
+ "!pip install tqdm\n",
63
+ "!apt install fluidsynth #Pip does not work for some reason. Only apt works\n",
64
+ "!pip install midi2audio"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "execution_count": null,
70
+ "metadata": {
71
+ "gradient": {
72
+ "editing": false,
73
+ "id": "b8207b76-9514-4c07-95db-95a4742e52c5",
74
+ "kernelId": ""
75
+ },
76
+ "id": "z7n9vnKmug1J",
77
+ "cellView": "form"
78
+ },
79
+ "outputs": [],
80
+ "source": [
81
+ "#@title Import all needed modules\n",
82
+ "\n",
83
+ "print('Loading core modules...')\n",
84
+ "import os\n",
85
+ "import copy\n",
86
+ "from collections import Counter\n",
87
+ "import random\n",
88
+ "import pickle\n",
89
+ "from tqdm import tqdm\n",
90
+ "\n",
91
+ "from joblib import Parallel, delayed\n",
92
+ "import multiprocessing\n",
93
+ "\n",
94
+ "if not os.path.exists('/content/LAMD'):\n",
95
+ " os.makedirs('/content/LAMD')\n",
96
+ "\n",
97
+ "print('Loading MIDI.py module...')\n",
98
+ "os.chdir('/content/Los-Angeles-MIDI-Dataset')\n",
99
+ "import MIDI\n",
100
+ "\n",
101
+ "print('Loading aux modules...')\n",
102
+ "from sklearn.metrics import pairwise_distances, pairwise\n",
103
+ "import matplotlib.pyplot as plt\n",
104
+ "\n",
105
+ "from midi2audio import FluidSynth\n",
106
+ "from IPython.display import Audio, display\n",
107
+ "\n",
108
+ "from huggingface_hub import hf_hub_download\n",
109
+ "\n",
110
+ "os.chdir('/content/')\n",
111
+ "print('Done!')"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "markdown",
116
+ "source": [
117
+ "# (PREP DATA)"
118
+ ],
119
+ "metadata": {
120
+ "id": "Erj-5wMNA1Jd"
121
+ }
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "source": [
126
+ "#@title Unzip LAMDa data\n",
127
+ "%cd /content/Los-Angeles-MIDI-Dataset/META-DATA\n",
128
+ "\n",
129
+ "print('=' * 70)\n",
130
+ "print('Unzipping META-DATA...Please wait...')\n",
131
+ "\n",
132
+ "!cat LAMDa_META_DATA.zip* > LAMDa_META_DATA.zip\n",
133
+ "print('=' * 70)\n",
134
+ "\n",
135
+ "!unzip -j LAMDa_META_DATA.zip\n",
136
+ "print('=' * 70)\n",
137
+ "\n",
138
+ "print('Done! Enjoy! :)')\n",
139
+ "print('=' * 70)\n",
140
+ "%cd /content/\n",
141
+ "\n",
142
+ "#================================================\n",
143
+ "\n",
144
+ "%cd /content/Los-Angeles-MIDI-Dataset/MIDI-MATRIXES\n",
145
+ "\n",
146
+ "print('=' * 70)\n",
147
+ "print('Unzipping MIDI-MATRIXES...Please wait...')\n",
148
+ "\n",
149
+ "!cat LAMDa_MIDI_MATRIXES.zip* > LAMDa_MIDI_MATRIXES.zip\n",
150
+ "print('=' * 70)\n",
151
+ "\n",
152
+ "!unzip -j LAMDa_MIDI_MATRIXES.zip\n",
153
+ "print('=' * 70)\n",
154
+ "\n",
155
+ "print('Done! Enjoy! :)')\n",
156
+ "print('=' * 70)\n",
157
+ "%cd /content/\n",
158
+ "\n",
159
+ "#==================================================\n",
160
+ "\n",
161
+ "%cd /content/Los-Angeles-MIDI-Dataset/TOTALS\n",
162
+ "\n",
163
+ "print('=' * 70)\n",
164
+ "print('Unzipping TOTALS...Please wait...')\n",
165
+ "\n",
166
+ "!unzip -j LAMDa_TOTALS.zip\n",
167
+ "print('=' * 70)\n",
168
+ "\n",
169
+ "print('Done! Enjoy! :)')\n",
170
+ "print('=' * 70)\n",
171
+ "%cd /content/"
172
+ ],
173
+ "metadata": {
174
+ "cellView": "form",
175
+ "id": "Shs-6PR6ie7-"
176
+ },
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "source": [
183
+ "#@title Load LAMDa data\n",
184
+ "print('=' * 70)\n",
185
+ "print('Loading LAMDa data...Please wait...')\n",
186
+ "print('=' * 70)\n",
187
+ "print('Loading LAMDa META-DATA...')\n",
188
+ "meta_data = pickle.load(open('/content/Los-Angeles-MIDI-Dataset/META-DATA/LAMDa_META_DATA.pickle', 'rb'))\n",
189
+ "print('Done!')\n",
190
+ "print('=' * 70)\n",
191
+ "print('Loading LAMDa MIDI-MATRIXES...')\n",
192
+ "midi_matrixes = pickle.load(open('/content/Los-Angeles-MIDI-Dataset/MIDI-MATRIXES/LAMDa_MIDI_MATRIXES.pickle', 'rb'))\n",
193
+ "print('Done!')\n",
194
+ "print('=' * 70)\n",
195
+ "print('Loading LAMDa TOTALS...')\n",
196
+ "totals = pickle.load(open('/content/Los-Angeles-MIDI-Dataset/TOTALS/LAMDa_TOTALS.pickle', 'rb'))\n",
197
+ "print('Done!')\n",
198
+ "print('=' * 70)\n",
199
+ "print('Enjoy!')\n",
200
+ "print('=' * 70)"
201
+ ],
202
+ "metadata": {
203
+ "id": "ML1CecXtjiGE",
204
+ "cellView": "form"
205
+ },
206
+ "execution_count": null,
207
+ "outputs": []
208
+ },
209
+ {
210
+ "cell_type": "markdown",
211
+ "source": [
212
+ "# (PREP MIDI DATASET)"
213
+ ],
214
+ "metadata": {
215
+ "id": "GDKQys8pFgtj"
216
+ }
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "source": [
221
+ "#@title Download the dataset\n",
222
+ "print('=' * 70)\n",
223
+ "print('Downloading Los Angeles MIDI Dataset...Please wait...')\n",
224
+ "print('=' * 70)\n",
225
+ "\n",
226
+ "hf_hub_download(repo_id='projectlosangeles/Los-Angeles-MIDI-Dataset', \n",
227
+ " filename='Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip',\n",
228
+ " repo_type=\"dataset\",\n",
229
+ " local_dir='/content/LAMD', \n",
230
+ " local_dir_use_symlinks=False)\n",
231
+ "print('=' * 70)\n",
232
+ "print('Done! Enjoy! :)')\n",
233
+ "print('=' * 70)"
234
+ ],
235
+ "metadata": {
236
+ "id": "U_KPkpWMCkNO",
237
+ "cellView": "form"
238
+ },
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "source": [
245
+ "#@title Unzip the dataset\n",
246
+ "%cd /content/LAMD\n",
247
+ "\n",
248
+ "print('=' * 70)\n",
249
+ "print('Unzipping Los Angeles MIDI Dataset...Please wait...')\n",
250
+ "!unzip 'Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip'\n",
251
+ "print('=' * 70)\n",
252
+ "\n",
253
+ "print('Done! Enjoy! :)')\n",
254
+ "print('=' * 70)\n",
255
+ "%cd /content/"
256
+ ],
257
+ "metadata": {
258
+ "cellView": "form",
259
+ "id": "mKFlrD98FMAP"
260
+ },
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "source": [
267
+ "#@title Create dataset files list\n",
268
+ "print('=' * 70)\n",
269
+ "print('Creating dataset files list...')\n",
270
+ "dataset_addr = \"/content/LAMD/MIDIs\"\n",
271
+ "\n",
272
+ "# os.chdir(dataset_addr)\n",
273
+ "filez = list()\n",
274
+ "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n",
275
+ " filez += [os.path.join(dirpath, file) for file in filenames]\n",
276
+ "\n",
277
+ "if filez == []:\n",
278
+ " print('Could not find any MIDI files. Please check Dataset dir...')\n",
279
+ " print('=' * 70)\n",
280
+ "\n",
281
+ "print('=' * 70)\n",
282
+ "print('Randomizing file list...')\n",
283
+ "random.shuffle(filez)\n",
284
+ "print('=' * 70)\n",
285
+ "\n",
286
+ "LAMD_files_list = []\n",
287
+ "\n",
288
+ "for f in tqdm(filez):\n",
289
+ " LAMD_files_list.append([f.split('/')[-1].split('.mid')[0], f])\n",
290
+ "print('Done!')\n",
291
+ "print('=' * 70)"
292
+ ],
293
+ "metadata": {
294
+ "cellView": "form",
295
+ "id": "nMRMnn7rHBg5"
296
+ },
297
+ "execution_count": null,
298
+ "outputs": []
299
+ },
300
+ {
301
+ "cell_type": "markdown",
302
+ "source": [
303
+ "# (PLOT TOTALS)"
304
+ ],
305
+ "metadata": {
306
+ "id": "ta6K3AOOqhpM"
307
+ }
308
+ },
309
+ {
310
+ "cell_type": "code",
311
+ "source": [
312
+ "#@title Plot Totals\n",
313
+ "\n",
314
+ "cos_sim = pairwise.cosine_similarity(\n",
315
+ " totals[0][0][4] \n",
316
+ " )\n",
317
+ "plt.figure(figsize=(8, 8))\n",
318
+ "plt.imshow(cos_sim, cmap=\"inferno\", interpolation=\"none\")\n",
319
+ "im_ratio = 1\n",
320
+ "plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)\n",
321
+ "plt.title('Times')\n",
322
+ "plt.xlabel(\"Position\")\n",
323
+ "plt.ylabel(\"Position\")\n",
324
+ "plt.tight_layout()\n",
325
+ "plt.plot()\n",
326
+ "\n",
327
+ "cos_sim = pairwise.cosine_similarity(\n",
328
+ " totals[0][0][5] \n",
329
+ " )\n",
330
+ "plt.figure(figsize=(8, 8))\n",
331
+ "plt.imshow(cos_sim, cmap=\"inferno\", interpolation=\"none\")\n",
332
+ "im_ratio = 1\n",
333
+ "plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)\n",
334
+ "plt.title('Durations')\n",
335
+ "plt.xlabel(\"Position\")\n",
336
+ "plt.ylabel(\"Position\")\n",
337
+ "plt.tight_layout()\n",
338
+ "plt.plot()\n",
339
+ "\n",
340
+ "cos_sim = pairwise.cosine_similarity(\n",
341
+ " totals[0][0][6] \n",
342
+ " )\n",
343
+ "plt.figure(figsize=(8, 8))\n",
344
+ "plt.imshow(cos_sim, cmap=\"inferno\", interpolation=\"none\")\n",
345
+ "im_ratio = 1\n",
346
+ "plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)\n",
347
+ "plt.title('Channels')\n",
348
+ "plt.xlabel(\"Position\")\n",
349
+ "plt.ylabel(\"Position\")\n",
350
+ "plt.tight_layout()\n",
351
+ "plt.plot()\n",
352
+ "\n",
353
+ "cos_sim = pairwise.cosine_similarity(\n",
354
+ " totals[0][0][7] \n",
355
+ " )\n",
356
+ "plt.figure(figsize=(8, 8))\n",
357
+ "plt.imshow(cos_sim, cmap=\"inferno\", interpolation=\"none\")\n",
358
+ "im_ratio = 1\n",
359
+ "plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)\n",
360
+ "plt.title('Instruments')\n",
361
+ "plt.xlabel(\"Position\")\n",
362
+ "plt.ylabel(\"Position\")\n",
363
+ "plt.tight_layout()\n",
364
+ "plt.plot()\n",
365
+ "\n",
366
+ "cos_sim = pairwise.cosine_similarity(\n",
367
+ " totals[0][0][8] \n",
368
+ " )\n",
369
+ "plt.figure(figsize=(8, 8))\n",
370
+ "plt.imshow(cos_sim, cmap=\"inferno\", interpolation=\"none\")\n",
371
+ "im_ratio = 1\n",
372
+ "plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)\n",
373
+ "plt.title('Pitches')\n",
374
+ "plt.xlabel(\"Position\")\n",
375
+ "plt.ylabel(\"Position\")\n",
376
+ "plt.tight_layout()\n",
377
+ "plt.plot()\n",
378
+ "\n",
379
+ "cos_sim = pairwise.cosine_similarity(\n",
380
+ " totals[0][0][9] \n",
381
+ " )\n",
382
+ "plt.figure(figsize=(8, 8))\n",
383
+ "plt.imshow(cos_sim, cmap=\"inferno\", interpolation=\"none\")\n",
384
+ "im_ratio = 1\n",
385
+ "plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)\n",
386
+ "plt.title('Velocities')\n",
387
+ "plt.xlabel(\"Position\")\n",
388
+ "plt.ylabel(\"Position\")\n",
389
+ "plt.tight_layout()\n",
390
+ "plt.plot()"
391
+ ],
392
+ "metadata": {
393
+ "cellView": "form",
394
+ "id": "Tk-3Q3UnqkpL"
395
+ },
396
+ "execution_count": null,
397
+ "outputs": []
398
+ },
399
+ {
400
+ "cell_type": "markdown",
401
+ "source": [
402
+ "# (LOAD SOURCE MIDI)"
403
+ ],
404
+ "metadata": {
405
+ "id": "jiVsfC0u7aAQ"
406
+ }
407
+ },
408
+ {
409
+ "cell_type": "code",
410
+ "source": [
411
+ "#@title Load source MIDI\n",
412
+ "\n",
413
+ "full_path_to_source_MIDI = \"/content/Los-Angeles-MIDI-Dataset/Come-To-My-Window-Modified-Sample-MIDI.mid\" #@param {type:\"string\"}\n",
414
+ "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
415
+ "\n",
416
+ "#=================================================================================\n",
417
+ "\n",
418
+ "f = full_path_to_source_MIDI\n",
419
+ "\n",
420
+ "print('=' * 70)\n",
421
+ "print('Loading MIDI file...')\n",
422
+ "\n",
423
+ "score = MIDI.midi2ms_score(open(f, 'rb').read())\n",
424
+ "\n",
425
+ "events_matrix = []\n",
426
+ "\n",
427
+ "itrack = 1\n",
428
+ "\n",
429
+ "while itrack < len(score):\n",
430
+ " for event in score[itrack]: \n",
431
+ " events_matrix.append(event)\n",
432
+ " itrack += 1\n",
433
+ "\n",
434
+ "# Sorting...\n",
435
+ "events_matrix.sort(key=lambda x: x[1])\n",
436
+ "\n",
437
+ "# recalculating timings\n",
438
+ "for e in events_matrix:\n",
439
+ " e[1] = int(e[1] / 10)\n",
440
+ " if e[0] == 'note':\n",
441
+ " e[2] = int(e[2] / 20)\n",
442
+ "\n",
443
+ "# final processing...\n",
444
+ "\n",
445
+ "melody_chords = []\n",
446
+ "\n",
447
+ "patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n",
448
+ "\n",
449
+ "pe = events_matrix[0]\n",
450
+ "for e in events_matrix:\n",
451
+ "\n",
452
+ " if e[0] == 'note':\n",
453
+ " # ['note', start_time, duration, channel, note, velocity]\n",
454
+ " time = max(0, min(255, e[1]-pe[1]))\n",
455
+ " duration = max(1, min(255, e[2]))\n",
456
+ " channel = max(0, min(15, e[3]))\n",
457
+ "\n",
458
+ " if e[3] != 9:\n",
459
+ " instrument = max(0, min(127, patches[e[3]]))\n",
460
+ " else:\n",
461
+ " instrument = max(128, min(255, patches[e[3]]+128))\n",
462
+ "\n",
463
+ " if e[3] != 9:\n",
464
+ "\n",
465
+ " pitch = max(1, min(127, e[4]))\n",
466
+ " else:\n",
467
+ " pitch = max(129, min(255, e[4]+128))\n",
468
+ "\n",
469
+ " if e[3] != 9:\n",
470
+ " velocity = max(1, min(127, e[5]))\n",
471
+ " else:\n",
472
+ " velocity = max(129, min(255, e[5]+128))\n",
473
+ "\n",
474
+ " melody_chords.append([time, duration, channel, instrument, pitch, velocity])\n",
475
+ "\n",
476
+ " if e[0] == 'patch_change':\n",
477
+ " # ['patch_change', dtime, channel, patch]\n",
478
+ " time = max(0, min(127, e[1]-pe[1]))\n",
479
+ " channel = max(0, min(15, e[2]))\n",
480
+ " patch = max(0, min(127, e[3]))\n",
481
+ "\n",
482
+ " patches[channel] = patch\n",
483
+ "\n",
484
+ " pe = e # Previous event\n",
485
+ "\n",
486
+ "MATRIX = [[0]*256 for i in range(38)]\n",
487
+ "\n",
488
+ "for m in melody_chords:\n",
489
+ "\n",
490
+ " MATRIX[0][m[0]] += 1\n",
491
+ " MATRIX[1][m[1]] += 1\n",
492
+ " MATRIX[2][m[2]] += 1 \n",
493
+ " MATRIX[3][m[3]] += 1\n",
494
+ " MATRIX[4][m[4]] += 1\n",
495
+ " MATRIX[5][m[5]] += 1\n",
496
+ " MATRIX[m[2]+6][m[3]] += 1\n",
497
+ " MATRIX[m[2]+22][m[4]] += 1\n",
498
+ "\n",
499
+ "#==================================================\n",
500
+ "\n",
501
+ "score = MIDI.midi2score(open(f, 'rb').read())\n",
502
+ "\n",
503
+ "events_matrix = []\n",
504
+ "\n",
505
+ "track_count = 0\n",
506
+ "\n",
507
+ "for s in score:\n",
508
+ " \n",
509
+ " if track_count > 0:\n",
510
+ " track = s\n",
511
+ " track.sort(key=lambda x: x[1])\n",
512
+ " events_matrix.extend(track)\n",
513
+ " else:\n",
514
+ " midi_ticks = s\n",
515
+ "\n",
516
+ " track_count += 1\n",
517
+ " \n",
518
+ "events_matrix.sort(key=lambda x: x[1])\n",
519
+ "\n",
520
+ "for e in events_matrix:\n",
521
+ " if e[0] == 'note':\n",
522
+ " if e[3] == 9:\n",
523
+ " e[4] = ((e[4] % 128) + 128)\n",
524
+ "\n",
525
+ "pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix if y[0] == 'note']).most_common()]\n",
526
+ "pitches_counts.sort(key=lambda x: x[0], reverse=True)\n",
527
+ "\n",
528
+ "patches_list = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))\n",
529
+ "\n",
530
+ "print('=' * 70)\n",
531
+ "print('Done!')\n",
532
+ "print('=' * 70)\n",
533
+ "\n",
534
+ "#============================================\n",
535
+ "# MIDI rendering code\n",
536
+ "#============================================\n",
537
+ "\n",
538
+ "print('Rendering source MIDI...')\n",
539
+ "print('=' * 70)\n",
540
+ "\n",
541
+ "ms_score = MIDI.midi2ms_score(open(f, 'rb').read())\n",
542
+ "\n",
543
+ "itrack = 1\n",
544
+ "song_f = []\n",
545
+ "\n",
546
+ "while itrack < len(ms_score):\n",
547
+ " for event in ms_score[itrack]: \n",
548
+ " if event[0] == 'note':\n",
549
+ " song_f.append(event)\n",
550
+ " itrack += 1\n",
551
+ "\n",
552
+ "song_f.sort(key=lambda x: x[1])\n",
553
+ "\n",
554
+ "fname = f.split('.mid')[0]\n",
555
+ "\n",
556
+ "x = []\n",
557
+ "y =[]\n",
558
+ "c = []\n",
559
+ "\n",
560
+ "colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']\n",
561
+ "\n",
562
+ "for s in song_f:\n",
563
+ " x.append(s[1] / 1000)\n",
564
+ " y.append(s[4])\n",
565
+ " c.append(colors[s[3]])\n",
566
+ "\n",
567
+ "if render_MIDI_to_audio:\n",
568
+ " FluidSynth(\"/usr/share/sounds/sf2/FluidR3_GM.sf2\", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))\n",
569
+ " display(Audio(str(fname + '.wav'), rate=16000))\n",
570
+ "\n",
571
+ "plt.figure(figsize=(14,5))\n",
572
+ "ax=plt.axes(title=fname)\n",
573
+ "ax.set_facecolor('black')\n",
574
+ "\n",
575
+ "plt.scatter(x,y, c=c)\n",
576
+ "plt.xlabel(\"Time\")\n",
577
+ "plt.ylabel(\"Pitch\")\n",
578
+ "plt.show()"
579
+ ],
580
+ "metadata": {
581
+ "cellView": "form",
582
+ "id": "z7mm6WsDmuRi"
583
+ },
584
+ "execution_count": null,
585
+ "outputs": []
586
+ },
587
+ {
588
+ "cell_type": "markdown",
589
+ "source": [
590
+ "# (SEARCH AND EXPLORE)"
591
+ ],
592
+ "metadata": {
593
+ "id": "LRnuphuiqc5F"
594
+ }
595
+ },
596
+ {
597
+ "cell_type": "code",
598
+ "source": [
599
+ "#@title Legacy MIDI Matrixes Search (Slow)\n",
600
+ "matching_type = \"minkowski\" #@param {type:\"string\"}\n",
601
+ "stop_search_on_exact_match = True #@param {type:\"boolean\"}\n",
602
+ "\n",
603
+ "#=================================================================================\n",
604
+ "\n",
605
+ "def compress_matrix(midi_matrix):\n",
606
+ "\n",
607
+ " MX = 38\n",
608
+ " MY = 256\n",
609
+ "\n",
610
+ " if len(midi_matrix) == MX:\n",
611
+ "\n",
612
+ " compressed_matrix = []\n",
613
+ " zeros = 0\n",
614
+ " zeros_shift = 0\n",
615
+ " zeros_count = 0\n",
616
+ "\n",
617
+ " for m in midi_matrix:\n",
618
+ " for mm in m:\n",
619
+ " zeros_shift = max(zeros_shift, mm) + 1\n",
620
+ "\n",
621
+ " compressed_matrix.append(zeros_shift)\n",
622
+ "\n",
623
+ " for m in midi_matrix:\n",
624
+ " if len(m) == MY:\n",
625
+ " for mm in m:\n",
626
+ " if mm != 0:\n",
627
+ " if zeros > 0:\n",
628
+ " compressed_matrix.append(zeros+zeros_shift)\n",
629
+ " zeros = 0\n",
630
+ " compressed_matrix.append(mm)\n",
631
+ " \n",
632
+ " else:\n",
633
+ " zeros += 1\n",
634
+ " zeros_count += 1\n",
635
+ " \n",
636
+ " else:\n",
637
+ " print('Wrong matrix format!')\n",
638
+ " return [1]\n",
639
+ "\n",
640
+ " if zeros > 0:\n",
641
+ " compressed_matrix.append(zeros+zeros_shift)\n",
642
+ "\n",
643
+ " compressed_matrix.append(zeros_count+zeros_shift)\n",
644
+ " compressed_matrix.append(zeros_shift)\n",
645
+ "\n",
646
+ " return compressed_matrix\n",
647
+ "\n",
648
+ " else:\n",
649
+ " print('Wrong matrix format!')\n",
650
+ " return [0]\n",
651
+ "\n",
652
+ "#=================================================================================\n",
653
+ "\n",
654
+ "def decompress_matrix(compressed_midi_matrix):\n",
655
+ "\n",
656
+ " MX = 38\n",
657
+ " MY = 256\n",
658
+ "\n",
659
+ " zeros_count = 0\n",
660
+ "\n",
661
+ " temp_matrix = []\n",
662
+ " decompressed_matrix = [[0]*MY for i in range(MX)]\n",
663
+ "\n",
664
+ " if compressed_midi_matrix[0] == compressed_midi_matrix[-1]:\n",
665
+ " zeros_shift = compressed_midi_matrix[0]\n",
666
+ " mcount = 0\n",
667
+ "\n",
668
+ " for c in compressed_midi_matrix[1:-2]:\n",
669
+ " if c > zeros_shift:\n",
670
+ " temp_matrix.extend([0] * (c-zeros_shift))\n",
671
+ " zeros_count += (c-zeros_shift)\n",
672
+ "\n",
673
+ " else:\n",
674
+ " temp_matrix.extend([c])\n",
675
+ "\n",
676
+ " if len(temp_matrix) == (MX * MY):\n",
677
+ "\n",
678
+ " for i in range(MX):\n",
679
+ " for j in range(MY):\n",
680
+ " decompressed_matrix[i][j] = copy.deepcopy(temp_matrix[(i*MY) + j])\n",
681
+ " \n",
682
+ " if len(decompressed_matrix) == MX and zeros_count == (compressed_midi_matrix[-2]-zeros_shift):\n",
683
+ " return decompressed_matrix\n",
684
+ "\n",
685
+ " else:\n",
686
+ " print('Matrix is corrupted!')\n",
687
+ " return [len(decompressed_matrix), (MX * MY), zeros_count, (compressed_midi_matrix[-2]-zeros_shift)]\n",
688
+ " \n",
689
+ " else:\n",
690
+ " print('Matrix is corrupted!')\n",
691
+ " return [len(temp_matrix), zeros_count]\n",
692
+ "\n",
693
+ " else:\n",
694
+ " print('Matrix is corrupted!')\n",
695
+ " return [0]\n",
696
+ "\n",
697
+ "#=================================================================================\n",
698
+ "\n",
699
+ "def batched_scores(matbatch, matrix):\n",
700
+ "\n",
701
+ " sco= []\n",
702
+ " for D in matbatch:\n",
703
+ "\n",
704
+ " dist = pairwise_distances(matrix, decompress_matrix(D[1]), metric=matching_type)[0][0] \n",
705
+ " sco.append(dist)\n",
706
+ "\n",
707
+ " return sco\n",
708
+ "\n",
709
+ "#=================================================================================\n",
710
+ "\n",
711
+ "print('=' * 70)\n",
712
+ "print('Searching...Please wait...')\n",
713
+ "print('=' * 70)\n",
714
+ "\n",
715
+ "scores = []\n",
716
+ "\n",
717
+ "c_count = multiprocessing.cpu_count()\n",
718
+ "\n",
719
+ "par = Parallel(n_jobs=c_count)\n",
720
+ "\n",
721
+ "num_jobs = c_count\n",
722
+ "scores_per_job = 100\n",
723
+ "\n",
724
+ "MATRIX_X = [MATRIX] * num_jobs\n",
725
+ "\n",
726
+ "for i in tqdm(range(0, len(midi_matrixes), (num_jobs*scores_per_job))):\n",
727
+ " \n",
728
+ " try:\n",
729
+ "\n",
730
+ " MAT_BATCHES = []\n",
731
+ "\n",
732
+ " for j in range(num_jobs):\n",
733
+ " MAT_BATCHES.append(midi_matrixes[i+(j*scores_per_job):i+((j+1)*scores_per_job)])\n",
734
+ "\n",
735
+ " output = par(delayed(batched_scores) (MB, MAT) for MB, MAT in zip(MAT_BATCHES, MATRIX_X))\n",
736
+ "\n",
737
+ " output1 = []\n",
738
+ "\n",
739
+ " for o in output:\n",
740
+ " output1.extend(o)\n",
741
+ "\n",
742
+ " scores.extend(output1) \n",
743
+ "\n",
744
+ " if stop_search_on_exact_match:\n",
745
+ " if 0 in output1:\n",
746
+ " print('=' * 70)\n",
747
+ " print('Found exact match!')\n",
748
+ " print('Stoping further search...')\n",
749
+ " print('=' * 70)\n",
750
+ " break\n",
751
+ "\n",
752
+ " else:\n",
753
+ " if 0 in output1:\n",
754
+ " print('=' * 70)\n",
755
+ " print('Found exact match!')\n",
756
+ " print('=' * 70)\n",
757
+ " print('LAMDa Index:', scores.index(min(scores)))\n",
758
+ " print('LAMDa File Name:', midi_matrixes[scores.index(min(scores))][0])\n",
759
+ " print('=' * 70)\n",
760
+ " print('Continuing search...')\n",
761
+ " print('=' * 70)\n",
762
+ " except KeyboardInterrupt:\n",
763
+ " break\n",
764
+ " \n",
765
+ " except:\n",
766
+ " continue\n",
767
+ "\n",
768
+ "print('Done!')\n",
769
+ "print('=' * 70)\n",
770
+ "print('Best match:')\n",
771
+ "print('=' * 70) \n",
772
+ "print(matching_type.title(), 'distance ==', min(scores))\n",
773
+ "print('LAMDa Index:', scores.index(min(scores)))\n",
774
+ "print('LAMDa File Name:', midi_matrixes[scores.index(min(scores))][0])\n",
775
+ "print('=' * 70)\n",
776
+ "\n",
777
+ "print('Top 100 matches')\n",
778
+ "print('=' * 70)\n",
779
+ "\n",
780
+ "top_matches = []\n",
781
+ "\n",
782
+ "for i in range(len(scores)):\n",
783
+ " top_matches.append([midi_matrixes[i][0], scores[i]])\n",
784
+ "\n",
785
+ "top_matches.sort(key=lambda x: x[1])\n",
786
+ "\n",
787
+ "for t in top_matches[:100]:\n",
788
+ " print(t)\n",
789
+ " \n",
790
+ "print('=' * 70)"
791
+ ],
792
+ "metadata": {
793
+ "cellView": "form",
794
+ "id": "pNQG6Qgfrlfi"
795
+ },
796
+ "execution_count": null,
797
+ "outputs": []
798
+ },
799
+ {
800
+ "cell_type": "code",
801
+ "source": [
802
+ "#@title MIDI Pitches Search\n",
803
+ "\n",
804
+ "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
805
+ "\n",
806
+ "print('=' * 70)\n",
807
+ "print('MIDI Pitches Search')\n",
808
+ "print('=' * 70)\n",
809
+ "\n",
810
+ "ratios = []\n",
811
+ "\n",
812
+ "for d in tqdm(meta_data):\n",
813
+ " p_counts = d[1][3][1]\n",
814
+ "\n",
815
+ " num_same_pitches = len(set([T[0] for T in p_counts]) & set([m[0] for m in pitches_counts]))\n",
816
+ " same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in p_counts]+[T[0] for T in pitches_counts])))\n",
817
+ "\n",
818
+ " ratios.append(same_pitches_ratio)\n",
819
+ "\n",
820
+ "max_ratio = max(ratios)\n",
821
+ "max_ratio_index = ratios.index(max(ratios))\n",
822
+ "\n",
823
+ "print('FOUND')\n",
824
+ "print('=' * 70)\n",
825
+ "print('Match ratio', max_ratio)\n",
826
+ "print('MIDI file name', meta_data[max_ratio_index][0])\n",
827
+ "print('=' * 70)\n",
828
+ "print('First metadata MIDI event', meta_data[max_ratio_index][1][0])\n",
829
+ "print('=' * 70)\n",
830
+ "\n",
831
+ "#============================================\n",
832
+ "# MIDI rendering code\n",
833
+ "#============================================\n",
834
+ "\n",
835
+ "print('Rendering source MIDI...')\n",
836
+ "print('=' * 70)\n",
837
+ "\n",
838
+ "fn = meta_data[max_ratio_index][0]\n",
839
+ "fn_idx = [y[0] for y in LAMD_files_list].index(fn)\n",
840
+ "\n",
841
+ "f = LAMD_files_list[fn_idx][1]\n",
842
+ "\n",
843
+ "ms_score = MIDI.midi2ms_score(open(f, 'rb').read())\n",
844
+ "\n",
845
+ "itrack = 1\n",
846
+ "song_f = []\n",
847
+ "\n",
848
+ "while itrack < len(ms_score):\n",
849
+ " for event in ms_score[itrack]: \n",
850
+ " if event[0] == 'note':\n",
851
+ " song_f.append(event)\n",
852
+ " itrack += 1\n",
853
+ "\n",
854
+ "song_f.sort(key=lambda x: x[1])\n",
855
+ "\n",
856
+ "fname = f.split('.mid')[0]\n",
857
+ "\n",
858
+ "x = []\n",
859
+ "y =[]\n",
860
+ "c = []\n",
861
+ "\n",
862
+ "colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']\n",
863
+ "\n",
864
+ "for s in song_f:\n",
865
+ " x.append(s[1] / 1000)\n",
866
+ " y.append(s[4])\n",
867
+ " c.append(colors[s[3]])\n",
868
+ "\n",
869
+ "if render_MIDI_to_audio:\n",
870
+ " FluidSynth(\"/usr/share/sounds/sf2/FluidR3_GM.sf2\", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))\n",
871
+ " display(Audio(str(fname + '.wav'), rate=16000))\n",
872
+ "\n",
873
+ "plt.figure(figsize=(14,5))\n",
874
+ "ax=plt.axes(title=fname)\n",
875
+ "ax.set_facecolor('black')\n",
876
+ "\n",
877
+ "plt.scatter(x,y, c=c)\n",
878
+ "plt.xlabel(\"Time\")\n",
879
+ "plt.ylabel(\"Pitch\")\n",
880
+ "plt.show()"
881
+ ],
882
+ "metadata": {
883
+ "cellView": "form",
884
+ "id": "C-P71_9ojh8G"
885
+ },
886
+ "execution_count": null,
887
+ "outputs": []
888
+ },
889
+ {
890
+ "cell_type": "code",
891
+ "source": [
892
+ "#@title MIDI Patches Search\n",
893
+ "\n",
894
+ "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
895
+ "\n",
896
+ "print('=' * 70)\n",
897
+ "print('MIDI Patches Search')\n",
898
+ "print('=' * 70)\n",
899
+ "\n",
900
+ "ratios = []\n",
901
+ "\n",
902
+ "for d in tqdm(meta_data):\n",
903
+ " p_list= d[1][4][1]\n",
904
+ "\n",
905
+ " num_same_patches = len(set(p_list) & set(patches_list))\n",
906
+ " \n",
907
+ " if len(set(p_list + patches_list)) > 0:\n",
908
+ " same_patches_ratio = num_same_patches / len(set(p_list + patches_list))\n",
909
+ " else:\n",
910
+ " same_patches_ratio = 0\n",
911
+ "\n",
912
+ " ratios.append(same_patches_ratio)\n",
913
+ "\n",
914
+ "max_ratio = max(ratios)\n",
915
+ "max_ratio_index = ratios.index(max(ratios))\n",
916
+ "\n",
917
+ "print('FOUND')\n",
918
+ "print('=' * 70)\n",
919
+ "print('Match ratio', max_ratio)\n",
920
+ "print('MIDI file name', meta_data[max_ratio_index][0])\n",
921
+ "print('=' * 70)\n",
922
+ "print('Found MIDI patches list', meta_data[max_ratio_index][1][4][1])\n",
923
+ "print('=' * 70)\n",
924
+ "\n",
925
+ "#============================================\n",
926
+ "# MIDI rendering code\n",
927
+ "#============================================\n",
928
+ "\n",
929
+ "print('Rendering source MIDI...')\n",
930
+ "print('=' * 70)\n",
931
+ "\n",
932
+ "fn = meta_data[max_ratio_index][0]\n",
933
+ "fn_idx = [y[0] for y in LAMD_files_list].index(fn)\n",
934
+ "\n",
935
+ "f = LAMD_files_list[fn_idx][1]\n",
936
+ "\n",
937
+ "ms_score = MIDI.midi2ms_score(open(f, 'rb').read())\n",
938
+ "\n",
939
+ "itrack = 1\n",
940
+ "song_f = []\n",
941
+ "\n",
942
+ "while itrack < len(ms_score):\n",
943
+ " for event in ms_score[itrack]: \n",
944
+ " if event[0] == 'note':\n",
945
+ " song_f.append(event)\n",
946
+ " itrack += 1\n",
947
+ "\n",
948
+ "song_f.sort(key=lambda x: x[1])\n",
949
+ "\n",
950
+ "fname = f.split('.mid')[0]\n",
951
+ "\n",
952
+ "x = []\n",
953
+ "y =[]\n",
954
+ "c = []\n",
955
+ "\n",
956
+ "colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']\n",
957
+ "\n",
958
+ "for s in song_f:\n",
959
+ " x.append(s[1] / 1000)\n",
960
+ " y.append(s[4])\n",
961
+ " c.append(colors[s[3]])\n",
962
+ "\n",
963
+ "if render_MIDI_to_audio:\n",
964
+ " FluidSynth(\"/usr/share/sounds/sf2/FluidR3_GM.sf2\", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))\n",
965
+ " display(Audio(str(fname + '.wav'), rate=16000))\n",
966
+ "\n",
967
+ "plt.figure(figsize=(14,5))\n",
968
+ "ax=plt.axes(title=fname)\n",
969
+ "ax.set_facecolor('black')\n",
970
+ "\n",
971
+ "plt.scatter(x,y, c=c)\n",
972
+ "plt.xlabel(\"Time\")\n",
973
+ "plt.ylabel(\"Pitch\")\n",
974
+ "plt.show()"
975
+ ],
976
+ "metadata": {
977
+ "cellView": "form",
978
+ "id": "JmV8VNj-tz1m"
979
+ },
980
+ "execution_count": null,
981
+ "outputs": []
982
+ },
983
+ {
984
+ "cell_type": "code",
985
+ "source": [
986
+ "#@title Metadata Search\n",
987
+ "search_query = \"Come To My Window\" #@param {type:\"string\"}\n",
988
+ "case_sensitive_search = False #@param {type:\"boolean\"}\n",
989
+ "\n",
990
+ "fields_to_search = ['track_name', \n",
991
+ " 'text_event', \n",
992
+ " 'lyric', \n",
993
+ " 'copyright_text_event', \n",
994
+ " 'marker',\n",
995
+ " 'text_event_08',\n",
996
+ " 'text_event_09',\n",
997
+ " 'text_event_0a',\n",
998
+ " 'text_event_0b',\n",
999
+ " 'text_event_0c',\n",
1000
+ " 'text_event_0d',\n",
1001
+ " 'text_event_0e',\n",
1002
+ " 'text_event_0f',\n",
1003
+ " ]\n",
1004
+ "\n",
1005
+ "print('=' * 70)\n",
1006
+ "print('Sarching...')\n",
1007
+ "print('=' * 70)\n",
1008
+ "\n",
1009
+ "for d in tqdm(meta_data):\n",
1010
+ " for dd in d[1]:\n",
1011
+ " if dd[0] in fields_to_search:\n",
1012
+ " if case_sensitive_search:\n",
1013
+ " if str(search_query) in str(dd[2]):\n",
1014
+ " print('Found!')\n",
1015
+ " print('=' * 70)\n",
1016
+ " print('Metadata index:', meta_data.index(d))\n",
1017
+ " print('MIDI file name:', meta_data[meta_data.index(d)][0])\n",
1018
+ " print('Result:', dd[2])\n",
1019
+ " print('=' * 70)\n",
1020
+ " \n",
1021
+ " else:\n",
1022
+ " if str(search_query).lower() in str(dd[2]).lower():\n",
1023
+ " print('Found!')\n",
1024
+ " print('=' * 70)\n",
1025
+ " print('Metadata index:', meta_data.index(d))\n",
1026
+ " print('MIDI file name:', meta_data[meta_data.index(d)][0])\n",
1027
+ " print('Result:', dd[2])\n",
1028
+ " print('=' * 70)"
1029
+ ],
1030
+ "metadata": {
1031
+ "cellView": "form",
1032
+ "id": "98JuBEdMqIE3"
1033
+ },
1034
+ "execution_count": null,
1035
+ "outputs": []
1036
+ },
1037
+ {
1038
+ "cell_type": "markdown",
1039
+ "source": [
1040
+ "# (CUSTOM ANALYSIS TEMPLATE)"
1041
+ ],
1042
+ "metadata": {
1043
+ "id": "jNH-J2ry7sLj"
1044
+ }
1045
+ },
1046
+ {
1047
+ "cell_type": "code",
1048
+ "source": [
1049
+ "#@title Los Angeles MIDI Dataset Reader\n",
1050
+ "\n",
1051
+ "print('=' * 70)\n",
1052
+ "print('Los Angeles MIDI Dataset Reader')\n",
1053
+ "print('=' * 70)\n",
1054
+ "print('Starting up...')\n",
1055
+ "print('=' * 70)\n",
1056
+ "\n",
1057
+ "###########\n",
1058
+ "\n",
1059
+ "print('Loading MIDI files...')\n",
1060
+ "print('This may take a while on a large dataset in particular.')\n",
1061
+ "\n",
1062
+ "dataset_addr = \"/content/LAMD/MIDIs\"\n",
1063
+ "\n",
1064
+ "# os.chdir(dataset_addr)\n",
1065
+ "filez = list()\n",
1066
+ "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n",
1067
+ " filez += [os.path.join(dirpath, file) for file in filenames]\n",
1068
+ "\n",
1069
+ "if filez == []:\n",
1070
+ " print('Could not find any MIDI files. Please check Dataset dir...')\n",
1071
+ " print('=' * 70)\n",
1072
+ "\n",
1073
+ "print('=' * 70)\n",
1074
+ "print('Randomizing file list...')\n",
1075
+ "random.shuffle(filez)\n",
1076
+ "print('=' * 70)\n",
1077
+ "\n",
1078
+ "###########\n",
1079
+ "\n",
1080
+ "START_FILE_NUMBER = 0\n",
1081
+ "LAST_SAVED_BATCH_COUNT = 0\n",
1082
+ "\n",
1083
+ "input_files_count = START_FILE_NUMBER\n",
1084
+ "files_count = LAST_SAVED_BATCH_COUNT\n",
1085
+ "\n",
1086
+ "stats = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n",
1087
+ "\n",
1088
+ "print('Reading MIDI files. Please wait...')\n",
1089
+ "print('=' * 70)\n",
1090
+ "\n",
1091
+ "for f in tqdm(filez[START_FILE_NUMBER:]):\n",
1092
+ " try:\n",
1093
+ " input_files_count += 1\n",
1094
+ "\n",
1095
+ " fn = os.path.basename(f)\n",
1096
+ " fn1 = fn.split('.mid')[0]\n",
1097
+ "\n",
1098
+ " #=======================================================\n",
1099
+ " # START PROCESSING\n",
1100
+ " #=======================================================\n",
1101
+ "\n",
1102
+ " # Convering MIDI to score with MIDI.py module\n",
1103
+ " score = MIDI.midi2score(open(f, 'rb').read())\n",
1104
+ "\n",
1105
+ " events_matrix = []\n",
1106
+ " \n",
1107
+ " itrack = 1\n",
1108
+ "\n",
1109
+ " while itrack < len(score):\n",
1110
+ " for event in score[itrack]: \n",
1111
+ " events_matrix.append(event)\n",
1112
+ " itrack += 1\n",
1113
+ "\n",
1114
+ " # Sorting...\n",
1115
+ " events_matrix.sort(key=lambda x: x[1])\n",
1116
+ "\n",
1117
+ " if len(events_matrix) > 0:\n",
1118
+ " \n",
1119
+ " #=======================================================\n",
1120
+ " # INSERT YOUR CUSTOM ANAYLSIS CODE RIGHT HERE\n",
1121
+ " #=======================================================\n",
1122
+ "\n",
1123
+ " # Processed files counter\n",
1124
+ " files_count += 1\n",
1125
+ "\n",
1126
+ " # Saving every 5000 processed files\n",
1127
+ " if files_count % 10000 == 0:\n",
1128
+ " print('=' * 70)\n",
1129
+ " print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')\n",
1130
+ " print('=' * 70)\n",
1131
+ "\n",
1132
+ " except KeyboardInterrupt:\n",
1133
+ " print('Saving current progress and quitting...')\n",
1134
+ " break \n",
1135
+ "\n",
1136
+ " except Exception as ex:\n",
1137
+ " print('WARNING !!!')\n",
1138
+ " print('=' * 70)\n",
1139
+ " print('Bad MIDI:', f)\n",
1140
+ " print('Error detected:', ex)\n",
1141
+ " print('=' * 70)\n",
1142
+ " continue\n",
1143
+ "\n",
1144
+ "print('=' * 70)\n",
1145
+ "print('Final files counts:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')\n",
1146
+ "print('=' * 70)\n",
1147
+ "\n",
1148
+ "print('Resulting Stats:')\n",
1149
+ "print('=' * 70)\n",
1150
+ "print('Total good processed MIDI files:', files_count)\n",
1151
+ "print('=' * 70)\n",
1152
+ "print('Done!') \n",
1153
+ "print('=' * 70)"
1154
+ ],
1155
+ "metadata": {
1156
+ "id": "xrmnVUkXGsUi",
1157
+ "cellView": "form"
1158
+ },
1159
+ "execution_count": null,
1160
+ "outputs": []
1161
+ },
1162
+ {
1163
+ "cell_type": "markdown",
1164
+ "metadata": {
1165
+ "id": "YzCMd94Tu_gz"
1166
+ },
1167
+ "source": [
1168
+ "# Congrats! You did it! :)"
1169
+ ]
1170
+ }
1171
+ ],
1172
+ "metadata": {
1173
+ "colab": {
1174
+ "private_outputs": true,
1175
+ "provenance": [],
1176
+ "machine_shape": "hm"
1177
+ },
1178
+ "kernelspec": {
1179
+ "display_name": "Python 3 (ipykernel)",
1180
+ "language": "python",
1181
+ "name": "python3"
1182
+ },
1183
+ "language_info": {
1184
+ "codemirror_mode": {
1185
+ "name": "ipython",
1186
+ "version": 3
1187
+ },
1188
+ "file_extension": ".py",
1189
+ "mimetype": "text/x-python",
1190
+ "name": "python",
1191
+ "nbconvert_exporter": "python",
1192
+ "pygments_lexer": "ipython3",
1193
+ "version": "3.9.7"
1194
+ },
1195
+ "gpuClass": "standard"
1196
+ },
1197
+ "nbformat": 4,
1198
+ "nbformat_minor": 0
1199
+ }