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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "private_outputs": true,
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# MIDI Images Solo Piano Dataset Maker (ver. 1.0)\n",
        "\n",
        "***\n",
        "\n",
        "Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools\n",
        "\n",
        "***\n",
        "\n",
        "#### Project Los Angeles\n",
        "\n",
        "#### Tegridy Code 2024\n",
        "\n",
        "***"
      ],
      "metadata": {
        "id": "LUgrspEA-68o"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (SETUP ENVIRONMENT)"
      ],
      "metadata": {
        "id": "7N-KXNgQ_a0h"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pxNxlyfZ8hCg",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        "# @title Install dependecies\n",
        "!git clone --depth 1 https://github.com/asigalov61/tegridy-tools"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Import all needed modules\n",
        "\n",
        "print('=' * 70)\n",
        "print('Loading core modules...')\n",
        "print('Please wait...')\n",
        "print('=' * 70)\n",
        "\n",
        "import os\n",
        "import copy\n",
        "import math\n",
        "import statistics\n",
        "import random\n",
        "import pickle\n",
        "import shutil\n",
        "from itertools import groupby\n",
        "from collections import Counter\n",
        "from sklearn.metrics import pairwise_distances\n",
        "from sklearn import metrics\n",
        "from joblib import Parallel, delayed, parallel_config\n",
        "import numpy as np\n",
        "from tqdm import tqdm\n",
        "from PIL import Image\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Creating I/O dirs...')\n",
        "\n",
        "if not os.path.exists('/content/Dataset'):\n",
        "    os.makedirs('/content/Dataset')\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Loading tegridy-tools modules...')\n",
        "print('=' * 70)\n",
        "\n",
        "%cd /content/tegridy-tools/tegridy-tools\n",
        "\n",
        "import TMIDIX\n",
        "import TMELODIES\n",
        "import TPLOTS\n",
        "import HaystackSearch\n",
        "\n",
        "%cd /content/\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "OblKfMMT8rfM",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (DOWNLOAD SAMPLE MIDI DATASET)"
      ],
      "metadata": {
        "id": "gUXM7WsN_ioe"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Download sample MIDI dataset (POP909)\n",
        "%cd /content/Dataset/\n",
        "!git clone --depth 1 https://github.com/music-x-lab/POP909-Dataset\n",
        "%cd /content/"
      ],
      "metadata": {
        "id": "JLm4OmOUYlEK",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Save file list\n",
        "###########\n",
        "\n",
        "print('=' * 70)\n",
        "print('Loading MIDI files...')\n",
        "print('This may take a while on a large dataset in particular...')\n",
        "\n",
        "dataset_addr = '/content/Dataset/'\n",
        "\n",
        "# os.chdir(dataset_addr)\n",
        "filez = list()\n",
        "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n",
        "    filez += [os.path.join(dirpath, file) for file in filenames if file.endswith('.mid') or file.endswith('.midi') or file.endswith('.kar')]\n",
        "print('=' * 70)\n",
        "\n",
        "if filez == []:\n",
        "    print('Could not find any MIDI files. Please check Dataset dir...')\n",
        "    print('=' * 70)\n",
        "\n",
        "print('Randomizing file list...')\n",
        "random.shuffle(filez)\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Total found MIDI files:', len(filez))\n",
        "print('=' * 70)\n",
        "\n",
        "TMIDIX.Tegridy_Any_Pickle_File_Writer(filez, 'filez')\n",
        "\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "AJrFrZ9grhMM"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (LOAD TMIDIX MIDI PROCESSOR)"
      ],
      "metadata": {
        "id": "RJeTdierAbeF"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Load TMIDIX MIDI processor\n",
        "\n",
        "print('=' * 70)\n",
        "print('TMIDIX MIDI Processor')\n",
        "print('=' * 70)\n",
        "print('Loading...')\n",
        "\n",
        "###########\n",
        "\n",
        "def TMIDIX_MIDI_Processor(midi_file):\n",
        "\n",
        "    fn = os.path.basename(midi_file)\n",
        "    fn1 = fn.split('.mid')[0]\n",
        "\n",
        "    try:\n",
        "\n",
        "        #=======================================================\n",
        "        # START PROCESSING\n",
        "\n",
        "        raw_score = TMIDIX.midi2single_track_ms_score(midi_file)\n",
        "\n",
        "        escore_notes = TMIDIX.advanced_score_processor(raw_score, return_enhanced_score_notes=True)[0]\n",
        "\n",
        "        escore_notes = TMIDIX.augment_enhanced_score_notes(escore_notes, timings_divider=256)\n",
        "\n",
        "        sp_escore_notes = TMIDIX.recalculate_score_timings(TMIDIX.solo_piano_escore_notes(escore_notes, keep_drums=False))\n",
        "\n",
        "        if sp_escore_notes:\n",
        "\n",
        "            bmatrix = TMIDIX.escore_notes_to_binary_matrix(sp_escore_notes)\n",
        "\n",
        "            return [fn1, bmatrix]\n",
        "\n",
        "        else:\n",
        "            return [fn1, []]\n",
        "\n",
        "        #=======================================================\n",
        "\n",
        "    except Exception as ex:\n",
        "        print('WARNING !!!')\n",
        "        print('=' * 70)\n",
        "        print('Bad MIDI:', midi_file)\n",
        "        print('Error detected:', ex)\n",
        "        print('=' * 70)\n",
        "        return None\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "fBbIiUWSZA5y"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (PROCESS MIDIs)"
      ],
      "metadata": {
        "id": "R3QxQN6OA_jX"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Process MIDIs with TMIDIX MIDI processor\n",
        "output_folder = \"/content/MIDI-Images/\" # @param {\"type\":\"string\"}\n",
        "\n",
        "NUMBER_OF_PARALLEL_JOBS = 4 # Number of parallel jobs\n",
        "NUMBER_OF_FILES_PER_ITERATION = 4 # Number of files to queue for each parallel iteration\n",
        "SAVE_EVERY_NUMBER_OF_ITERATIONS = 128 # Save every 2560 files\n",
        "\n",
        "print('=' * 70)\n",
        "print('TMIDIX MIDI Processor')\n",
        "print('=' * 70)\n",
        "print('Starting up...')\n",
        "print('=' * 70)\n",
        "\n",
        "###########\n",
        "\n",
        "melody_chords_f = []\n",
        "\n",
        "files_count = 0\n",
        "\n",
        "print('Processing MIDI files...')\n",
        "print('Please wait...')\n",
        "print('=' * 70)\n",
        "\n",
        "for i in tqdm(range(0, len(filez), NUMBER_OF_FILES_PER_ITERATION)):\n",
        "\n",
        "  with parallel_config(backend='threading', n_jobs=NUMBER_OF_PARALLEL_JOBS, verbose = 0):\n",
        "\n",
        "    output = Parallel(n_jobs=NUMBER_OF_PARALLEL_JOBS, verbose=0)(delayed(TMIDIX_MIDI_Processor)(f) for f in filez[i:i+NUMBER_OF_FILES_PER_ITERATION])\n",
        "\n",
        "    for o in output:\n",
        "\n",
        "        if o is not None:\n",
        "            melody_chords_f.append(o)\n",
        "\n",
        "    if i % (NUMBER_OF_FILES_PER_ITERATION * SAVE_EVERY_NUMBER_OF_ITERATIONS) == 0 and i != 0:\n",
        "\n",
        "        print('SAVING !!!')\n",
        "        print('=' * 70)\n",
        "        print('Saving processed files...')\n",
        "        files_count += len(melody_chords_f)\n",
        "        print('=' * 70)\n",
        "        print('Processed so far:', files_count, 'out of', len(filez), '===', files_count / len(filez), 'good files ratio')\n",
        "        print('=' * 70)\n",
        "        print('Writing images...')\n",
        "        print('Please wait...')\n",
        "\n",
        "        for mat in melody_chords_f:\n",
        "\n",
        "          if mat[1]:\n",
        "\n",
        "            TPLOTS.binary_matrix_to_images(mat[1],\n",
        "                                            128,\n",
        "                                            32,\n",
        "                                            output_folder=output_folder+str(mat[0])+'/',\n",
        "                                            output_img_prefix=str(mat[0]),\n",
        "                                            output_img_ext='.png',\n",
        "                                            verbose=False\n",
        "                                            )\n",
        "\n",
        "        print('Done!')\n",
        "        print('=' * 70)\n",
        "        melody_chords_f = []\n",
        "\n",
        "print('SAVING !!!')\n",
        "print('=' * 70)\n",
        "print('Saving processed files...')\n",
        "files_count += len(melody_chords_f)\n",
        "print('=' * 70)\n",
        "print('Processed so far:', files_count, 'out of', len(filez), '===', files_count / len(filez), 'good files ratio')\n",
        "print('=' * 70)\n",
        "print('Writing images...')\n",
        "print('Please wait...')\n",
        "\n",
        "for mat in melody_chords_f:\n",
        "\n",
        "  if mat[1]:\n",
        "\n",
        "    TPLOTS.binary_matrix_to_images(mat[1],\n",
        "                                    128,\n",
        "                                    32,\n",
        "                                    output_folder=output_folder+str(mat[0])+'/',\n",
        "                                    output_img_prefix=str(mat[0]),\n",
        "                                    output_img_ext='.png',\n",
        "                                    verbose=False\n",
        "                                    )\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "15y4uzSOZX52"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (LOAD IMAGES)"
      ],
      "metadata": {
        "id": "GtejvUFAFocZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Load created MIDI images\n",
        "full_path_to_metadata_pickle_files = \"/content/MIDI-Images\" #@param {type:\"string\"}\n",
        "\n",
        "print('=' * 70)\n",
        "print('MIDI Images Reader')\n",
        "print('=' * 70)\n",
        "print('Searching for images...')\n",
        "\n",
        "filez = list()\n",
        "for (dirpath, dirnames, filenames) in os.walk(full_path_to_metadata_pickle_files):\n",
        "    filez += [os.path.join(dirpath, file) for file in filenames if file.endswith('.png')]\n",
        "print('=' * 70)\n",
        "\n",
        "filez.sort()\n",
        "\n",
        "print('Found', len(filez), 'images!')\n",
        "print('=' * 70)\n",
        "print('Reading images...')\n",
        "print('Please wait...')\n",
        "print('=' * 70)\n",
        "\n",
        "fidx = 0\n",
        "\n",
        "all_read_images = []\n",
        "\n",
        "for img in tqdm(filez):\n",
        "\n",
        "    img = Image.open(img)\n",
        "\n",
        "    img_arr = np.array(img).tolist()\n",
        "\n",
        "    all_read_images.append(img_arr)\n",
        "\n",
        "    fidx += 1\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Loaded', fidx, 'images!')\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "cXpLWHG1dBB3"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (TEST IMAGES)"
      ],
      "metadata": {
        "id": "qbClHSmhB1NF"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Test created MIDI images\n",
        "\n",
        "print('=' * 70)\n",
        "\n",
        "image = random.choice(all_read_images)\n",
        "\n",
        "escore = TMIDIX.binary_matrix_to_original_escore_notes(image)\n",
        "\n",
        "output_score, patches, overflow_patches = TMIDIX.patch_enhanced_score_notes(escore)\n",
        "\n",
        "detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score,\n",
        "                                                          output_signature = 'MIDI Images',\n",
        "                                                          output_file_name = '/content/MIDI-Images-Composition',\n",
        "                                                          track_name='Project Los Angeles',\n",
        "                                                          list_of_MIDI_patches=patches,\n",
        "                                                          timings_multiplier=256\n",
        "                                                          )\n",
        "\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "nrPDM1VQdKES",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (ZIP IMAGES)"
      ],
      "metadata": {
        "id": "sIq55gvPCgJh"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Zip created MIDI images\n",
        "!zip -9 -r POP909_MIDI_Images_128_128_32_BW.zip MIDI-Images/ > /dev/null"
      ],
      "metadata": {
        "id": "tVe0REKSqJeV",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Congrats! You did it! :)"
      ],
      "metadata": {
        "id": "iDdMYg4haGFn"
      }
    }
  ]
}