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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "gradient": {
          "editing": false,
          "id": "ac5a4cf0-d9d2-47b5-9633-b53f8d99a4d2",
          "kernelId": ""
        },
        "id": "SiTIpPjArIyr"
      },
      "source": [
        "# Los Angeles MIDI Dataset Maker (ver. 3.1)\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 2023\n",
        "\n",
        "***"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "gradient": {
          "editing": false,
          "id": "fa0a611c-1803-42ae-bdf6-a49b5a4e781b",
          "kernelId": ""
        },
        "id": "gOd93yV0sGd2"
      },
      "source": [
        "# (SETUP ENVIRONMENT)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "gradient": {
          "editing": false,
          "id": "a1a45a91-d909-4fd4-b67a-5e16b971d179",
          "kernelId": ""
        },
        "id": "fX12Yquyuihc"
      },
      "outputs": [],
      "source": [
        "#@title Install all dependencies (run only once per session)\n",
        "\n",
        "!git clone https://github.com/asigalov61/tegridy-tools\n",
        "!pip install tqdm"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "gradient": {
          "editing": false,
          "id": "b8207b76-9514-4c07-95db-95a4742e52c5",
          "kernelId": ""
        },
        "id": "z7n9vnKmug1J"
      },
      "outputs": [],
      "source": [
        "#@title Import all needed modules\n",
        "\n",
        "print('Loading core modules... Please wait...')\n",
        "import os\n",
        "\n",
        "import math\n",
        "import statistics\n",
        "import random\n",
        "from collections import Counter\n",
        "import shutil\n",
        "import hashlib\n",
        "from tqdm import tqdm\n",
        "\n",
        "print('Creating IO dirs...')\n",
        "\n",
        "if not os.path.exists('/content/Dataset'):\n",
        "    os.makedirs('/content/Dataset')\n",
        "\n",
        "if not os.path.exists('/content/Output'):\n",
        "    os.makedirs('/content/Output')\n",
        "\n",
        "output_dirs_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']\n",
        "\n",
        "for o in output_dirs_list:\n",
        "  if not os.path.exists('/content/Output/'+str(o)+'/'):\n",
        "    os.makedirs('/content/Output/'+str(o)+'/')\n",
        "\n",
        "print('Loading TMIDIX module...')\n",
        "os.chdir('/content/tegridy-tools/tegridy-tools')\n",
        "\n",
        "import TMIDIX\n",
        "\n",
        "print('Done!')\n",
        "\n",
        "os.chdir('/content/')\n",
        "print('Enjoy! :)')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "gradient": {
          "editing": false,
          "id": "20b8698a-0b4e-4fdb-ae49-24d063782e77",
          "kernelId": ""
        },
        "id": "ObPxlEutsQBj"
      },
      "source": [
        "# (DOWNLOAD SOURCE MIDI DATASET)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Download original LAKH MIDI Dataset\n",
        "\n",
        "%cd /content/Dataset/\n",
        "\n",
        "!wget 'http://hog.ee.columbia.edu/craffel/lmd/lmd_full.tar.gz'\n",
        "!tar -xvf 'lmd_full.tar.gz'\n",
        "!rm 'lmd_full.tar.gz'\n",
        "\n",
        "%cd /content/"
      ],
      "metadata": {
        "cellView": "form",
        "id": "7aItlhq9cRxZ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JwrqQeie08t0"
      },
      "source": [
        "# (FILE LIST)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "DuVWtdDNcqKh"
      },
      "outputs": [],
      "source": [
        "#@title Save file list\n",
        "###########\n",
        "\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",
        "# 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]\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",
        "\n",
        "TMIDIX.Tegridy_Any_Pickle_File_Writer(filez, '/content/filez')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "qI_adhjojrJ9"
      },
      "outputs": [],
      "source": [
        "#@title Load file list\n",
        "filez = TMIDIX.Tegridy_Any_Pickle_File_Reader('/content/filez')\n",
        "print('Done!')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FLxHvO-wlwfU"
      },
      "source": [
        "# (PROCESS)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Process MIDIs with TMIDIX MIDI processor\n",
        "\n",
        "print('=' * 70)\n",
        "print('TMIDIX MIDI Processor')\n",
        "print('=' * 70)\n",
        "print('Starting up...')\n",
        "print('=' * 70)\n",
        "\n",
        "###########\n",
        "\n",
        "START_FILE_NUMBER = 0\n",
        "LAST_SAVED_BATCH_COUNT = 0\n",
        "\n",
        "input_files_count = START_FILE_NUMBER\n",
        "files_count = LAST_SAVED_BATCH_COUNT\n",
        "\n",
        "melody_chords_f = []\n",
        "\n",
        "all_md5_names = []\n",
        "all_pitches_sums = []\n",
        "all_pitches_counts = []\n",
        "all_pitches_and_counts = []\n",
        "\n",
        "print('Processing MIDI files. Please wait...')\n",
        "print('=' * 70)\n",
        "\n",
        "for f in tqdm(filez[START_FILE_NUMBER:]):\n",
        "    try:\n",
        "        input_files_count += 1\n",
        "\n",
        "        fn = os.path.basename(f)\n",
        "\n",
        "        # Filtering out giant MIDIs\n",
        "        file_size = os.path.getsize(f)\n",
        "\n",
        "        if file_size <= 1000000:\n",
        "\n",
        "            fdata = open(f, 'rb').read()\n",
        "\n",
        "            md5sum = hashlib.md5(fdata).hexdigest()\n",
        "\n",
        "            md5name = str(md5sum) + '.mid'\n",
        "\n",
        "            #=======================================================\n",
        "            # START PROCESSING\n",
        "\n",
        "            # Convering MIDI to ms score with MIDI.py module\n",
        "            score = TMIDIX.midi2score(fdata)\n",
        "\n",
        "            events_matrix = []\n",
        "            itrack = 1\n",
        "\n",
        "            while itrack < len(score):\n",
        "              for event in score[itrack]:\n",
        "                events_matrix.append(event)\n",
        "              itrack += 1\n",
        "\n",
        "            events_matrix.sort(key=lambda x: x[1])\n",
        "\n",
        "            notes = [y for y in events_matrix if y[0] == 'note']\n",
        "\n",
        "            if len(notes) >= 256:\n",
        "\n",
        "                times = [n[1] for n in notes]\n",
        "                durs = [n[2] for n in notes]\n",
        "\n",
        "                if min(times) >= 0 and min(durs) >= 0:\n",
        "                    if len(times) > len(set(times)):\n",
        "\n",
        "                        if str(md5sum) not in all_md5_names:\n",
        "\n",
        "                            all_md5_names.append(str(md5sum))\n",
        "\n",
        "                            pitches = [n[4] for n in notes]\n",
        "                            pitches_sum = sum(pitches)\n",
        "\n",
        "                            if pitches_sum not in all_pitches_sums:\n",
        "\n",
        "                                all_pitches_sums.append(pitches_sum)\n",
        "\n",
        "                                pitches_and_counts = sorted([[key, val] for key,val in Counter(pitches).most_common()], reverse=True, key = lambda x: x[1])\n",
        "                                pitches_counts = [p[1] for p in pitches_and_counts]\n",
        "\n",
        "                                #=======================================================\n",
        "\n",
        "                                if pitches_counts not in all_pitches_counts:\n",
        "\n",
        "                                    # Saving data every 50000 processed files\n",
        "                                    if files_count % 50000 == 0:\n",
        "                                      print('SAVING !!!')\n",
        "                                      print('=' * 70)\n",
        "                                      print('Saving processed data...')\n",
        "                                      print('=' * 70)\n",
        "                                      TMIDIX.Tegridy_Any_Pickle_File_Writer([filez, all_md5_names, all_pitches_sums, all_pitches_and_counts], '/content/Output/all_files_data')\n",
        "                                      print('=' * 70)\n",
        "                                      print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')\n",
        "                                      print('=' * 70)\n",
        "\n",
        "\n",
        "                                    shutil.copy2(f, '/content/Output/'+str(md5name[0])+'/'+md5name)\n",
        "\n",
        "                                    all_pitches_counts.append(pitches_counts)\n",
        "                                    all_pitches_and_counts.append(pitches_and_counts)\n",
        "\n",
        "                                    if files_count % 1000 == 0:\n",
        "                                      print('=' * 70)\n",
        "                                      print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')\n",
        "                                      print('=' * 70)\n",
        "\n",
        "                                    # Processed files counter\n",
        "                                    files_count += 1\n",
        "\n",
        "                                #=======================================================\n",
        "\n",
        "    except KeyboardInterrupt:\n",
        "        print('Saving current progress and quitting...')\n",
        "        break\n",
        "\n",
        "    except Exception as ex:\n",
        "        print('WARNING !!!')\n",
        "        print('=' * 70)\n",
        "        print('Bad MIDI:', f)\n",
        "        print('Error detected:', ex)\n",
        "        print('=' * 70)\n",
        "        continue\n",
        "\n",
        "# Saving last processed data...\n",
        "print('=' * 70)\n",
        "print('Saving processed data...')\n",
        "print('=' * 70)\n",
        "TMIDIX.Tegridy_Any_Pickle_File_Writer([filez, all_md5_names, all_pitches_sums, all_pitches_and_counts], '/content/Output/all_files_data')\n",
        "print('=' * 70)\n",
        "print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "\n",
        "print('Resulting Stats:')\n",
        "print('=' * 70)\n",
        "print('Total good processed MIDI files:', files_count)\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "OtmMHNozWPSV"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YzCMd94Tu_gz"
      },
      "source": [
        "# Congrats! You did it! :)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "machine_shape": "hm",
      "private_outputs": true,
      "provenance": []
    },
    "gpuClass": "standard",
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}