projectlosangeles commited on
Commit
3bd77c9
1 Parent(s): e0bb6ec

Upload 5 files

Browse files
Los_Angeles_MIDI_Dataset_Metadata_Maker.ipynb ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Metadata Maker (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 tqdm"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "execution_count": null,
66
+ "metadata": {
67
+ "cellView": "form",
68
+ "gradient": {
69
+ "editing": false,
70
+ "id": "b8207b76-9514-4c07-95db-95a4742e52c5",
71
+ "kernelId": ""
72
+ },
73
+ "id": "z7n9vnKmug1J"
74
+ },
75
+ "outputs": [],
76
+ "source": [
77
+ "#@title Import all needed modules\n",
78
+ "\n",
79
+ "print('Loading needed modules. Please wait...')\n",
80
+ "import os\n",
81
+ "\n",
82
+ "import math\n",
83
+ "import statistics\n",
84
+ "import random\n",
85
+ "from collections import Counter\n",
86
+ "\n",
87
+ "from tqdm import tqdm\n",
88
+ "\n",
89
+ "if not os.path.exists('/content/Dataset'):\n",
90
+ " os.makedirs('/content/Dataset')\n",
91
+ "\n",
92
+ "print('Loading TMIDIX module...')\n",
93
+ "os.chdir('/content/tegridy-tools/tegridy-tools')\n",
94
+ "\n",
95
+ "import TMIDIX\n",
96
+ "\n",
97
+ "print('Done!')\n",
98
+ "\n",
99
+ "os.chdir('/content/')\n",
100
+ "print('Enjoy! :)')"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "markdown",
105
+ "metadata": {
106
+ "gradient": {
107
+ "editing": false,
108
+ "id": "20b8698a-0b4e-4fdb-ae49-24d063782e77",
109
+ "kernelId": ""
110
+ },
111
+ "id": "ObPxlEutsQBj"
112
+ },
113
+ "source": [
114
+ "# (DOWNLOAD SOURCE MIDI DATASET)"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "source": [
120
+ "#@title Download original LAKH MIDI Dataset\n",
121
+ "\n",
122
+ "%cd /content/Dataset/\n",
123
+ "\n",
124
+ "!wget 'http://hog.ee.columbia.edu/craffel/lmd/lmd_full.tar.gz'\n",
125
+ "!tar -xvf 'lmd_full.tar.gz'\n",
126
+ "!rm 'lmd_full.tar.gz'\n",
127
+ "\n",
128
+ "%cd /content/"
129
+ ],
130
+ "metadata": {
131
+ "cellView": "form",
132
+ "id": "7aItlhq9cRxZ"
133
+ },
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "execution_count": null,
140
+ "metadata": {
141
+ "cellView": "form",
142
+ "id": "S69mWHAcn5Bg"
143
+ },
144
+ "outputs": [],
145
+ "source": [
146
+ "#@title Mount Google Drive\n",
147
+ "from google.colab import drive\n",
148
+ "drive.mount('/content/drive')"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "markdown",
153
+ "metadata": {
154
+ "id": "JwrqQeie08t0"
155
+ },
156
+ "source": [
157
+ "# (FILE LIST)"
158
+ ]
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "execution_count": null,
163
+ "metadata": {
164
+ "cellView": "form",
165
+ "id": "DuVWtdDNcqKh"
166
+ },
167
+ "outputs": [],
168
+ "source": [
169
+ "#@title Save file list\n",
170
+ "###########\n",
171
+ "\n",
172
+ "print('Loading MIDI files...')\n",
173
+ "print('This may take a while on a large dataset in particular.')\n",
174
+ "\n",
175
+ "dataset_addr = \"/content/Dataset\"\n",
176
+ "# os.chdir(dataset_addr)\n",
177
+ "filez = list()\n",
178
+ "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n",
179
+ " filez += [os.path.join(dirpath, file) for file in filenames]\n",
180
+ "print('=' * 70)\n",
181
+ "\n",
182
+ "if filez == []:\n",
183
+ " print('Could not find any MIDI files. Please check Dataset dir...')\n",
184
+ " print('=' * 70)\n",
185
+ "\n",
186
+ "print('Randomizing file list...')\n",
187
+ "random.shuffle(filez)\n",
188
+ "\n",
189
+ "TMIDIX.Tegridy_Any_Pickle_File_Writer(filez, '/content/drive/MyDrive/filez')"
190
+ ]
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "execution_count": null,
195
+ "metadata": {
196
+ "cellView": "form",
197
+ "id": "qI_adhjojrJ9"
198
+ },
199
+ "outputs": [],
200
+ "source": [
201
+ "#@title Load file list\n",
202
+ "filez = TMIDIX.Tegridy_Any_Pickle_File_Reader('/content/drive/MyDrive/filez')\n",
203
+ "print('Done!')"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "markdown",
208
+ "metadata": {
209
+ "id": "FLxHvO-wlwfU"
210
+ },
211
+ "source": [
212
+ "# (PROCESS)"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "execution_count": null,
218
+ "metadata": {
219
+ "id": "CeGo7CruaCJQ",
220
+ "cellView": "form"
221
+ },
222
+ "outputs": [],
223
+ "source": [
224
+ "#@title Process MIDIs with TMIDIX MIDI processor\n",
225
+ "\n",
226
+ "print('=' * 70)\n",
227
+ "print('TMIDIX MIDI Processor')\n",
228
+ "print('=' * 70)\n",
229
+ "print('Starting up...')\n",
230
+ "print('=' * 70)\n",
231
+ "\n",
232
+ "###########\n",
233
+ "\n",
234
+ "START_FILE_NUMBER = 0\n",
235
+ "LAST_SAVED_BATCH_COUNT = 0\n",
236
+ "\n",
237
+ "input_files_count = START_FILE_NUMBER\n",
238
+ "files_count = LAST_SAVED_BATCH_COUNT\n",
239
+ "\n",
240
+ "melody_chords_f = []\n",
241
+ "\n",
242
+ "stats = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n",
243
+ "\n",
244
+ "print('Processing MIDI files. Please wait...')\n",
245
+ "print('=' * 70)\n",
246
+ "\n",
247
+ "for f in tqdm(filez[START_FILE_NUMBER:]):\n",
248
+ " try:\n",
249
+ " input_files_count += 1\n",
250
+ "\n",
251
+ " fn = os.path.basename(f)\n",
252
+ " fn1 = fn.split('.mid')[0]\n",
253
+ "\n",
254
+ " #=======================================================\n",
255
+ " # START PROCESSING\n",
256
+ " \n",
257
+ " opus = TMIDIX.midi2opus(open(f, 'rb').read())\n",
258
+ " \n",
259
+ " opus_events_matrix = []\n",
260
+ " \n",
261
+ " itrack0 = 1\n",
262
+ " \n",
263
+ " while itrack0 < len(opus):\n",
264
+ " for event in opus[itrack0]: \n",
265
+ " opus_events_matrix.append(event)\n",
266
+ " itrack0 += 1\n",
267
+ " \n",
268
+ " #=======================================================\n",
269
+ " \n",
270
+ " ms_score = TMIDIX.opus2score(TMIDIX.to_millisecs(opus))\n",
271
+ "\n",
272
+ " ms_events_matrix = []\n",
273
+ " \n",
274
+ " itrack1 = 1\n",
275
+ " \n",
276
+ " while itrack1 < len(ms_score):\n",
277
+ " for event in ms_score[itrack1]: \n",
278
+ " if event[0] == 'note':\n",
279
+ " ms_events_matrix.append(event)\n",
280
+ " itrack1 += 1\n",
281
+ "\n",
282
+ " ms_events_matrix.sort(key=lambda x: x[1])\n",
283
+ " \n",
284
+ " #=======================================================\n",
285
+ "\n",
286
+ " # Convering MIDI to score with MIDI.py module\n",
287
+ " score = TMIDIX.opus2score(opus)\n",
288
+ "\n",
289
+ " events_matrix = []\n",
290
+ " full_events_matrix = []\n",
291
+ " \n",
292
+ " itrack = 1\n",
293
+ " patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n",
294
+ "\n",
295
+ " while itrack < len(score):\n",
296
+ " for event in score[itrack]: \n",
297
+ " if event[0] == 'note' or event[0] == 'patch_change':\n",
298
+ " events_matrix.append(event)\n",
299
+ " full_events_matrix.append(event)\n",
300
+ " itrack += 1\n",
301
+ " \n",
302
+ " full_events_matrix.sort(key=lambda x: x[1])\n",
303
+ " events_matrix.sort(key=lambda x: x[1])\n",
304
+ " \n",
305
+ " events_matrix1 = []\n",
306
+ "\n",
307
+ " for event in events_matrix:\n",
308
+ " if event[0] == 'patch_change':\n",
309
+ " patches[event[2]] = event[3]\n",
310
+ "\n",
311
+ " if event[0] == 'note':\n",
312
+ " event.extend([patches[event[3]]])\n",
313
+ " events_matrix1.append(event)\n",
314
+ "\n",
315
+ " if len(events_matrix1) > 0: \n",
316
+ " \n",
317
+ " events_matrix1.sort(key=lambda x: x[1])\n",
318
+ "\n",
319
+ " for e in events_matrix1:\n",
320
+ " if e[0] == 'note':\n",
321
+ " if e[3] == 9:\n",
322
+ " e[4] = ((abs(e[4]) % 128) + 128)\n",
323
+ " else:\n",
324
+ " e[4] = (abs(e[4]) % 128)\n",
325
+ "\n",
326
+ " pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix1]).most_common()]\n",
327
+ " pitches_counts.sort(key=lambda x: x[0], reverse=True)\n",
328
+ "\n",
329
+ " patches_counts = [[y[0],y[1]] for y in Counter([y[6] for y in events_matrix1]).most_common()]\n",
330
+ " patches_counts.sort(key=lambda x: x[1], reverse=True)\n",
331
+ " \n",
332
+ " pitches_patches = sorted([[y[4], y[6]] for y in events_matrix1], reverse=True)\n",
333
+ " pitches_patches_counts = [[[y[0][0], y[0][1]], y[1]] for y in Counter([tuple(x) for x in pitches_patches]).most_common()]\n",
334
+ " \n",
335
+ " midi_patches = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))\n",
336
+ " if len(midi_patches) == 0:\n",
337
+ " midi_patches = [None]\n",
338
+ " \n",
339
+ " times = []\n",
340
+ " pt = ms_events_matrix[0][1]\n",
341
+ " start = True\n",
342
+ " for e in ms_events_matrix:\n",
343
+ " if (e[1]-pt) != 0 or start == True:\n",
344
+ " times.append((e[1]-pt))\n",
345
+ " start = False\n",
346
+ " pt = e[1]\n",
347
+ " \n",
348
+ " times_sum = sum(times)\n",
349
+ " \n",
350
+ " durs = [e[2] for e in ms_events_matrix]\n",
351
+ " vels = [e[5] for e in ms_events_matrix]\n",
352
+ " \n",
353
+ " avg_time = int(sum(times) / len(times))\n",
354
+ " avg_dur = int(sum(durs) / len(durs))\n",
355
+ " avg_vel = int(sum(vels) / len(vels))\n",
356
+ " \n",
357
+ " mode_time = statistics.mode(times)\n",
358
+ " mode_dur = statistics.mode(durs)\n",
359
+ " mode_vel = statistics.mode(vels)\n",
360
+ " \n",
361
+ " median_time = int(statistics.median(times))\n",
362
+ " median_dur = int(statistics.median(durs))\n",
363
+ " median_vel = int(statistics.median(vels))\n",
364
+ " \n",
365
+ " text_events_list = ['text_event', \n",
366
+ " 'text_event_08', \n",
367
+ " 'text_event_09', \n",
368
+ " 'text_event_0a', \n",
369
+ " 'text_event_0b', \n",
370
+ " 'text_event_0c',\n",
371
+ " 'text_event_0d',\n",
372
+ " 'text_event_0e',\n",
373
+ " 'text_event_0f']\n",
374
+ " \n",
375
+ " text_events_count = len([e for e in full_events_matrix if e[0] in text_events_list])\n",
376
+ " lyric_events_count = len([e for e in full_events_matrix if e[0] == 'lyric'])\n",
377
+ " \n",
378
+ " chords = []\n",
379
+ " pe = ms_events_matrix[0]\n",
380
+ " cho = []\n",
381
+ " for e in ms_events_matrix:\n",
382
+ " if (e[1] - pe[1]) == 0:\n",
383
+ " if e[3] != 9:\n",
384
+ " if (e[4] % 12) not in cho:\n",
385
+ " cho.append(e[4] % 12)\n",
386
+ " else:\n",
387
+ " if len(cho) > 0:\n",
388
+ " chords.append(sorted(cho))\n",
389
+ " cho = []\n",
390
+ " if e[3] != 9:\n",
391
+ " if (e[4] % 12) not in cho:\n",
392
+ " cho.append(e[4] % 12)\n",
393
+ "\n",
394
+ " pe = e\n",
395
+ " \n",
396
+ " if len(cho) > 0:\n",
397
+ " chords.append(sorted(cho))\n",
398
+ "\n",
399
+ " 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",
400
+ " \n",
401
+ " tempo_change_count = len([f for f in full_events_matrix if f[0] == 'set_tempo'])\n",
402
+ " \n",
403
+ " sixty_forth_note = [e for e in events_matrix1][64]\n",
404
+ " sixty_forth_note_idx = full_events_matrix.index(sixty_forth_note)\n",
405
+ "\n",
406
+ " data = []\n",
407
+ " data.append(['total_number_of_tracks', itrack])\n",
408
+ " data.append(['total_number_of_opus_midi_events', len(opus_events_matrix)])\n",
409
+ " data.append(['total_number_of_score_midi_events', len(full_events_matrix)])\n",
410
+ " data.append(['average_median_mode_time_ms', [avg_time, median_time, mode_time]])\n",
411
+ " data.append(['average_median_mode_dur_ms', [avg_dur, median_dur, mode_dur]])\n",
412
+ " data.append(['average_median_mode_vel', [avg_vel, median_vel, mode_vel]])\n",
413
+ " data.append(['total_number_of_chords', len(set([y[1] for y in events_matrix1]))])\n",
414
+ " data.append(['total_number_of_chords_ms', len(times)])\n",
415
+ " data.append(['ms_chords_counts', ms_chords_counts])\n",
416
+ " data.append(['pitches_times_sum_ms', times_sum])\n",
417
+ " data.append(['total_pitches_counts', pitches_counts])\n",
418
+ " data.append(['total_patches_counts', patches_counts])\n",
419
+ " data.append(['midi_patches', midi_patches])\n",
420
+ " data.append(['total_pitches_patches_counts', pitches_patches_counts])\n",
421
+ " data.append(['tempo_change_count', tempo_change_count])\n",
422
+ " data.append(['text_events_count', text_events_count])\n",
423
+ " data.append(['lyric_events_count', lyric_events_count])\n",
424
+ " data.append(['midi_ticks', score[0]])\n",
425
+ " data.extend(full_events_matrix[:sixty_forth_note_idx])\n",
426
+ " data.append(full_events_matrix[-1])\n",
427
+ " \n",
428
+ " melody_chords_f.append([fn1, data])\n",
429
+ "\n",
430
+ " #=======================================================\n",
431
+ "\n",
432
+ " # Processed files counter\n",
433
+ " files_count += 1\n",
434
+ "\n",
435
+ " # Saving every 5000 processed files\n",
436
+ " if files_count % 10000 == 0:\n",
437
+ " print('SAVING !!!')\n",
438
+ " print('=' * 70)\n",
439
+ " print('Saving processed files...')\n",
440
+ " print('=' * 70)\n",
441
+ " print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')\n",
442
+ " print('=' * 70)\n",
443
+ " count = str(files_count)\n",
444
+ " TMIDIX.Tegridy_Any_Pickle_File_Writer(melody_chords_f, '/content/drive/MyDrive/LAMD_META_'+count)\n",
445
+ " melody_chords_f = []\n",
446
+ " print('=' * 70)\n",
447
+ "\n",
448
+ " except KeyboardInterrupt:\n",
449
+ " print('Saving current progress and quitting...')\n",
450
+ " break \n",
451
+ "\n",
452
+ " except Exception as ex:\n",
453
+ " print('WARNING !!!')\n",
454
+ " print('=' * 70)\n",
455
+ " print('Bad MIDI:', f)\n",
456
+ " print('Error detected:', ex)\n",
457
+ " print('=' * 70)\n",
458
+ " continue\n",
459
+ "\n",
460
+ "# Saving last processed files...\n",
461
+ "print('=' * 70)\n",
462
+ "print('Saving processed files...')\n",
463
+ "print('=' * 70)\n",
464
+ "print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')\n",
465
+ "print('=' * 70)\n",
466
+ "count = str(files_count)\n",
467
+ "TMIDIX.Tegridy_Any_Pickle_File_Writer(melody_chords_f, '/content/drive/MyDrive/LAMD_META_'+count)\n",
468
+ "\n",
469
+ "# Displaying resulting processing stats...\n",
470
+ "print('=' * 70)\n",
471
+ "print('Done!') \n",
472
+ "print('=' * 70)\n",
473
+ "\n",
474
+ "print('Resulting Stats:')\n",
475
+ "print('=' * 70)\n",
476
+ "print('Total good processed MIDI files:', files_count)\n",
477
+ "print('=' * 70)"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "markdown",
482
+ "metadata": {
483
+ "id": "YzCMd94Tu_gz"
484
+ },
485
+ "source": [
486
+ "# Congrats! You did it! :)"
487
+ ]
488
+ }
489
+ ],
490
+ "metadata": {
491
+ "colab": {
492
+ "machine_shape": "hm",
493
+ "private_outputs": true,
494
+ "provenance": []
495
+ },
496
+ "gpuClass": "standard",
497
+ "kernelspec": {
498
+ "display_name": "Python 3 (ipykernel)",
499
+ "language": "python",
500
+ "name": "python3"
501
+ },
502
+ "language_info": {
503
+ "codemirror_mode": {
504
+ "name": "ipython",
505
+ "version": 3
506
+ },
507
+ "file_extension": ".py",
508
+ "mimetype": "text/x-python",
509
+ "name": "python",
510
+ "nbconvert_exporter": "python",
511
+ "pygments_lexer": "ipython3",
512
+ "version": "3.9.7"
513
+ }
514
+ },
515
+ "nbformat": 4,
516
+ "nbformat_minor": 0
517
+ }
Los_Angeles_MIDI_Dataset_Search_and_Explore.ipynb CHANGED
@@ -88,6 +88,7 @@
88
  "import pickle\n",
89
  "from tqdm import tqdm\n",
90
  "import pprint\n",
 
91
  "\n",
92
  "from joblib import Parallel, delayed\n",
93
  "import multiprocessing\n",
@@ -707,6 +708,27 @@
707
  "\n",
708
  "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",
709
  "\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
710
  "#==================================================\n",
711
  "\n",
712
  "print('=' * 70)\n",
@@ -1071,10 +1093,24 @@
1071
  "\n",
1072
  "#@markdown NOTE: You can stop the search at any time to render partial results\n",
1073
  "\n",
 
 
1074
  "maximum_match_ratio_to_search_for = 1 #@param {type:\"slider\", min:0, max:1, step:0.01}\n",
 
 
 
1075
  "pitches_counts_cutoff_threshold_ratio = 0 #@param {type:\"slider\", min:0, max:1, step:0.05}\n",
1076
  "search_transposed_pitches = False #@param {type:\"boolean\"}\n",
1077
  "skip_exact_matches = False #@param {type:\"boolean\"}\n",
 
 
 
 
 
 
 
 
 
1078
  "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
1079
  "download_MIDI = False #@param {type:\"boolean\"}\n",
1080
  "\n",
@@ -1082,7 +1118,7 @@
1082
  "print('MIDI Pitches Search')\n",
1083
  "print('=' * 70)\n",
1084
  "\n",
1085
- "ratios = []\n",
1086
  "\n",
1087
  "for d in tqdm(meta_data):\n",
1088
  "\n",
@@ -1090,34 +1126,145 @@
1090
  " p_counts = d[1][10][1]\n",
1091
  " p_counts.sort(reverse = True, key = lambda x: x[1])\n",
1092
  " max_p_count = p_counts[0][1]\n",
1093
- " trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)] \n",
 
1094
  " \n",
1095
  " if search_transposed_pitches:\n",
1096
  " search_pitches = mult_pitches_counts\n",
1097
  " else:\n",
1098
  " search_pitches = [mult_pitches_counts[6]]\n",
1099
- " \n",
1100
- " rat = []\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1101
  "\n",
1102
  " for m in search_pitches:\n",
1103
  "\n",
 
 
1104
  " m.sort(reverse = True, key = lambda x: x[1])\n",
1105
  " max_pitches_count = m[0][1]\n",
1106
- " trimmed_pitches_counts = [y for y in m if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)] \n",
 
1107
  "\n",
1108
- " num_same_pitches = len(set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts]))\n",
 
1109
  " 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",
1110
  "\n",
1111
  " if skip_exact_matches:\n",
1112
  " if same_pitches_ratio == 1:\n",
1113
  " same_pitches_ratio = 0\n",
1114
  "\n",
1115
- " if same_pitches_ratio > maximum_match_ratio_to_search_for:\n",
1116
- " same_pitches_ratio = 0\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1117
  "\n",
1118
- " rat.append(same_pitches_ratio)\n",
1119
  "\n",
1120
- " ratios.append(max(rat))\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1121
  " \n",
1122
  " except KeyboardInterrupt:\n",
1123
  " break\n",
@@ -1130,8 +1277,8 @@
1130
  " print('=' * 70)\n",
1131
  " break\n",
1132
  "\n",
1133
- "max_ratio = max(ratios)\n",
1134
- "max_ratio_index = ratios.index(max(ratios))\n",
1135
  "\n",
1136
  "print('FOUND')\n",
1137
  "print('=' * 70)\n",
 
88
  "import pickle\n",
89
  "from tqdm import tqdm\n",
90
  "import pprint\n",
91
+ "import statistics\n",
92
  "\n",
93
  "from joblib import Parallel, delayed\n",
94
  "import multiprocessing\n",
 
708
  "\n",
709
  "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",
710
  "\n",
711
+ "times = []\n",
712
+ "pt = ms_events_matrix[0][1]\n",
713
+ "start = True\n",
714
+ "for e in ms_events_matrix:\n",
715
+ " if (e[1]-pt) != 0 or start == True:\n",
716
+ " times.append((e[1]-pt))\n",
717
+ " start = False\n",
718
+ " pt = e[1]\n",
719
+ " \n",
720
+ "durs = [e[2] for e in ms_events_matrix]\n",
721
+ "vels = [e[5] for e in ms_events_matrix]\n",
722
+ "\n",
723
+ "avg_time = int(sum(times) / len(times))\n",
724
+ "avg_dur = int(sum(durs) / len(durs))\n",
725
+ "\n",
726
+ "mode_time = statistics.mode(times)\n",
727
+ "mode_dur = statistics.mode(durs)\n",
728
+ "\n",
729
+ "median_time = int(statistics.median(times))\n",
730
+ "median_dur = int(statistics.median(durs))\n",
731
+ "\n",
732
  "#==================================================\n",
733
  "\n",
734
  "print('=' * 70)\n",
 
1093
  "\n",
1094
  "#@markdown NOTE: You can stop the search at any time to render partial results\n",
1095
  "\n",
1096
+ "#@markdown Match ratio control option\n",
1097
+ "\n",
1098
  "maximum_match_ratio_to_search_for = 1 #@param {type:\"slider\", min:0, max:1, step:0.01}\n",
1099
+ "\n",
1100
+ "#@markdown MIDI pitches search options\n",
1101
+ "\n",
1102
  "pitches_counts_cutoff_threshold_ratio = 0 #@param {type:\"slider\", min:0, max:1, step:0.05}\n",
1103
  "search_transposed_pitches = False #@param {type:\"boolean\"}\n",
1104
  "skip_exact_matches = False #@param {type:\"boolean\"}\n",
1105
+ "\n",
1106
+ "#@markdown Additional search options\n",
1107
+ "\n",
1108
+ "add_pitches_counts_ratios = False #@param {type:\"boolean\"}\n",
1109
+ "add_timings_ratios = False #@param {type:\"boolean\"}\n",
1110
+ "add_durations_ratios = False #@param {type:\"boolean\"}\n",
1111
+ "\n",
1112
+ "#@markdown Other options\n",
1113
+ "\n",
1114
  "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
1115
  "download_MIDI = False #@param {type:\"boolean\"}\n",
1116
  "\n",
 
1118
  "print('MIDI Pitches Search')\n",
1119
  "print('=' * 70)\n",
1120
  "\n",
1121
+ "final_ratios = []\n",
1122
  "\n",
1123
  "for d in tqdm(meta_data):\n",
1124
  "\n",
 
1126
  " p_counts = d[1][10][1]\n",
1127
  " p_counts.sort(reverse = True, key = lambda x: x[1])\n",
1128
  " max_p_count = p_counts[0][1]\n",
1129
+ " trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)]\n",
1130
+ " total_p_counts = sum([y[1] for y in trimmed_p_counts])\n",
1131
  " \n",
1132
  " if search_transposed_pitches:\n",
1133
  " search_pitches = mult_pitches_counts\n",
1134
  " else:\n",
1135
  " search_pitches = [mult_pitches_counts[6]]\n",
1136
+ "\n",
1137
+ " #===================================================\n",
1138
+ "\n",
1139
+ " ratios_list = []\n",
1140
+ "\n",
1141
+ " #===================================================\n",
1142
+ "\n",
1143
+ " atrat = [0]\n",
1144
+ "\n",
1145
+ " if add_timings_ratios:\n",
1146
+ "\n",
1147
+ " source_times = [avg_time, \n",
1148
+ " median_time, \n",
1149
+ " mode_time]\n",
1150
+ "\n",
1151
+ " match_times = meta_data[0][1][3][1]\n",
1152
+ "\n",
1153
+ " times_ratios = []\n",
1154
+ "\n",
1155
+ " for i in range(len(source_times)):\n",
1156
+ " maxtratio = max(source_times[i], match_times[i])\n",
1157
+ " mintratio = min(source_times[i], match_times[i])\n",
1158
+ " times_ratios.append(mintratio / maxtratio)\n",
1159
+ "\n",
1160
+ " avg_times_ratio = sum(times_ratios) / len(times_ratios)\n",
1161
+ "\n",
1162
+ " atrat[0] = avg_times_ratio\n",
1163
+ "\n",
1164
+ " #===================================================\n",
1165
+ "\n",
1166
+ " adrat = [0]\n",
1167
+ "\n",
1168
+ " if add_durations_ratios:\n",
1169
+ "\n",
1170
+ " source_durs = [avg_dur,\n",
1171
+ " median_dur,\n",
1172
+ " mode_dur]\n",
1173
+ "\n",
1174
+ " match_durs = meta_data[0][1][4][1]\n",
1175
+ "\n",
1176
+ " durs_ratios = []\n",
1177
+ "\n",
1178
+ " for i in range(len(source_durs)):\n",
1179
+ " maxtratio = max(source_durs[i], match_durs[i])\n",
1180
+ " mintratio = min(source_durs[i], match_durs[i])\n",
1181
+ " durs_ratios.append(mintratio / maxtratio)\n",
1182
+ "\n",
1183
+ " avg_durs_ratio = sum(durs_ratios) / len(durs_ratios)\n",
1184
+ "\n",
1185
+ " adrat[0] = avg_durs_ratio\n",
1186
+ "\n",
1187
+ " #===================================================\n",
1188
  "\n",
1189
  " for m in search_pitches:\n",
1190
  "\n",
1191
+ " sprat = []\n",
1192
+ "\n",
1193
  " m.sort(reverse = True, key = lambda x: x[1])\n",
1194
  " max_pitches_count = m[0][1]\n",
1195
+ " trimmed_pitches_counts = [y for y in m if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)]\n",
1196
+ " total_pitches_counts = sum([y[1] for y in trimmed_pitches_counts])\n",
1197
  "\n",
1198
+ " same_pitches = set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts])\n",
1199
+ " num_same_pitches = len(same_pitches)\n",
1200
  " 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",
1201
  "\n",
1202
  " if skip_exact_matches:\n",
1203
  " if same_pitches_ratio == 1:\n",
1204
  " same_pitches_ratio = 0\n",
1205
  "\n",
1206
+ " sprat.append(same_pitches_ratio)\n",
1207
+ "\n",
1208
+ " #===================================================\n",
1209
+ "\n",
1210
+ " spcrat = [0]\n",
1211
+ "\n",
1212
+ " if add_pitches_counts_ratios:\n",
1213
+ "\n",
1214
+ " same_trimmed_p_counts = sorted([T for T in trimmed_p_counts if T[0] in same_pitches], reverse = True)\n",
1215
+ " same_trimmed_pitches_counts = sorted([T for T in trimmed_pitches_counts if T[0] in same_pitches], reverse = True)\n",
1216
+ "\n",
1217
+ " same_trimmed_p_counts_ratios = [[s[0], s[1] / total_p_counts] for s in same_trimmed_p_counts]\n",
1218
+ " same_trimmed_pitches_counts_ratios = [[s[0], s[1] / total_pitches_counts] for s in same_trimmed_pitches_counts]\n",
1219
+ "\n",
1220
+ " same_pitches_counts_ratios = []\n",
1221
+ "\n",
1222
+ " for i in range(len(same_trimmed_p_counts_ratios)):\n",
1223
+ " mincratio = min(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])\n",
1224
+ " maxcratio = max(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])\n",
1225
+ " same_pitches_counts_ratios.append([same_trimmed_p_counts_ratios[i][0], mincratio / maxcratio])\n",
1226
+ "\n",
1227
+ " same_counts_ratios = [s[1] for s in same_pitches_counts_ratios]\n",
1228
+ "\n",
1229
+ " if len(same_counts_ratios) > 0:\n",
1230
+ " avg_same_pitches_counts_ratio = sum(same_counts_ratios) / len(same_counts_ratios)\n",
1231
+ " else:\n",
1232
+ " avg_same_pitches_counts_ratio = 0\n",
1233
  "\n",
1234
+ " spcrat[0] = avg_same_pitches_counts_ratio\n",
1235
  "\n",
1236
+ " #===================================================\n",
1237
+ "\n",
1238
+ " r_list = [sprat[0]]\n",
1239
+ "\n",
1240
+ " if add_pitches_counts_ratios:\n",
1241
+ " r_list.append(spcrat[0])\n",
1242
+ " \n",
1243
+ " if add_timings_ratios:\n",
1244
+ " r_list.append(atrat[0])\n",
1245
+ " \n",
1246
+ " if add_durations_ratios:\n",
1247
+ " r_list.append(adrat[0])\n",
1248
+ "\n",
1249
+ " ratios_list.append(r_list)\n",
1250
+ "\n",
1251
+ " #===================================================\n",
1252
+ " \n",
1253
+ " avg_ratios_list = []\n",
1254
+ "\n",
1255
+ " for r in ratios_list:\n",
1256
+ " avg_ratios_list.append(sum(r) / len(r))\n",
1257
+ "\n",
1258
+ " #===================================================\n",
1259
+ " \n",
1260
+ " final_ratio = max(avg_ratios_list)\n",
1261
+ " \n",
1262
+ " if final_ratio > maximum_match_ratio_to_search_for:\n",
1263
+ " final_ratio = 0\n",
1264
+ "\n",
1265
+ " final_ratios.append(final_ratio)\n",
1266
+ "\n",
1267
+ " #===================================================\n",
1268
  " \n",
1269
  " except KeyboardInterrupt:\n",
1270
  " break\n",
 
1277
  " print('=' * 70)\n",
1278
  " break\n",
1279
  "\n",
1280
+ "max_ratio = max(final_ratios)\n",
1281
+ "max_ratio_index = final_ratios.index(max_ratio)\n",
1282
  "\n",
1283
  "print('FOUND')\n",
1284
  "print('=' * 70)\n",
MIDI.py ADDED
@@ -0,0 +1,1730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/python3
2
+ # unsupported 20091104 ...
3
+ # ['set_sequence_number', dtime, sequence]
4
+ # ['raw_data', dtime, raw]
5
+
6
+ # 20150914 jimbo1qaz MIDI.py str/bytes bug report
7
+ # I found a MIDI file which had Shift-JIS titles. When midi.py decodes it as
8
+ # latin-1, it produces a string which cannot even be accessed without raising
9
+ # a UnicodeDecodeError. Maybe, when converting raw byte strings from MIDI,
10
+ # you should keep them as bytes, not improperly decode them. However, this
11
+ # would change the API. (ie: text = a "string" ? of 0 or more bytes). It
12
+ # could break compatiblity, but there's not much else you can do to fix the bug
13
+ # https://en.wikipedia.org/wiki/Shift_JIS
14
+
15
+ r'''
16
+ This module offers functions: concatenate_scores(), grep(),
17
+ merge_scores(), mix_scores(), midi2opus(), midi2score(), opus2midi(),
18
+ opus2score(), play_score(), score2midi(), score2opus(), score2stats(),
19
+ score_type(), segment(), timeshift() and to_millisecs(),
20
+ where "midi" means the MIDI-file bytes (as can be put in a .mid file,
21
+ or piped into aplaymidi), and "opus" and "score" are list-structures
22
+ as inspired by Sean Burke's MIDI-Perl CPAN module.
23
+
24
+ Warning: Version 6.4 is not necessarily backward-compatible with
25
+ previous versions, in that text-data is now bytes, not strings.
26
+ This reflects the fact that many MIDI files have text data in
27
+ encodings other that ISO-8859-1, for example in Shift-JIS.
28
+
29
+ Download MIDI.py from http://www.pjb.com.au/midi/free/MIDI.py
30
+ and put it in your PYTHONPATH. MIDI.py depends on Python3.
31
+
32
+ There is also a call-compatible translation into Lua of this
33
+ module: see http://www.pjb.com.au/comp/lua/MIDI.html
34
+
35
+ The "opus" is a direct translation of the midi-file-events, where
36
+ the times are delta-times, in ticks, since the previous event.
37
+
38
+ The "score" is more human-centric; it uses absolute times, and
39
+ combines the separate note_on and note_off events into one "note"
40
+ event, with a duration:
41
+ ['note', start_time, duration, channel, note, velocity] # in a "score"
42
+
43
+ EVENTS (in an "opus" structure)
44
+ ['note_off', dtime, channel, note, velocity] # in an "opus"
45
+ ['note_on', dtime, channel, note, velocity] # in an "opus"
46
+ ['key_after_touch', dtime, channel, note, velocity]
47
+ ['control_change', dtime, channel, controller(0-127), value(0-127)]
48
+ ['patch_change', dtime, channel, patch]
49
+ ['channel_after_touch', dtime, channel, velocity]
50
+ ['pitch_wheel_change', dtime, channel, pitch_wheel]
51
+ ['text_event', dtime, text]
52
+ ['copyright_text_event', dtime, text]
53
+ ['track_name', dtime, text]
54
+ ['instrument_name', dtime, text]
55
+ ['lyric', dtime, text]
56
+ ['marker', dtime, text]
57
+ ['cue_point', dtime, text]
58
+ ['text_event_08', dtime, text]
59
+ ['text_event_09', dtime, text]
60
+ ['text_event_0a', dtime, text]
61
+ ['text_event_0b', dtime, text]
62
+ ['text_event_0c', dtime, text]
63
+ ['text_event_0d', dtime, text]
64
+ ['text_event_0e', dtime, text]
65
+ ['text_event_0f', dtime, text]
66
+ ['end_track', dtime]
67
+ ['set_tempo', dtime, tempo]
68
+ ['smpte_offset', dtime, hr, mn, se, fr, ff]
69
+ ['time_signature', dtime, nn, dd, cc, bb]
70
+ ['key_signature', dtime, sf, mi]
71
+ ['sequencer_specific', dtime, raw]
72
+ ['raw_meta_event', dtime, command(0-255), raw]
73
+ ['sysex_f0', dtime, raw]
74
+ ['sysex_f7', dtime, raw]
75
+ ['song_position', dtime, song_pos]
76
+ ['song_select', dtime, song_number]
77
+ ['tune_request', dtime]
78
+
79
+ DATA TYPES
80
+ channel = a value 0 to 15
81
+ controller = 0 to 127 (see http://www.pjb.com.au/muscript/gm.html#cc )
82
+ dtime = time measured in "ticks", 0 to 268435455
83
+ velocity = a value 0 (soft) to 127 (loud)
84
+ note = a value 0 to 127 (middle-C is 60)
85
+ patch = 0 to 127 (see http://www.pjb.com.au/muscript/gm.html )
86
+ pitch_wheel = a value -8192 to 8191 (0x1FFF)
87
+ raw = bytes, of length 0 or more (for sysex events see below)
88
+ sequence_number = a value 0 to 65,535 (0xFFFF)
89
+ song_pos = a value 0 to 16,383 (0x3FFF)
90
+ song_number = a value 0 to 127
91
+ tempo = microseconds per crochet (quarter-note), 0 to 16777215
92
+ text = bytes, of length 0 or more
93
+ ticks = the number of ticks per crochet (quarter-note)
94
+
95
+ In sysex_f0 events, the raw data must not start with a \xF0 byte,
96
+ since this gets added automatically;
97
+ but it must end with an explicit \xF7 byte!
98
+ In the very unlikely case that you ever need to split sysex data
99
+ into one sysex_f0 followed by one or more sysex_f7s, then only the
100
+ last of those sysex_f7 events must end with the explicit \xF7 byte
101
+ (again, the raw data of individual sysex_f7 events must not start
102
+ with any \xF7 byte, since this gets added automatically).
103
+
104
+ Since version 6.4, text data is in bytes, not in a ISO-8859-1 string.
105
+
106
+
107
+ GOING THROUGH A SCORE WITHIN A PYTHON PROGRAM
108
+ channels = {2,3,5,8,13}
109
+ itrack = 1 # skip 1st element which is ticks
110
+ while itrack < len(score):
111
+ for event in score[itrack]:
112
+ if event[0] == 'note': # for example,
113
+ pass # do something to all notes
114
+ # or, to work on events in only particular channels...
115
+ channel_index = MIDI.Event2channelindex.get(event[0], False)
116
+ if channel_index and (event[channel_index] in channels):
117
+ pass # do something to channels 2,3,5,8 and 13
118
+ itrack += 1
119
+
120
+ '''
121
+
122
+ import sys, struct, copy
123
+ # sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb')
124
+ Version = '6.7'
125
+ VersionDate = '20201120'
126
+ # 20201120 6.7 call to bytest() removed, and protect _unshift_ber_int
127
+ # 20160702 6.6 to_millisecs() now handles set_tempo across multiple Tracks
128
+ # 20150921 6.5 segment restores controllers as well as patch and tempo
129
+ # 20150914 6.4 text data is bytes or bytearray, not ISO-8859-1 strings
130
+ # 20150628 6.3 absent any set_tempo, default is 120bpm (see MIDI file spec 1.1)
131
+ # 20150101 6.2 all text events can be 8-bit; let user get the right encoding
132
+ # 20141231 6.1 fix _some_text_event; sequencer_specific data can be 8-bit
133
+ # 20141230 6.0 synth_specific data can be 8-bit
134
+ # 20120504 5.9 add the contents of mid_opus_tracks()
135
+ # 20120208 5.8 fix num_notes_by_channel() ; should be a dict
136
+ # 20120129 5.7 _encode handles empty tracks; score2stats num_notes_by_channel
137
+ # 20111111 5.6 fix patch 45 and 46 in Number2patch, should be Harp
138
+ # 20110129 5.5 add mix_opus_tracks() and event2alsaseq()
139
+ # 20110126 5.4 "previous message repeated N times" to save space on stderr
140
+ # 20110125 5.2 opus2score terminates unended notes at the end of the track
141
+ # 20110124 5.1 the warnings in midi2opus display track_num
142
+ # 21110122 5.0 if garbage, midi2opus returns the opus so far
143
+ # 21110119 4.9 non-ascii chars stripped out of the text_events
144
+ # 21110110 4.8 note_on with velocity=0 treated as a note-off
145
+ # 21110108 4.6 unknown F-series event correctly eats just one byte
146
+ # 21011010 4.2 segment() uses start_time, end_time named params
147
+ # 21011005 4.1 timeshift() must not pad the set_tempo command
148
+ # 21011003 4.0 pitch2note_event must be chapitch2note_event
149
+ # 21010918 3.9 set_sequence_number supported, FWIW
150
+ # 20100913 3.7 many small bugfixes; passes all tests
151
+ # 20100910 3.6 concatenate_scores enforce ticks=1000, just like merge_scores
152
+ # 20100908 3.5 minor bugs fixed in score2stats
153
+ # 20091104 3.4 tune_request now supported
154
+ # 20091104 3.3 fixed bug in decoding song_position and song_select
155
+ # 20091104 3.2 unsupported: set_sequence_number tune_request raw_data
156
+ # 20091101 3.1 document how to traverse a score within Python
157
+ # 20091021 3.0 fixed bug in score2stats detecting GM-mode = 0
158
+ # 20091020 2.9 score2stats reports GM-mode and bank msb,lsb events
159
+ # 20091019 2.8 in merge_scores, channel 9 must remain channel 9 (in GM)
160
+ # 20091018 2.7 handles empty tracks gracefully
161
+ # 20091015 2.6 grep() selects channels
162
+ # 20091010 2.5 merge_scores reassigns channels to avoid conflicts
163
+ # 20091010 2.4 fixed bug in to_millisecs which now only does opusses
164
+ # 20091010 2.3 score2stats returns channels & patch_changes, by_track & total
165
+ # 20091010 2.2 score2stats() returns also pitches and percussion dicts
166
+ # 20091010 2.1 bugs: >= not > in segment, to notice patch_change at time 0
167
+ # 20091010 2.0 bugs: spurious pop(0) ( in _decode sysex
168
+ # 20091008 1.9 bugs: ISO decoding in sysex; str( not int( in note-off warning
169
+ # 20091008 1.8 add concatenate_scores()
170
+ # 20091006 1.7 score2stats() measures nticks and ticks_per_quarter
171
+ # 20091004 1.6 first mix_scores() and merge_scores()
172
+ # 20090424 1.5 timeshift() bugfix: earliest only sees events after from_time
173
+ # 20090330 1.4 timeshift() has also a from_time argument
174
+ # 20090322 1.3 timeshift() has also a start_time argument
175
+ # 20090319 1.2 add segment() and timeshift()
176
+ # 20090301 1.1 add to_millisecs()
177
+
178
+ _previous_warning = '' # 5.4
179
+ _previous_times = 0 # 5.4
180
+ #------------------------------- Encoding stuff --------------------------
181
+
182
+ def opus2midi(opus=[]):
183
+ r'''The argument is a list: the first item in the list is the "ticks"
184
+ parameter, the others are the tracks. Each track is a list
185
+ of midi-events, and each event is itself a list; see above.
186
+ opus2midi() returns a bytestring of the MIDI, which can then be
187
+ written either to a file opened in binary mode (mode='wb'),
188
+ or to stdout by means of: sys.stdout.buffer.write()
189
+
190
+ my_opus = [
191
+ 96,
192
+ [ # track 0:
193
+ ['patch_change', 0, 1, 8], # and these are the events...
194
+ ['note_on', 5, 1, 25, 96],
195
+ ['note_off', 96, 1, 25, 0],
196
+ ['note_on', 0, 1, 29, 96],
197
+ ['note_off', 96, 1, 29, 0],
198
+ ], # end of track 0
199
+ ]
200
+ my_midi = opus2midi(my_opus)
201
+ sys.stdout.buffer.write(my_midi)
202
+ '''
203
+ if len(opus) < 2:
204
+ opus=[1000, [],]
205
+ tracks = copy.deepcopy(opus)
206
+ ticks = int(tracks.pop(0))
207
+ ntracks = len(tracks)
208
+ if ntracks == 1:
209
+ format = 0
210
+ else:
211
+ format = 1
212
+
213
+ my_midi = b"MThd\x00\x00\x00\x06"+struct.pack('>HHH',format,ntracks,ticks)
214
+ for track in tracks:
215
+ events = _encode(track)
216
+ my_midi += b'MTrk' + struct.pack('>I',len(events)) + events
217
+ _clean_up_warnings()
218
+ return my_midi
219
+
220
+
221
+ def score2opus(score=None):
222
+ r'''
223
+ The argument is a list: the first item in the list is the "ticks"
224
+ parameter, the others are the tracks. Each track is a list
225
+ of score-events, and each event is itself a list. A score-event
226
+ is similar to an opus-event (see above), except that in a score:
227
+ 1) the times are expressed as an absolute number of ticks
228
+ from the track's start time
229
+ 2) the pairs of 'note_on' and 'note_off' events in an "opus"
230
+ are abstracted into a single 'note' event in a "score":
231
+ ['note', start_time, duration, channel, pitch, velocity]
232
+ score2opus() returns a list specifying the equivalent "opus".
233
+
234
+ my_score = [
235
+ 96,
236
+ [ # track 0:
237
+ ['patch_change', 0, 1, 8],
238
+ ['note', 5, 96, 1, 25, 96],
239
+ ['note', 101, 96, 1, 29, 96]
240
+ ], # end of track 0
241
+ ]
242
+ my_opus = score2opus(my_score)
243
+ '''
244
+ if len(score) < 2:
245
+ score=[1000, [],]
246
+ tracks = copy.deepcopy(score)
247
+ ticks = int(tracks.pop(0))
248
+ opus_tracks = []
249
+ for scoretrack in tracks:
250
+ time2events = dict([])
251
+ for scoreevent in scoretrack:
252
+ if scoreevent[0] == 'note':
253
+ note_on_event = ['note_on',scoreevent[1],
254
+ scoreevent[3],scoreevent[4],scoreevent[5]]
255
+ note_off_event = ['note_off',scoreevent[1]+scoreevent[2],
256
+ scoreevent[3],scoreevent[4],scoreevent[5]]
257
+ if time2events.get(note_on_event[1]):
258
+ time2events[note_on_event[1]].append(note_on_event)
259
+ else:
260
+ time2events[note_on_event[1]] = [note_on_event,]
261
+ if time2events.get(note_off_event[1]):
262
+ time2events[note_off_event[1]].append(note_off_event)
263
+ else:
264
+ time2events[note_off_event[1]] = [note_off_event,]
265
+ continue
266
+ if time2events.get(scoreevent[1]):
267
+ time2events[scoreevent[1]].append(scoreevent)
268
+ else:
269
+ time2events[scoreevent[1]] = [scoreevent,]
270
+
271
+ sorted_times = [] # list of keys
272
+ for k in time2events.keys():
273
+ sorted_times.append(k)
274
+ sorted_times.sort()
275
+
276
+ sorted_events = [] # once-flattened list of values sorted by key
277
+ for time in sorted_times:
278
+ sorted_events.extend(time2events[time])
279
+
280
+ abs_time = 0
281
+ for event in sorted_events: # convert abs times => delta times
282
+ delta_time = event[1] - abs_time
283
+ abs_time = event[1]
284
+ event[1] = delta_time
285
+ opus_tracks.append(sorted_events)
286
+ opus_tracks.insert(0,ticks)
287
+ _clean_up_warnings()
288
+ return opus_tracks
289
+
290
+ def score2midi(score=None):
291
+ r'''
292
+ Translates a "score" into MIDI, using score2opus() then opus2midi()
293
+ '''
294
+ return opus2midi(score2opus(score))
295
+
296
+ #--------------------------- Decoding stuff ------------------------
297
+
298
+ def midi2opus(midi=b''):
299
+ r'''Translates MIDI into a "opus". For a description of the
300
+ "opus" format, see opus2midi()
301
+ '''
302
+ my_midi=bytearray(midi)
303
+ if len(my_midi) < 4:
304
+ _clean_up_warnings()
305
+ return [1000,[],]
306
+ id = bytes(my_midi[0:4])
307
+ if id != b'MThd':
308
+ _warn("midi2opus: midi starts with "+str(id)+" instead of 'MThd'")
309
+ _clean_up_warnings()
310
+ return [1000,[],]
311
+ [length, format, tracks_expected, ticks] = struct.unpack(
312
+ '>IHHH', bytes(my_midi[4:14]))
313
+ if length != 6:
314
+ _warn("midi2opus: midi header length was "+str(length)+" instead of 6")
315
+ _clean_up_warnings()
316
+ return [1000,[],]
317
+ my_opus = [ticks,]
318
+ my_midi = my_midi[14:]
319
+ track_num = 1 # 5.1
320
+ while len(my_midi) >= 8:
321
+ track_type = bytes(my_midi[0:4])
322
+ if track_type != b'MTrk':
323
+ _warn('midi2opus: Warning: track #'+str(track_num)+' type is '+str(track_type)+" instead of b'MTrk'")
324
+ [track_length] = struct.unpack('>I', my_midi[4:8])
325
+ my_midi = my_midi[8:]
326
+ if track_length > len(my_midi):
327
+ _warn('midi2opus: track #'+str(track_num)+' length '+str(track_length)+' is too large')
328
+ _clean_up_warnings()
329
+ return my_opus # 5.0
330
+ my_midi_track = my_midi[0:track_length]
331
+ my_track = _decode(my_midi_track)
332
+ my_opus.append(my_track)
333
+ my_midi = my_midi[track_length:]
334
+ track_num += 1 # 5.1
335
+ _clean_up_warnings()
336
+ return my_opus
337
+
338
+ def opus2score(opus=[]):
339
+ r'''For a description of the "opus" and "score" formats,
340
+ see opus2midi() and score2opus().
341
+ '''
342
+ if len(opus) < 2:
343
+ _clean_up_warnings()
344
+ return [1000,[],]
345
+ tracks = copy.deepcopy(opus) # couple of slices probably quicker...
346
+ ticks = int(tracks.pop(0))
347
+ score = [ticks,]
348
+ for opus_track in tracks:
349
+ ticks_so_far = 0
350
+ score_track = []
351
+ chapitch2note_on_events = dict([]) # 4.0
352
+ for opus_event in opus_track:
353
+ ticks_so_far += opus_event[1]
354
+ if opus_event[0] == 'note_off' or (opus_event[0] == 'note_on' and opus_event[4] == 0): # 4.8
355
+ cha = opus_event[2]
356
+ pitch = opus_event[3]
357
+ key = cha*128 + pitch
358
+ if chapitch2note_on_events.get(key):
359
+ new_event = chapitch2note_on_events[key].pop(0)
360
+ new_event[2] = ticks_so_far - new_event[1]
361
+ score_track.append(new_event)
362
+ elif pitch > 127:
363
+ pass #_warn('opus2score: note_off with no note_on, bad pitch='+str(pitch))
364
+ else:
365
+ pass #_warn('opus2score: note_off with no note_on cha='+str(cha)+' pitch='+str(pitch))
366
+ elif opus_event[0] == 'note_on':
367
+ cha = opus_event[2]
368
+ pitch = opus_event[3]
369
+ key = cha*128 + pitch
370
+ new_event = ['note',ticks_so_far,0,cha,pitch, opus_event[4]]
371
+ if chapitch2note_on_events.get(key):
372
+ chapitch2note_on_events[key].append(new_event)
373
+ else:
374
+ chapitch2note_on_events[key] = [new_event,]
375
+ else:
376
+ opus_event[1] = ticks_so_far
377
+ score_track.append(opus_event)
378
+ # check for unterminated notes (Oisín) -- 5.2
379
+ for chapitch in chapitch2note_on_events:
380
+ note_on_events = chapitch2note_on_events[chapitch]
381
+ for new_e in note_on_events:
382
+ new_e[2] = ticks_so_far - new_e[1]
383
+ score_track.append(new_e)
384
+ pass #_warn("opus2score: note_on with no note_off cha="+str(new_e[3])+' pitch='+str(new_e[4])+'; adding note_off at end')
385
+ score.append(score_track)
386
+ _clean_up_warnings()
387
+ return score
388
+
389
+ def midi2score(midi=b''):
390
+ r'''
391
+ Translates MIDI into a "score", using midi2opus() then opus2score()
392
+ '''
393
+ return opus2score(midi2opus(midi))
394
+
395
+ def midi2ms_score(midi=b''):
396
+ r'''
397
+ Translates MIDI into a "score" with one beat per second and one
398
+ tick per millisecond, using midi2opus() then to_millisecs()
399
+ then opus2score()
400
+ '''
401
+ return opus2score(to_millisecs(midi2opus(midi)))
402
+
403
+ #------------------------ Other Transformations ---------------------
404
+
405
+ def to_millisecs(old_opus=None):
406
+ r'''Recallibrates all the times in an "opus" to use one beat
407
+ per second and one tick per millisecond. This makes it
408
+ hard to retrieve any information about beats or barlines,
409
+ but it does make it easy to mix different scores together.
410
+ '''
411
+ if old_opus == None:
412
+ return [1000,[],]
413
+ try:
414
+ old_tpq = int(old_opus[0])
415
+ except IndexError: # 5.0
416
+ _warn('to_millisecs: the opus '+str(type(old_opus))+' has no elements')
417
+ return [1000,[],]
418
+ new_opus = [1000,]
419
+ # 6.7 first go through building a table of set_tempos by absolute-tick
420
+ ticks2tempo = {}
421
+ itrack = 1
422
+ while itrack < len(old_opus):
423
+ ticks_so_far = 0
424
+ for old_event in old_opus[itrack]:
425
+ if old_event[0] == 'note':
426
+ raise TypeError('to_millisecs needs an opus, not a score')
427
+ ticks_so_far += old_event[1]
428
+ if old_event[0] == 'set_tempo':
429
+ ticks2tempo[ticks_so_far] = old_event[2]
430
+ itrack += 1
431
+ # then get the sorted-array of their keys
432
+ tempo_ticks = [] # list of keys
433
+ for k in ticks2tempo.keys():
434
+ tempo_ticks.append(k)
435
+ tempo_ticks.sort()
436
+ # then go through converting to millisec, testing if the next
437
+ # set_tempo lies before the next track-event, and using it if so.
438
+ itrack = 1
439
+ while itrack < len(old_opus):
440
+ ms_per_old_tick = 500.0 / old_tpq # float: will round later 6.3
441
+ i_tempo_ticks = 0
442
+ ticks_so_far = 0
443
+ ms_so_far = 0.0
444
+ previous_ms_so_far = 0.0
445
+ new_track = [['set_tempo',0,1000000],] # new "crochet" is 1 sec
446
+ for old_event in old_opus[itrack]:
447
+ # detect if ticks2tempo has something before this event
448
+ # 20160702 if ticks2tempo is at the same time, leave it
449
+ event_delta_ticks = old_event[1]
450
+ if (i_tempo_ticks < len(tempo_ticks) and
451
+ tempo_ticks[i_tempo_ticks] < (ticks_so_far + old_event[1])):
452
+ delta_ticks = tempo_ticks[i_tempo_ticks] - ticks_so_far
453
+ ms_so_far += (ms_per_old_tick * delta_ticks)
454
+ ticks_so_far = tempo_ticks[i_tempo_ticks]
455
+ ms_per_old_tick = ticks2tempo[ticks_so_far] / (1000.0*old_tpq)
456
+ i_tempo_ticks += 1
457
+ event_delta_ticks -= delta_ticks
458
+ new_event = copy.deepcopy(old_event) # now handle the new event
459
+ ms_so_far += (ms_per_old_tick * old_event[1])
460
+ new_event[1] = round(ms_so_far - previous_ms_so_far)
461
+ if old_event[0] != 'set_tempo':
462
+ previous_ms_so_far = ms_so_far
463
+ new_track.append(new_event)
464
+ ticks_so_far += event_delta_ticks
465
+ new_opus.append(new_track)
466
+ itrack += 1
467
+ _clean_up_warnings()
468
+ return new_opus
469
+
470
+ def event2alsaseq(event=None): # 5.5
471
+ r'''Converts an event into the format needed by the alsaseq module,
472
+ http://pp.com.mx/python/alsaseq
473
+ The type of track (opus or score) is autodetected.
474
+ '''
475
+ pass
476
+
477
+ def grep(score=None, channels=None):
478
+ r'''Returns a "score" containing only the channels specified
479
+ '''
480
+ if score == None:
481
+ return [1000,[],]
482
+ ticks = score[0]
483
+ new_score = [ticks,]
484
+ if channels == None:
485
+ return new_score
486
+ channels = set(channels)
487
+ global Event2channelindex
488
+ itrack = 1
489
+ while itrack < len(score):
490
+ new_score.append([])
491
+ for event in score[itrack]:
492
+ channel_index = Event2channelindex.get(event[0], False)
493
+ if channel_index:
494
+ if event[channel_index] in channels:
495
+ new_score[itrack].append(event)
496
+ else:
497
+ new_score[itrack].append(event)
498
+ itrack += 1
499
+ return new_score
500
+
501
+ def play_score(score=None):
502
+ r'''Converts the "score" to midi, and feeds it into 'aplaymidi -'
503
+ '''
504
+ if score == None:
505
+ return
506
+ import subprocess
507
+ pipe = subprocess.Popen(['aplaymidi','-'], stdin=subprocess.PIPE)
508
+ if score_type(score) == 'opus':
509
+ pipe.stdin.write(opus2midi(score))
510
+ else:
511
+ pipe.stdin.write(score2midi(score))
512
+ pipe.stdin.close()
513
+
514
+ def timeshift(score=None, shift=None, start_time=None, from_time=0, tracks={0,1,2,3,4,5,6,7,8,10,12,13,14,15}):
515
+ r'''Returns a "score" shifted in time by "shift" ticks, or shifted
516
+ so that the first event starts at "start_time" ticks.
517
+
518
+ If "from_time" is specified, only those events in the score
519
+ that begin after it are shifted. If "start_time" is less than
520
+ "from_time" (or "shift" is negative), then the intermediate
521
+ notes are deleted, though patch-change events are preserved.
522
+
523
+ If "tracks" are specified, then only those tracks get shifted.
524
+ "tracks" can be a list, tuple or set; it gets converted to set
525
+ internally.
526
+
527
+ It is deprecated to specify both "shift" and "start_time".
528
+ If this does happen, timeshift() will print a warning to
529
+ stderr and ignore the "shift" argument.
530
+
531
+ If "shift" is negative and sufficiently large that it would
532
+ leave some event with a negative tick-value, then the score
533
+ is shifted so that the first event occurs at time 0. This
534
+ also occurs if "start_time" is negative, and is also the
535
+ default if neither "shift" nor "start_time" are specified.
536
+ '''
537
+ #_warn('tracks='+str(tracks))
538
+ if score == None or len(score) < 2:
539
+ return [1000, [],]
540
+ new_score = [score[0],]
541
+ my_type = score_type(score)
542
+ if my_type == '':
543
+ return new_score
544
+ if my_type == 'opus':
545
+ _warn("timeshift: opus format is not supported\n")
546
+ # _clean_up_scores() 6.2; doesn't exist! what was it supposed to do?
547
+ return new_score
548
+ if not (shift == None) and not (start_time == None):
549
+ _warn("timeshift: shift and start_time specified: ignoring shift\n")
550
+ shift = None
551
+ if shift == None:
552
+ if (start_time == None) or (start_time < 0):
553
+ start_time = 0
554
+ # shift = start_time - from_time
555
+
556
+ i = 1 # ignore first element (ticks)
557
+ tracks = set(tracks) # defend against tuples and lists
558
+ earliest = 1000000000
559
+ if not (start_time == None) or shift < 0: # first find the earliest event
560
+ while i < len(score):
561
+ if len(tracks) and not ((i-1) in tracks):
562
+ i += 1
563
+ continue
564
+ for event in score[i]:
565
+ if event[1] < from_time:
566
+ continue # just inspect the to_be_shifted events
567
+ if event[1] < earliest:
568
+ earliest = event[1]
569
+ i += 1
570
+ if earliest > 999999999:
571
+ earliest = 0
572
+ if shift == None:
573
+ shift = start_time - earliest
574
+ elif (earliest + shift) < 0:
575
+ start_time = 0
576
+ shift = 0 - earliest
577
+
578
+ i = 1 # ignore first element (ticks)
579
+ while i < len(score):
580
+ if len(tracks) == 0 or not ((i-1) in tracks): # 3.8
581
+ new_score.append(score[i])
582
+ i += 1
583
+ continue
584
+ new_track = []
585
+ for event in score[i]:
586
+ new_event = list(event)
587
+ #if new_event[1] == 0 and shift > 0 and new_event[0] != 'note':
588
+ # pass
589
+ #elif new_event[1] >= from_time:
590
+ if new_event[1] >= from_time:
591
+ # 4.1 must not rightshift set_tempo
592
+ if new_event[0] != 'set_tempo' or shift<0:
593
+ new_event[1] += shift
594
+ elif (shift < 0) and (new_event[1] >= (from_time+shift)):
595
+ continue
596
+ new_track.append(new_event)
597
+ if len(new_track) > 0:
598
+ new_score.append(new_track)
599
+ i += 1
600
+ _clean_up_warnings()
601
+ return new_score
602
+
603
+ def segment(score=None, start_time=None, end_time=None, start=0, end=100000000,
604
+ tracks={0,1,2,3,4,5,6,7,8,10,11,12,13,14,15}):
605
+ r'''Returns a "score" which is a segment of the one supplied
606
+ as the argument, beginning at "start_time" ticks and ending
607
+ at "end_time" ticks (or at the end if "end_time" is not supplied).
608
+ If the set "tracks" is specified, only those tracks will
609
+ be returned.
610
+ '''
611
+ if score == None or len(score) < 2:
612
+ return [1000, [],]
613
+ if start_time == None: # as of 4.2 start_time is recommended
614
+ start_time = start # start is legacy usage
615
+ if end_time == None: # likewise
616
+ end_time = end
617
+ new_score = [score[0],]
618
+ my_type = score_type(score)
619
+ if my_type == '':
620
+ return new_score
621
+ if my_type == 'opus':
622
+ # more difficult (disconnecting note_on's from their note_off's)...
623
+ _warn("segment: opus format is not supported\n")
624
+ _clean_up_warnings()
625
+ return new_score
626
+ i = 1 # ignore first element (ticks); we count in ticks anyway
627
+ tracks = set(tracks) # defend against tuples and lists
628
+ while i < len(score):
629
+ if len(tracks) and not ((i-1) in tracks):
630
+ i += 1
631
+ continue
632
+ new_track = []
633
+ channel2cc_num = {} # most recent controller change before start
634
+ channel2cc_val = {}
635
+ channel2cc_time = {}
636
+ channel2patch_num = {} # keep most recent patch change before start
637
+ channel2patch_time = {}
638
+ set_tempo_num = 500000 # most recent tempo change before start 6.3
639
+ set_tempo_time = 0
640
+ earliest_note_time = end_time
641
+ for event in score[i]:
642
+ if event[0] == 'control_change': # 6.5
643
+ cc_time = channel2cc_time.get(event[2]) or 0
644
+ if (event[1] <= start_time) and (event[1] >= cc_time):
645
+ channel2cc_num[event[2]] = event[3]
646
+ channel2cc_val[event[2]] = event[4]
647
+ channel2cc_time[event[2]] = event[1]
648
+ elif event[0] == 'patch_change':
649
+ patch_time = channel2patch_time.get(event[2]) or 0
650
+ if (event[1]<=start_time) and (event[1] >= patch_time): # 2.0
651
+ channel2patch_num[event[2]] = event[3]
652
+ channel2patch_time[event[2]] = event[1]
653
+ elif event[0] == 'set_tempo':
654
+ if (event[1]<=start_time) and (event[1]>=set_tempo_time): #6.4
655
+ set_tempo_num = event[2]
656
+ set_tempo_time = event[1]
657
+ if (event[1] >= start_time) and (event[1] <= end_time):
658
+ new_track.append(event)
659
+ if (event[0] == 'note') and (event[1] < earliest_note_time):
660
+ earliest_note_time = event[1]
661
+ if len(new_track) > 0:
662
+ new_track.append(['set_tempo', start_time, set_tempo_num])
663
+ for c in channel2patch_num:
664
+ new_track.append(['patch_change',start_time,c,channel2patch_num[c]],)
665
+ for c in channel2cc_num: # 6.5
666
+ new_track.append(['control_change',start_time,c,channel2cc_num[c],channel2cc_val[c]])
667
+ new_score.append(new_track)
668
+ i += 1
669
+ _clean_up_warnings()
670
+ return new_score
671
+
672
+ def score_type(opus_or_score=None):
673
+ r'''Returns a string, either 'opus' or 'score' or ''
674
+ '''
675
+ if opus_or_score == None or str(type(opus_or_score)).find('list')<0 or len(opus_or_score) < 2:
676
+ return ''
677
+ i = 1 # ignore first element
678
+ while i < len(opus_or_score):
679
+ for event in opus_or_score[i]:
680
+ if event[0] == 'note':
681
+ return 'score'
682
+ elif event[0] == 'note_on':
683
+ return 'opus'
684
+ i += 1
685
+ return ''
686
+
687
+ def concatenate_scores(scores):
688
+ r'''Concatenates a list of scores into one score.
689
+ If the scores differ in their "ticks" parameter,
690
+ they will all get converted to millisecond-tick format.
691
+ '''
692
+ # the deepcopys are needed if the input_score's are refs to the same obj
693
+ # e.g. if invoked by midisox's repeat()
694
+ input_scores = _consistentise_ticks(scores) # 3.7
695
+ output_score = copy.deepcopy(input_scores[0])
696
+ for input_score in input_scores[1:]:
697
+ output_stats = score2stats(output_score)
698
+ delta_ticks = output_stats['nticks']
699
+ itrack = 1
700
+ while itrack < len(input_score):
701
+ if itrack >= len(output_score): # new output track if doesn't exist
702
+ output_score.append([])
703
+ for event in input_score[itrack]:
704
+ output_score[itrack].append(copy.deepcopy(event))
705
+ output_score[itrack][-1][1] += delta_ticks
706
+ itrack += 1
707
+ return output_score
708
+
709
+ def merge_scores(scores):
710
+ r'''Merges a list of scores into one score. A merged score comprises
711
+ all of the tracks from all of the input scores; un-merging is possible
712
+ by selecting just some of the tracks. If the scores differ in their
713
+ "ticks" parameter, they will all get converted to millisecond-tick
714
+ format. merge_scores attempts to resolve channel-conflicts,
715
+ but there are of course only 15 available channels...
716
+ '''
717
+ input_scores = _consistentise_ticks(scores) # 3.6
718
+ output_score = [1000]
719
+ channels_so_far = set()
720
+ all_channels = {0,1,2,3,4,5,6,7,8,10,11,12,13,14,15}
721
+ global Event2channelindex
722
+ for input_score in input_scores:
723
+ new_channels = set(score2stats(input_score).get('channels_total', []))
724
+ new_channels.discard(9) # 2.8 cha9 must remain cha9 (in GM)
725
+ for channel in channels_so_far & new_channels:
726
+ # consistently choose lowest avaiable, to ease testing
727
+ free_channels = list(all_channels - (channels_so_far|new_channels))
728
+ if len(free_channels) > 0:
729
+ free_channels.sort()
730
+ free_channel = free_channels[0]
731
+ else:
732
+ free_channel = None
733
+ break
734
+ itrack = 1
735
+ while itrack < len(input_score):
736
+ for input_event in input_score[itrack]:
737
+ channel_index=Event2channelindex.get(input_event[0],False)
738
+ if channel_index and input_event[channel_index]==channel:
739
+ input_event[channel_index] = free_channel
740
+ itrack += 1
741
+ channels_so_far.add(free_channel)
742
+
743
+ channels_so_far |= new_channels
744
+ output_score.extend(input_score[1:])
745
+ return output_score
746
+
747
+ def _ticks(event):
748
+ return event[1]
749
+ def mix_opus_tracks(input_tracks): # 5.5
750
+ r'''Mixes an array of tracks into one track. A mixed track
751
+ cannot be un-mixed. It is assumed that the tracks share the same
752
+ ticks parameter and the same tempo.
753
+ Mixing score-tracks is trivial (just insert all events into one array).
754
+ Mixing opus-tracks is only slightly harder, but it's common enough
755
+ that a dedicated function is useful.
756
+ '''
757
+ output_score = [1000, []]
758
+ for input_track in input_tracks: # 5.8
759
+ input_score = opus2score([1000, input_track])
760
+ for event in input_score[1]:
761
+ output_score[1].append(event)
762
+ output_score[1].sort(key=_ticks)
763
+ output_opus = score2opus(output_score)
764
+ return output_opus[1]
765
+
766
+ def mix_scores(scores):
767
+ r'''Mixes a list of scores into one one-track score.
768
+ A mixed score cannot be un-mixed. Hopefully the scores
769
+ have no undesirable channel-conflicts between them.
770
+ If the scores differ in their "ticks" parameter,
771
+ they will all get converted to millisecond-tick format.
772
+ '''
773
+ input_scores = _consistentise_ticks(scores) # 3.6
774
+ output_score = [1000, []]
775
+ for input_score in input_scores:
776
+ for input_track in input_score[1:]:
777
+ output_score[1].extend(input_track)
778
+ return output_score
779
+
780
+ def score2stats(opus_or_score=None):
781
+ r'''Returns a dict of some basic stats about the score, like
782
+ bank_select (list of tuples (msb,lsb)),
783
+ channels_by_track (list of lists), channels_total (set),
784
+ general_midi_mode (list),
785
+ ntracks, nticks, patch_changes_by_track (list of dicts),
786
+ num_notes_by_channel (list of numbers),
787
+ patch_changes_total (set),
788
+ percussion (dict histogram of channel 9 events),
789
+ pitches (dict histogram of pitches on channels other than 9),
790
+ pitch_range_by_track (list, by track, of two-member-tuples),
791
+ pitch_range_sum (sum over tracks of the pitch_ranges),
792
+ '''
793
+ bank_select_msb = -1
794
+ bank_select_lsb = -1
795
+ bank_select = []
796
+ channels_by_track = []
797
+ channels_total = set([])
798
+ general_midi_mode = []
799
+ num_notes_by_channel = dict([])
800
+ patches_used_by_track = []
801
+ patches_used_total = set([])
802
+ patch_changes_by_track = []
803
+ patch_changes_total = set([])
804
+ percussion = dict([]) # histogram of channel 9 "pitches"
805
+ pitches = dict([]) # histogram of pitch-occurrences channels 0-8,10-15
806
+ pitch_range_sum = 0 # u pitch-ranges of each track
807
+ pitch_range_by_track = []
808
+ is_a_score = True
809
+ if opus_or_score == None:
810
+ return {'bank_select':[], 'channels_by_track':[], 'channels_total':[],
811
+ 'general_midi_mode':[], 'ntracks':0, 'nticks':0,
812
+ 'num_notes_by_channel':dict([]),
813
+ 'patch_changes_by_track':[], 'patch_changes_total':[],
814
+ 'percussion':{}, 'pitches':{}, 'pitch_range_by_track':[],
815
+ 'ticks_per_quarter':0, 'pitch_range_sum':0}
816
+ ticks_per_quarter = opus_or_score[0]
817
+ i = 1 # ignore first element, which is ticks
818
+ nticks = 0
819
+ while i < len(opus_or_score):
820
+ highest_pitch = 0
821
+ lowest_pitch = 128
822
+ channels_this_track = set([])
823
+ patch_changes_this_track = dict({})
824
+ for event in opus_or_score[i]:
825
+ if event[0] == 'note':
826
+ num_notes_by_channel[event[3]] = num_notes_by_channel.get(event[3],0) + 1
827
+ if event[3] == 9:
828
+ percussion[event[4]] = percussion.get(event[4],0) + 1
829
+ else:
830
+ pitches[event[4]] = pitches.get(event[4],0) + 1
831
+ if event[4] > highest_pitch:
832
+ highest_pitch = event[4]
833
+ if event[4] < lowest_pitch:
834
+ lowest_pitch = event[4]
835
+ channels_this_track.add(event[3])
836
+ channels_total.add(event[3])
837
+ finish_time = event[1] + event[2]
838
+ if finish_time > nticks:
839
+ nticks = finish_time
840
+ elif event[0] == 'note_off' or (event[0] == 'note_on' and event[4] == 0): # 4.8
841
+ finish_time = event[1]
842
+ if finish_time > nticks:
843
+ nticks = finish_time
844
+ elif event[0] == 'note_on':
845
+ is_a_score = False
846
+ num_notes_by_channel[event[2]] = num_notes_by_channel.get(event[2],0) + 1
847
+ if event[2] == 9:
848
+ percussion[event[3]] = percussion.get(event[3],0) + 1
849
+ else:
850
+ pitches[event[3]] = pitches.get(event[3],0) + 1
851
+ if event[3] > highest_pitch:
852
+ highest_pitch = event[3]
853
+ if event[3] < lowest_pitch:
854
+ lowest_pitch = event[3]
855
+ channels_this_track.add(event[2])
856
+ channels_total.add(event[2])
857
+ elif event[0] == 'patch_change':
858
+ patch_changes_this_track[event[2]] = event[3]
859
+ patch_changes_total.add(event[3])
860
+ elif event[0] == 'control_change':
861
+ if event[3] == 0: # bank select MSB
862
+ bank_select_msb = event[4]
863
+ elif event[3] == 32: # bank select LSB
864
+ bank_select_lsb = event[4]
865
+ if bank_select_msb >= 0 and bank_select_lsb >= 0:
866
+ bank_select.append((bank_select_msb,bank_select_lsb))
867
+ bank_select_msb = -1
868
+ bank_select_lsb = -1
869
+ elif event[0] == 'sysex_f0':
870
+ if _sysex2midimode.get(event[2], -1) >= 0:
871
+ general_midi_mode.append(_sysex2midimode.get(event[2]))
872
+ if is_a_score:
873
+ if event[1] > nticks:
874
+ nticks = event[1]
875
+ else:
876
+ nticks += event[1]
877
+ if lowest_pitch == 128:
878
+ lowest_pitch = 0
879
+ channels_by_track.append(channels_this_track)
880
+ patch_changes_by_track.append(patch_changes_this_track)
881
+ pitch_range_by_track.append((lowest_pitch,highest_pitch))
882
+ pitch_range_sum += (highest_pitch-lowest_pitch)
883
+ i += 1
884
+
885
+ return {'bank_select':bank_select,
886
+ 'channels_by_track':channels_by_track,
887
+ 'channels_total':channels_total,
888
+ 'general_midi_mode':general_midi_mode,
889
+ 'ntracks':len(opus_or_score)-1,
890
+ 'nticks':nticks,
891
+ 'num_notes_by_channel':num_notes_by_channel,
892
+ 'patch_changes_by_track':patch_changes_by_track,
893
+ 'patch_changes_total':patch_changes_total,
894
+ 'percussion':percussion,
895
+ 'pitches':pitches,
896
+ 'pitch_range_by_track':pitch_range_by_track,
897
+ 'pitch_range_sum':pitch_range_sum,
898
+ 'ticks_per_quarter':ticks_per_quarter}
899
+
900
+ #----------------------------- Event stuff --------------------------
901
+
902
+ _sysex2midimode = {
903
+ "\x7E\x7F\x09\x01\xF7": 1,
904
+ "\x7E\x7F\x09\x02\xF7": 0,
905
+ "\x7E\x7F\x09\x03\xF7": 2,
906
+ }
907
+
908
+ # Some public-access tuples:
909
+ MIDI_events = tuple('''note_off note_on key_after_touch
910
+ control_change patch_change channel_after_touch
911
+ pitch_wheel_change'''.split())
912
+
913
+ Text_events = tuple('''text_event copyright_text_event
914
+ track_name instrument_name lyric marker cue_point text_event_08
915
+ text_event_09 text_event_0a text_event_0b text_event_0c
916
+ text_event_0d text_event_0e text_event_0f'''.split())
917
+
918
+ Nontext_meta_events = tuple('''end_track set_tempo
919
+ smpte_offset time_signature key_signature sequencer_specific
920
+ raw_meta_event sysex_f0 sysex_f7 song_position song_select
921
+ tune_request'''.split())
922
+ # unsupported: raw_data
923
+
924
+ # Actually, 'tune_request' is is F-series event, not strictly a meta-event...
925
+ Meta_events = Text_events + Nontext_meta_events
926
+ All_events = MIDI_events + Meta_events
927
+
928
+ # And three dictionaries:
929
+ Number2patch = { # General MIDI patch numbers:
930
+ 0:'Acoustic Grand',
931
+ 1:'Bright Acoustic',
932
+ 2:'Electric Grand',
933
+ 3:'Honky-Tonk',
934
+ 4:'Electric Piano 1',
935
+ 5:'Electric Piano 2',
936
+ 6:'Harpsichord',
937
+ 7:'Clav',
938
+ 8:'Celesta',
939
+ 9:'Glockenspiel',
940
+ 10:'Music Box',
941
+ 11:'Vibraphone',
942
+ 12:'Marimba',
943
+ 13:'Xylophone',
944
+ 14:'Tubular Bells',
945
+ 15:'Dulcimer',
946
+ 16:'Drawbar Organ',
947
+ 17:'Percussive Organ',
948
+ 18:'Rock Organ',
949
+ 19:'Church Organ',
950
+ 20:'Reed Organ',
951
+ 21:'Accordion',
952
+ 22:'Harmonica',
953
+ 23:'Tango Accordion',
954
+ 24:'Acoustic Guitar(nylon)',
955
+ 25:'Acoustic Guitar(steel)',
956
+ 26:'Electric Guitar(jazz)',
957
+ 27:'Electric Guitar(clean)',
958
+ 28:'Electric Guitar(muted)',
959
+ 29:'Overdriven Guitar',
960
+ 30:'Distortion Guitar',
961
+ 31:'Guitar Harmonics',
962
+ 32:'Acoustic Bass',
963
+ 33:'Electric Bass(finger)',
964
+ 34:'Electric Bass(pick)',
965
+ 35:'Fretless Bass',
966
+ 36:'Slap Bass 1',
967
+ 37:'Slap Bass 2',
968
+ 38:'Synth Bass 1',
969
+ 39:'Synth Bass 2',
970
+ 40:'Violin',
971
+ 41:'Viola',
972
+ 42:'Cello',
973
+ 43:'Contrabass',
974
+ 44:'Tremolo Strings',
975
+ 45:'Pizzicato Strings',
976
+ 46:'Orchestral Harp',
977
+ 47:'Timpani',
978
+ 48:'String Ensemble 1',
979
+ 49:'String Ensemble 2',
980
+ 50:'SynthStrings 1',
981
+ 51:'SynthStrings 2',
982
+ 52:'Choir Aahs',
983
+ 53:'Voice Oohs',
984
+ 54:'Synth Voice',
985
+ 55:'Orchestra Hit',
986
+ 56:'Trumpet',
987
+ 57:'Trombone',
988
+ 58:'Tuba',
989
+ 59:'Muted Trumpet',
990
+ 60:'French Horn',
991
+ 61:'Brass Section',
992
+ 62:'SynthBrass 1',
993
+ 63:'SynthBrass 2',
994
+ 64:'Soprano Sax',
995
+ 65:'Alto Sax',
996
+ 66:'Tenor Sax',
997
+ 67:'Baritone Sax',
998
+ 68:'Oboe',
999
+ 69:'English Horn',
1000
+ 70:'Bassoon',
1001
+ 71:'Clarinet',
1002
+ 72:'Piccolo',
1003
+ 73:'Flute',
1004
+ 74:'Recorder',
1005
+ 75:'Pan Flute',
1006
+ 76:'Blown Bottle',
1007
+ 77:'Skakuhachi',
1008
+ 78:'Whistle',
1009
+ 79:'Ocarina',
1010
+ 80:'Lead 1 (square)',
1011
+ 81:'Lead 2 (sawtooth)',
1012
+ 82:'Lead 3 (calliope)',
1013
+ 83:'Lead 4 (chiff)',
1014
+ 84:'Lead 5 (charang)',
1015
+ 85:'Lead 6 (voice)',
1016
+ 86:'Lead 7 (fifths)',
1017
+ 87:'Lead 8 (bass+lead)',
1018
+ 88:'Pad 1 (new age)',
1019
+ 89:'Pad 2 (warm)',
1020
+ 90:'Pad 3 (polysynth)',
1021
+ 91:'Pad 4 (choir)',
1022
+ 92:'Pad 5 (bowed)',
1023
+ 93:'Pad 6 (metallic)',
1024
+ 94:'Pad 7 (halo)',
1025
+ 95:'Pad 8 (sweep)',
1026
+ 96:'FX 1 (rain)',
1027
+ 97:'FX 2 (soundtrack)',
1028
+ 98:'FX 3 (crystal)',
1029
+ 99:'FX 4 (atmosphere)',
1030
+ 100:'FX 5 (brightness)',
1031
+ 101:'FX 6 (goblins)',
1032
+ 102:'FX 7 (echoes)',
1033
+ 103:'FX 8 (sci-fi)',
1034
+ 104:'Sitar',
1035
+ 105:'Banjo',
1036
+ 106:'Shamisen',
1037
+ 107:'Koto',
1038
+ 108:'Kalimba',
1039
+ 109:'Bagpipe',
1040
+ 110:'Fiddle',
1041
+ 111:'Shanai',
1042
+ 112:'Tinkle Bell',
1043
+ 113:'Agogo',
1044
+ 114:'Steel Drums',
1045
+ 115:'Woodblock',
1046
+ 116:'Taiko Drum',
1047
+ 117:'Melodic Tom',
1048
+ 118:'Synth Drum',
1049
+ 119:'Reverse Cymbal',
1050
+ 120:'Guitar Fret Noise',
1051
+ 121:'Breath Noise',
1052
+ 122:'Seashore',
1053
+ 123:'Bird Tweet',
1054
+ 124:'Telephone Ring',
1055
+ 125:'Helicopter',
1056
+ 126:'Applause',
1057
+ 127:'Gunshot',
1058
+ }
1059
+ Notenum2percussion = { # General MIDI Percussion (on Channel 9):
1060
+ 35:'Acoustic Bass Drum',
1061
+ 36:'Bass Drum 1',
1062
+ 37:'Side Stick',
1063
+ 38:'Acoustic Snare',
1064
+ 39:'Hand Clap',
1065
+ 40:'Electric Snare',
1066
+ 41:'Low Floor Tom',
1067
+ 42:'Closed Hi-Hat',
1068
+ 43:'High Floor Tom',
1069
+ 44:'Pedal Hi-Hat',
1070
+ 45:'Low Tom',
1071
+ 46:'Open Hi-Hat',
1072
+ 47:'Low-Mid Tom',
1073
+ 48:'Hi-Mid Tom',
1074
+ 49:'Crash Cymbal 1',
1075
+ 50:'High Tom',
1076
+ 51:'Ride Cymbal 1',
1077
+ 52:'Chinese Cymbal',
1078
+ 53:'Ride Bell',
1079
+ 54:'Tambourine',
1080
+ 55:'Splash Cymbal',
1081
+ 56:'Cowbell',
1082
+ 57:'Crash Cymbal 2',
1083
+ 58:'Vibraslap',
1084
+ 59:'Ride Cymbal 2',
1085
+ 60:'Hi Bongo',
1086
+ 61:'Low Bongo',
1087
+ 62:'Mute Hi Conga',
1088
+ 63:'Open Hi Conga',
1089
+ 64:'Low Conga',
1090
+ 65:'High Timbale',
1091
+ 66:'Low Timbale',
1092
+ 67:'High Agogo',
1093
+ 68:'Low Agogo',
1094
+ 69:'Cabasa',
1095
+ 70:'Maracas',
1096
+ 71:'Short Whistle',
1097
+ 72:'Long Whistle',
1098
+ 73:'Short Guiro',
1099
+ 74:'Long Guiro',
1100
+ 75:'Claves',
1101
+ 76:'Hi Wood Block',
1102
+ 77:'Low Wood Block',
1103
+ 78:'Mute Cuica',
1104
+ 79:'Open Cuica',
1105
+ 80:'Mute Triangle',
1106
+ 81:'Open Triangle',
1107
+ }
1108
+
1109
+ Event2channelindex = { 'note':3, 'note_off':2, 'note_on':2,
1110
+ 'key_after_touch':2, 'control_change':2, 'patch_change':2,
1111
+ 'channel_after_touch':2, 'pitch_wheel_change':2
1112
+ }
1113
+
1114
+ ################################################################
1115
+ # The code below this line is full of frightening things, all to
1116
+ # do with the actual encoding and decoding of binary MIDI data.
1117
+
1118
+ def _twobytes2int(byte_a):
1119
+ r'''decode a 16 bit quantity from two bytes,'''
1120
+ return (byte_a[1] | (byte_a[0] << 8))
1121
+
1122
+ def _int2twobytes(int_16bit):
1123
+ r'''encode a 16 bit quantity into two bytes,'''
1124
+ return bytes([(int_16bit>>8) & 0xFF, int_16bit & 0xFF])
1125
+
1126
+ def _read_14_bit(byte_a):
1127
+ r'''decode a 14 bit quantity from two bytes,'''
1128
+ return (byte_a[0] | (byte_a[1] << 7))
1129
+
1130
+ def _write_14_bit(int_14bit):
1131
+ r'''encode a 14 bit quantity into two bytes,'''
1132
+ return bytes([int_14bit & 0x7F, (int_14bit>>7) & 0x7F])
1133
+
1134
+ def _ber_compressed_int(integer):
1135
+ r'''BER compressed integer (not an ASN.1 BER, see perlpacktut for
1136
+ details). Its bytes represent an unsigned integer in base 128,
1137
+ most significant digit first, with as few digits as possible.
1138
+ Bit eight (the high bit) is set on each byte except the last.
1139
+ '''
1140
+ ber = bytearray(b'')
1141
+ seven_bits = 0x7F & integer
1142
+ ber.insert(0, seven_bits) # XXX surely should convert to a char ?
1143
+ integer >>= 7
1144
+ while integer > 0:
1145
+ seven_bits = 0x7F & integer
1146
+ ber.insert(0, 0x80|seven_bits) # XXX surely should convert to a char ?
1147
+ integer >>= 7
1148
+ return ber
1149
+
1150
+ def _unshift_ber_int(ba):
1151
+ r'''Given a bytearray, returns a tuple of (the ber-integer at the
1152
+ start, and the remainder of the bytearray).
1153
+ '''
1154
+ if not len(ba): # 6.7
1155
+ _warn('_unshift_ber_int: no integer found')
1156
+ return ((0, b""))
1157
+ byte = ba.pop(0)
1158
+ integer = 0
1159
+ while True:
1160
+ integer += (byte & 0x7F)
1161
+ if not (byte & 0x80):
1162
+ return ((integer, ba))
1163
+ if not len(ba):
1164
+ _warn('_unshift_ber_int: no end-of-integer found')
1165
+ return ((0, ba))
1166
+ byte = ba.pop(0)
1167
+ integer <<= 7
1168
+
1169
+ def _clean_up_warnings(): # 5.4
1170
+ # Call this before returning from any publicly callable function
1171
+ # whenever there's a possibility that a warning might have been printed
1172
+ # by the function, or by any private functions it might have called.
1173
+ global _previous_times
1174
+ global _previous_warning
1175
+ if _previous_times > 1:
1176
+ # E:1176, 0: invalid syntax (<string>, line 1176) (syntax-error) ???
1177
+ # print(' previous message repeated '+str(_previous_times)+' times', file=sys.stderr)
1178
+ # 6.7
1179
+ sys.stderr.write(' previous message repeated {0} times\n'.format(_previous_times))
1180
+ elif _previous_times > 0:
1181
+ sys.stderr.write(' previous message repeated\n')
1182
+ _previous_times = 0
1183
+ _previous_warning = ''
1184
+
1185
+ def _warn(s=''):
1186
+ global _previous_times
1187
+ global _previous_warning
1188
+ if s == _previous_warning: # 5.4
1189
+ _previous_times = _previous_times + 1
1190
+ else:
1191
+ _clean_up_warnings()
1192
+ sys.stderr.write(str(s)+"\n")
1193
+ _previous_warning = s
1194
+
1195
+ def _some_text_event(which_kind=0x01, text=b'some_text'):
1196
+ if str(type(text)).find("'str'") >= 0: # 6.4 test for back-compatibility
1197
+ data = bytes(text, encoding='ISO-8859-1')
1198
+ else:
1199
+ data = bytes(text)
1200
+ return b'\xFF'+bytes((which_kind,))+_ber_compressed_int(len(data))+data
1201
+
1202
+ def _consistentise_ticks(scores): # 3.6
1203
+ # used by mix_scores, merge_scores, concatenate_scores
1204
+ if len(scores) == 1:
1205
+ return copy.deepcopy(scores)
1206
+ are_consistent = True
1207
+ ticks = scores[0][0]
1208
+ iscore = 1
1209
+ while iscore < len(scores):
1210
+ if scores[iscore][0] != ticks:
1211
+ are_consistent = False
1212
+ break
1213
+ iscore += 1
1214
+ if are_consistent:
1215
+ return copy.deepcopy(scores)
1216
+ new_scores = []
1217
+ iscore = 0
1218
+ while iscore < len(scores):
1219
+ score = scores[iscore]
1220
+ new_scores.append(opus2score(to_millisecs(score2opus(score))))
1221
+ iscore += 1
1222
+ return new_scores
1223
+
1224
+
1225
+ ###########################################################################
1226
+
1227
+ def _decode(trackdata=b'', exclude=None, include=None,
1228
+ event_callback=None, exclusive_event_callback=None, no_eot_magic=False):
1229
+ r'''Decodes MIDI track data into an opus-style list of events.
1230
+ The options:
1231
+ 'exclude' is a list of event types which will be ignored SHOULD BE A SET
1232
+ 'include' (and no exclude), makes exclude a list
1233
+ of all possible events, /minus/ what include specifies
1234
+ 'event_callback' is a coderef
1235
+ 'exclusive_event_callback' is a coderef
1236
+ '''
1237
+ trackdata = bytearray(trackdata)
1238
+ if exclude == None:
1239
+ exclude = []
1240
+ if include == None:
1241
+ include = []
1242
+ if include and not exclude:
1243
+ exclude = All_events
1244
+ include = set(include)
1245
+ exclude = set(exclude)
1246
+
1247
+ # Pointer = 0; not used here; we eat through the bytearray instead.
1248
+ event_code = -1; # used for running status
1249
+ event_count = 0;
1250
+ events = []
1251
+
1252
+ while(len(trackdata)):
1253
+ # loop while there's anything to analyze ...
1254
+ eot = False # When True, the event registrar aborts this loop
1255
+ event_count += 1
1256
+
1257
+ E = []
1258
+ # E for events - we'll feed it to the event registrar at the end.
1259
+
1260
+ # Slice off the delta time code, and analyze it
1261
+ [time, remainder] = _unshift_ber_int(trackdata)
1262
+
1263
+ # Now let's see what we can make of the command
1264
+ first_byte = trackdata.pop(0) & 0xFF
1265
+
1266
+ if (first_byte < 0xF0): # It's a MIDI event
1267
+ if (first_byte & 0x80):
1268
+ event_code = first_byte
1269
+ else:
1270
+ # It wants running status; use last event_code value
1271
+ trackdata.insert(0, first_byte)
1272
+ if (event_code == -1):
1273
+ _warn("Running status not set; Aborting track.")
1274
+ return []
1275
+
1276
+ command = event_code & 0xF0
1277
+ channel = event_code & 0x0F
1278
+
1279
+ if (command == 0xF6): # 0-byte argument
1280
+ pass
1281
+ elif (command == 0xC0 or command == 0xD0): # 1-byte argument
1282
+ parameter = trackdata.pop(0) # could be B
1283
+ else: # 2-byte argument could be BB or 14-bit
1284
+ parameter = (trackdata.pop(0), trackdata.pop(0))
1285
+
1286
+ #################################################################
1287
+ # MIDI events
1288
+
1289
+ if (command == 0x80):
1290
+ if 'note_off' in exclude:
1291
+ continue
1292
+ E = ['note_off', time, channel, parameter[0], parameter[1]]
1293
+ elif (command == 0x90):
1294
+ if 'note_on' in exclude:
1295
+ continue
1296
+ E = ['note_on', time, channel, parameter[0], parameter[1]]
1297
+ elif (command == 0xA0):
1298
+ if 'key_after_touch' in exclude:
1299
+ continue
1300
+ E = ['key_after_touch',time,channel,parameter[0],parameter[1]]
1301
+ elif (command == 0xB0):
1302
+ if 'control_change' in exclude:
1303
+ continue
1304
+ E = ['control_change',time,channel,parameter[0],parameter[1]]
1305
+ elif (command == 0xC0):
1306
+ if 'patch_change' in exclude:
1307
+ continue
1308
+ E = ['patch_change', time, channel, parameter]
1309
+ elif (command == 0xD0):
1310
+ if 'channel_after_touch' in exclude:
1311
+ continue
1312
+ E = ['channel_after_touch', time, channel, parameter]
1313
+ elif (command == 0xE0):
1314
+ if 'pitch_wheel_change' in exclude:
1315
+ continue
1316
+ E = ['pitch_wheel_change', time, channel,
1317
+ _read_14_bit(parameter)-0x2000]
1318
+ else:
1319
+ _warn("Shouldn't get here; command="+hex(command))
1320
+
1321
+ elif (first_byte == 0xFF): # It's a Meta-Event! ##################
1322
+ #[command, length, remainder] =
1323
+ # unpack("xCwa*", substr(trackdata, $Pointer, 6));
1324
+ #Pointer += 6 - len(remainder);
1325
+ # # Move past JUST the length-encoded.
1326
+ command = trackdata.pop(0) & 0xFF
1327
+ [length, trackdata] = _unshift_ber_int(trackdata)
1328
+ if (command == 0x00):
1329
+ if (length == 2):
1330
+ E = ['set_sequence_number',time,_twobytes2int(trackdata)]
1331
+ else:
1332
+ _warn('set_sequence_number: length must be 2, not '+str(length))
1333
+ E = ['set_sequence_number', time, 0]
1334
+
1335
+ elif command >= 0x01 and command <= 0x0f: # Text events
1336
+ # 6.2 take it in bytes; let the user get the right encoding.
1337
+ # text_str = trackdata[0:length].decode('ascii','ignore')
1338
+ # text_str = trackdata[0:length].decode('ISO-8859-1')
1339
+ # 6.4 take it in bytes; let the user get the right encoding.
1340
+ text_data = bytes(trackdata[0:length]) # 6.4
1341
+ # Defined text events
1342
+ if (command == 0x01):
1343
+ E = ['text_event', time, text_data]
1344
+ elif (command == 0x02):
1345
+ E = ['copyright_text_event', time, text_data]
1346
+ elif (command == 0x03):
1347
+ E = ['track_name', time, text_data]
1348
+ elif (command == 0x04):
1349
+ E = ['instrument_name', time, text_data]
1350
+ elif (command == 0x05):
1351
+ E = ['lyric', time, text_data]
1352
+ elif (command == 0x06):
1353
+ E = ['marker', time, text_data]
1354
+ elif (command == 0x07):
1355
+ E = ['cue_point', time, text_data]
1356
+ # Reserved but apparently unassigned text events
1357
+ elif (command == 0x08):
1358
+ E = ['text_event_08', time, text_data]
1359
+ elif (command == 0x09):
1360
+ E = ['text_event_09', time, text_data]
1361
+ elif (command == 0x0a):
1362
+ E = ['text_event_0a', time, text_data]
1363
+ elif (command == 0x0b):
1364
+ E = ['text_event_0b', time, text_data]
1365
+ elif (command == 0x0c):
1366
+ E = ['text_event_0c', time, text_data]
1367
+ elif (command == 0x0d):
1368
+ E = ['text_event_0d', time, text_data]
1369
+ elif (command == 0x0e):
1370
+ E = ['text_event_0e', time, text_data]
1371
+ elif (command == 0x0f):
1372
+ E = ['text_event_0f', time, text_data]
1373
+
1374
+ # Now the sticky events -------------------------------------
1375
+ elif (command == 0x2F):
1376
+ E = ['end_track', time]
1377
+ # The code for handling this, oddly, comes LATER,
1378
+ # in the event registrar.
1379
+ elif (command == 0x51): # DTime, Microseconds/Crochet
1380
+ if length != 3:
1381
+ _warn('set_tempo event, but length='+str(length))
1382
+ E = ['set_tempo', time,
1383
+ struct.unpack(">I", b'\x00'+trackdata[0:3])[0]]
1384
+ elif (command == 0x54):
1385
+ if length != 5: # DTime, HR, MN, SE, FR, FF
1386
+ _warn('smpte_offset event, but length='+str(length))
1387
+ E = ['smpte_offset',time] + list(struct.unpack(">BBBBB",trackdata[0:5]))
1388
+ elif (command == 0x58):
1389
+ if length != 4: # DTime, NN, DD, CC, BB
1390
+ _warn('time_signature event, but length='+str(length))
1391
+ E = ['time_signature', time]+list(trackdata[0:4])
1392
+ elif (command == 0x59):
1393
+ if length != 2: # DTime, SF(signed), MI
1394
+ _warn('key_signature event, but length='+str(length))
1395
+ E = ['key_signature',time] + list(struct.unpack(">bB",trackdata[0:2]))
1396
+ elif (command == 0x7F): # 6.4
1397
+ E = ['sequencer_specific',time, bytes(trackdata[0:length])]
1398
+ else:
1399
+ E = ['raw_meta_event', time, command,
1400
+ bytes(trackdata[0:length])] # 6.0
1401
+ #"[uninterpretable meta-event command of length length]"
1402
+ # DTime, Command, Binary Data
1403
+ # It's uninterpretable; record it as raw_data.
1404
+
1405
+ # Pointer += length; # Now move Pointer
1406
+ trackdata = trackdata[length:]
1407
+
1408
+ ######################################################################
1409
+ elif (first_byte == 0xF0 or first_byte == 0xF7):
1410
+ # Note that sysexes in MIDI /files/ are different than sysexes
1411
+ # in MIDI transmissions!! The vast majority of system exclusive
1412
+ # messages will just use the F0 format. For instance, the
1413
+ # transmitted message F0 43 12 00 07 F7 would be stored in a
1414
+ # MIDI file as F0 05 43 12 00 07 F7. As mentioned above, it is
1415
+ # required to include the F7 at the end so that the reader of the
1416
+ # MIDI file knows that it has read the entire message. (But the F7
1417
+ # is omitted if this is a non-final block in a multiblock sysex;
1418
+ # but the F7 (if there) is counted in the message's declared
1419
+ # length, so we don't have to think about it anyway.)
1420
+ #command = trackdata.pop(0)
1421
+ [length, trackdata] = _unshift_ber_int(trackdata)
1422
+ if first_byte == 0xF0:
1423
+ # 20091008 added ISO-8859-1 to get an 8-bit str
1424
+ # 6.4 return bytes instead
1425
+ E = ['sysex_f0', time, bytes(trackdata[0:length])]
1426
+ else:
1427
+ E = ['sysex_f7', time, bytes(trackdata[0:length])]
1428
+ trackdata = trackdata[length:]
1429
+
1430
+ ######################################################################
1431
+ # Now, the MIDI file spec says:
1432
+ # <track data> = <MTrk event>+
1433
+ # <MTrk event> = <delta-time> <event>
1434
+ # <event> = <MIDI event> | <sysex event> | <meta-event>
1435
+ # I know that, on the wire, <MIDI event> can include note_on,
1436
+ # note_off, and all the other 8x to Ex events, AND Fx events
1437
+ # other than F0, F7, and FF -- namely, <song position msg>,
1438
+ # <song select msg>, and <tune request>.
1439
+ #
1440
+ # Whether these can occur in MIDI files is not clear specified
1441
+ # from the MIDI file spec. So, I'm going to assume that
1442
+ # they CAN, in practice, occur. I don't know whether it's
1443
+ # proper for you to actually emit these into a MIDI file.
1444
+
1445
+ elif (first_byte == 0xF2): # DTime, Beats
1446
+ # <song position msg> ::= F2 <data pair>
1447
+ E = ['song_position', time, _read_14_bit(trackdata[:2])]
1448
+ trackdata = trackdata[2:]
1449
+
1450
+ elif (first_byte == 0xF3): # <song select msg> ::= F3 <data singlet>
1451
+ # E = ['song_select', time, struct.unpack('>B',trackdata.pop(0))[0]]
1452
+ E = ['song_select', time, trackdata[0]]
1453
+ trackdata = trackdata[1:]
1454
+ # DTime, Thing (what?! song number? whatever ...)
1455
+
1456
+ elif (first_byte == 0xF6): # DTime
1457
+ E = ['tune_request', time]
1458
+ # What would a tune request be doing in a MIDI /file/?
1459
+
1460
+ #########################################################
1461
+ # ADD MORE META-EVENTS HERE. TODO:
1462
+ # f1 -- MTC Quarter Frame Message. One data byte follows
1463
+ # the Status; it's the time code value, from 0 to 127.
1464
+ # f8 -- MIDI clock. no data.
1465
+ # fa -- MIDI start. no data.
1466
+ # fb -- MIDI continue. no data.
1467
+ # fc -- MIDI stop. no data.
1468
+ # fe -- Active sense. no data.
1469
+ # f4 f5 f9 fd -- unallocated
1470
+
1471
+ r'''
1472
+ elif (first_byte > 0xF0) { # Some unknown kinda F-series event ####
1473
+ # Here we only produce a one-byte piece of raw data.
1474
+ # But the encoder for 'raw_data' accepts any length of it.
1475
+ E = [ 'raw_data',
1476
+ time, substr(trackdata,Pointer,1) ]
1477
+ # DTime and the Data (in this case, the one Event-byte)
1478
+ ++Pointer; # itself
1479
+
1480
+ '''
1481
+ elif first_byte > 0xF0: # Some unknown F-series event
1482
+ # Here we only produce a one-byte piece of raw data.
1483
+ # E = ['raw_data', time, bytest(trackdata[0])] # 6.4
1484
+ E = ['raw_data', time, trackdata[0]] # 6.4 6.7
1485
+ trackdata = trackdata[1:]
1486
+ else: # Fallthru.
1487
+ _warn("Aborting track. Command-byte first_byte="+hex(first_byte))
1488
+ break
1489
+ # End of the big if-group
1490
+
1491
+
1492
+ ######################################################################
1493
+ # THE EVENT REGISTRAR...
1494
+ if E and (E[0] == 'end_track'):
1495
+ # This is the code for exceptional handling of the EOT event.
1496
+ eot = True
1497
+ if not no_eot_magic:
1498
+ if E[1] > 0: # a null text-event to carry the delta-time
1499
+ E = ['text_event', E[1], '']
1500
+ else:
1501
+ E = [] # EOT with a delta-time of 0; ignore it.
1502
+
1503
+ if E and not (E[0] in exclude):
1504
+ #if ( $exclusive_event_callback ):
1505
+ # &{ $exclusive_event_callback }( @E );
1506
+ #else:
1507
+ # &{ $event_callback }( @E ) if $event_callback;
1508
+ events.append(E)
1509
+ if eot:
1510
+ break
1511
+
1512
+ # End of the big "Event" while-block
1513
+
1514
+ return events
1515
+
1516
+
1517
+ ###########################################################################
1518
+ def _encode(events_lol, unknown_callback=None, never_add_eot=False,
1519
+ no_eot_magic=False, no_running_status=False):
1520
+ # encode an event structure, presumably for writing to a file
1521
+ # Calling format:
1522
+ # $data_r = MIDI::Event::encode( \@event_lol, { options } );
1523
+ # Takes a REFERENCE to an event structure (a LoL)
1524
+ # Returns an (unblessed) REFERENCE to track data.
1525
+
1526
+ # If you want to use this to encode a /single/ event,
1527
+ # you still have to do it as a reference to an event structure (a LoL)
1528
+ # that just happens to have just one event. I.e.,
1529
+ # encode( [ $event ] ) or encode( [ [ 'note_on', 100, 5, 42, 64] ] )
1530
+ # If you're doing this, consider the never_add_eot track option, as in
1531
+ # print MIDI ${ encode( [ $event], { 'never_add_eot' => 1} ) };
1532
+
1533
+ data = [] # what I'll store the chunks of byte-data in
1534
+
1535
+ # This is so my end_track magic won't corrupt the original
1536
+ events = copy.deepcopy(events_lol)
1537
+
1538
+ if not never_add_eot:
1539
+ # One way or another, tack on an 'end_track'
1540
+ if events:
1541
+ last = events[-1]
1542
+ if not (last[0] == 'end_track'): # no end_track already
1543
+ if (last[0] == 'text_event' and len(last[2]) == 0):
1544
+ # 0-length text event at track-end.
1545
+ if no_eot_magic:
1546
+ # Exceptional case: don't mess with track-final
1547
+ # 0-length text_events; just peg on an end_track
1548
+ events.append(['end_track', 0])
1549
+ else:
1550
+ # NORMAL CASE: replace with an end_track, leaving DTime
1551
+ last[0] = 'end_track'
1552
+ else:
1553
+ # last event was neither 0-length text_event nor end_track
1554
+ events.append(['end_track', 0])
1555
+ else: # an eventless track!
1556
+ events = [['end_track', 0],]
1557
+
1558
+ # maybe_running_status = not no_running_status # unused? 4.7
1559
+ last_status = -1
1560
+
1561
+ for event_r in (events):
1562
+ E = copy.deepcopy(event_r)
1563
+ # otherwise the shifting'd corrupt the original
1564
+ if not E:
1565
+ continue
1566
+
1567
+ event = E.pop(0)
1568
+ if not len(event):
1569
+ continue
1570
+
1571
+ dtime = int(E.pop(0))
1572
+ # print('event='+str(event)+' dtime='+str(dtime))
1573
+
1574
+ event_data = ''
1575
+
1576
+ if ( # MIDI events -- eligible for running status
1577
+ event == 'note_on'
1578
+ or event == 'note_off'
1579
+ or event == 'control_change'
1580
+ or event == 'key_after_touch'
1581
+ or event == 'patch_change'
1582
+ or event == 'channel_after_touch'
1583
+ or event == 'pitch_wheel_change' ):
1584
+
1585
+ # This block is where we spend most of the time. Gotta be tight.
1586
+ if (event == 'note_off'):
1587
+ status = 0x80 | (int(E[0]) & 0x0F)
1588
+ parameters = struct.pack('>BB', int(E[1])&0x7F, int(E[2])&0x7F)
1589
+ elif (event == 'note_on'):
1590
+ status = 0x90 | (int(E[0]) & 0x0F)
1591
+ parameters = struct.pack('>BB', int(E[1])&0x7F, int(E[2])&0x7F)
1592
+ elif (event == 'key_after_touch'):
1593
+ status = 0xA0 | (int(E[0]) & 0x0F)
1594
+ parameters = struct.pack('>BB', int(E[1])&0x7F, int(E[2])&0x7F)
1595
+ elif (event == 'control_change'):
1596
+ status = 0xB0 | (int(E[0]) & 0x0F)
1597
+ parameters = struct.pack('>BB', int(E[1])&0xFF, int(E[2])&0xFF)
1598
+ elif (event == 'patch_change'):
1599
+ status = 0xC0 | (int(E[0]) & 0x0F)
1600
+ parameters = struct.pack('>B', int(E[1]) & 0xFF)
1601
+ elif (event == 'channel_after_touch'):
1602
+ status = 0xD0 | (int(E[0]) & 0x0F)
1603
+ parameters = struct.pack('>B', int(E[1]) & 0xFF)
1604
+ elif (event == 'pitch_wheel_change'):
1605
+ status = 0xE0 | (int(E[0]) & 0x0F)
1606
+ parameters = _write_14_bit(int(E[1]) + 0x2000)
1607
+ else:
1608
+ _warn("BADASS FREAKOUT ERROR 31415!")
1609
+
1610
+ # And now the encoding
1611
+ # w = BER compressed integer (not ASN.1 BER, see perlpacktut for
1612
+ # details). Its bytes represent an unsigned integer in base 128,
1613
+ # most significant digit first, with as few digits as possible.
1614
+ # Bit eight (the high bit) is set on each byte except the last.
1615
+
1616
+ data.append(_ber_compressed_int(dtime))
1617
+ if (status != last_status) or no_running_status:
1618
+ data.append(struct.pack('>B', status))
1619
+ data.append(parameters)
1620
+
1621
+ last_status = status
1622
+ continue
1623
+ else:
1624
+ # Not a MIDI event.
1625
+ # All the code in this block could be more efficient,
1626
+ # but this is not where the code needs to be tight.
1627
+ # print "zaz $event\n";
1628
+ last_status = -1
1629
+
1630
+ if event == 'raw_meta_event':
1631
+ event_data = _some_text_event(int(E[0]), E[1])
1632
+ elif (event == 'set_sequence_number'): # 3.9
1633
+ event_data = b'\xFF\x00\x02'+_int2twobytes(E[0])
1634
+
1635
+ # Text meta-events...
1636
+ # a case for a dict, I think (pjb) ...
1637
+ elif (event == 'text_event'):
1638
+ event_data = _some_text_event(0x01, E[0])
1639
+ elif (event == 'copyright_text_event'):
1640
+ event_data = _some_text_event(0x02, E[0])
1641
+ elif (event == 'track_name'):
1642
+ event_data = _some_text_event(0x03, E[0])
1643
+ elif (event == 'instrument_name'):
1644
+ event_data = _some_text_event(0x04, E[0])
1645
+ elif (event == 'lyric'):
1646
+ event_data = _some_text_event(0x05, E[0])
1647
+ elif (event == 'marker'):
1648
+ event_data = _some_text_event(0x06, E[0])
1649
+ elif (event == 'cue_point'):
1650
+ event_data = _some_text_event(0x07, E[0])
1651
+ elif (event == 'text_event_08'):
1652
+ event_data = _some_text_event(0x08, E[0])
1653
+ elif (event == 'text_event_09'):
1654
+ event_data = _some_text_event(0x09, E[0])
1655
+ elif (event == 'text_event_0a'):
1656
+ event_data = _some_text_event(0x0A, E[0])
1657
+ elif (event == 'text_event_0b'):
1658
+ event_data = _some_text_event(0x0B, E[0])
1659
+ elif (event == 'text_event_0c'):
1660
+ event_data = _some_text_event(0x0C, E[0])
1661
+ elif (event == 'text_event_0d'):
1662
+ event_data = _some_text_event(0x0D, E[0])
1663
+ elif (event == 'text_event_0e'):
1664
+ event_data = _some_text_event(0x0E, E[0])
1665
+ elif (event == 'text_event_0f'):
1666
+ event_data = _some_text_event(0x0F, E[0])
1667
+ # End of text meta-events
1668
+
1669
+ elif (event == 'end_track'):
1670
+ event_data = b"\xFF\x2F\x00"
1671
+
1672
+ elif (event == 'set_tempo'):
1673
+ #event_data = struct.pack(">BBwa*", 0xFF, 0x51, 3,
1674
+ # substr( struct.pack('>I', E[0]), 1, 3))
1675
+ event_data = b'\xFF\x51\x03'+struct.pack('>I',E[0])[1:]
1676
+ elif (event == 'smpte_offset'):
1677
+ # event_data = struct.pack(">BBwBBBBB", 0xFF, 0x54, 5, E[0:5] )
1678
+ event_data = struct.pack(">BBBbBBBB", 0xFF,0x54,0x05,E[0],E[1],E[2],E[3],E[4])
1679
+ elif (event == 'time_signature'):
1680
+ # event_data = struct.pack(">BBwBBBB", 0xFF, 0x58, 4, E[0:4] )
1681
+ event_data = struct.pack(">BBBbBBB", 0xFF, 0x58, 0x04, E[0],E[1],E[2],E[3])
1682
+ elif (event == 'key_signature'):
1683
+ event_data = struct.pack(">BBBbB", 0xFF, 0x59, 0x02, E[0],E[1])
1684
+ elif (event == 'sequencer_specific'):
1685
+ # event_data = struct.pack(">BBwa*", 0xFF,0x7F, len(E[0]), E[0])
1686
+ event_data = _some_text_event(0x7F, E[0])
1687
+ # End of Meta-events
1688
+
1689
+ # Other Things...
1690
+ elif (event == 'sysex_f0'):
1691
+ #event_data = struct.pack(">Bwa*", 0xF0, len(E[0]), E[0])
1692
+ #B=bitstring w=BER-compressed-integer a=null-padded-ascii-str
1693
+ event_data = bytearray(b'\xF0')+_ber_compressed_int(len(E[0]))+bytearray(E[0])
1694
+ elif (event == 'sysex_f7'):
1695
+ #event_data = struct.pack(">Bwa*", 0xF7, len(E[0]), E[0])
1696
+ event_data = bytearray(b'\xF7')+_ber_compressed_int(len(E[0]))+bytearray(E[0])
1697
+
1698
+ elif (event == 'song_position'):
1699
+ event_data = b"\xF2" + _write_14_bit( E[0] )
1700
+ elif (event == 'song_select'):
1701
+ event_data = struct.pack('>BB', 0xF3, E[0] )
1702
+ elif (event == 'tune_request'):
1703
+ event_data = b"\xF6"
1704
+ elif (event == 'raw_data'):
1705
+ _warn("_encode: raw_data event not supported")
1706
+ # event_data = E[0]
1707
+ continue
1708
+ # End of Other Stuff
1709
+
1710
+ else:
1711
+ # The Big Fallthru
1712
+ if unknown_callback:
1713
+ # push(@data, &{ $unknown_callback }( @$event_r ))
1714
+ pass
1715
+ else:
1716
+ _warn("Unknown event: "+str(event))
1717
+ # To surpress complaint here, just set
1718
+ # 'unknown_callback' => sub { return () }
1719
+ continue
1720
+
1721
+ #print "Event $event encoded part 2\n"
1722
+ if str(type(event_data)).find("'str'") >= 0:
1723
+ event_data = bytearray(event_data.encode('Latin1', 'ignore'))
1724
+ if len(event_data): # how could $event_data be empty
1725
+ # data.append(struct.pack('>wa*', dtime, event_data))
1726
+ # print(' event_data='+str(event_data))
1727
+ data.append(_ber_compressed_int(dtime)+event_data)
1728
+
1729
+ return b''.join(data)
1730
+
los_angeles_midi_dataset_metadata_maker.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Los_Angeles_MIDI_Dataset_Metadata_Maker.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1YgHU5oqIdvDcx6QnZzZKkolhia27zGo8
8
+
9
+ # Los Angeles MIDI Dataset Metadata Maker (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 tqdm
30
+
31
+ #@title Import all needed modules
32
+
33
+ print('Loading needed modules. Please wait...')
34
+ import os
35
+
36
+ import math
37
+ import statistics
38
+ import random
39
+ from collections import Counter
40
+
41
+ from tqdm import tqdm
42
+
43
+ if not os.path.exists('/content/Dataset'):
44
+ os.makedirs('/content/Dataset')
45
+
46
+ print('Loading TMIDIX module...')
47
+ os.chdir('/content/tegridy-tools/tegridy-tools')
48
+
49
+ import TMIDIX
50
+
51
+ print('Done!')
52
+
53
+ os.chdir('/content/')
54
+ print('Enjoy! :)')
55
+
56
+ """# (DOWNLOAD SOURCE MIDI DATASET)"""
57
+
58
+ # Commented out IPython magic to ensure Python compatibility.
59
+ #@title Download original LAKH MIDI Dataset
60
+
61
+ # %cd /content/Dataset/
62
+
63
+ !wget 'http://hog.ee.columbia.edu/craffel/lmd/lmd_full.tar.gz'
64
+ !tar -xvf 'lmd_full.tar.gz'
65
+ !rm 'lmd_full.tar.gz'
66
+
67
+ # %cd /content/
68
+
69
+ #@title Mount Google Drive
70
+ from google.colab import drive
71
+ drive.mount('/content/drive')
72
+
73
+ """# (FILE LIST)"""
74
+
75
+ #@title Save file list
76
+ ###########
77
+
78
+ print('Loading MIDI files...')
79
+ print('This may take a while on a large dataset in particular.')
80
+
81
+ dataset_addr = "/content/Dataset"
82
+ # os.chdir(dataset_addr)
83
+ filez = list()
84
+ for (dirpath, dirnames, filenames) in os.walk(dataset_addr):
85
+ filez += [os.path.join(dirpath, file) for file in filenames]
86
+ print('=' * 70)
87
+
88
+ if filez == []:
89
+ print('Could not find any MIDI files. Please check Dataset dir...')
90
+ print('=' * 70)
91
+
92
+ print('Randomizing file list...')
93
+ random.shuffle(filez)
94
+
95
+ TMIDIX.Tegridy_Any_Pickle_File_Writer(filez, '/content/drive/MyDrive/filez')
96
+
97
+ #@title Load file list
98
+ filez = TMIDIX.Tegridy_Any_Pickle_File_Reader('/content/drive/MyDrive/filez')
99
+ print('Done!')
100
+
101
+ """# (PROCESS)"""
102
+
103
+ #@title Process MIDIs with TMIDIX MIDI processor
104
+
105
+ print('=' * 70)
106
+ print('TMIDIX MIDI Processor')
107
+ print('=' * 70)
108
+ print('Starting up...')
109
+ print('=' * 70)
110
+
111
+ ###########
112
+
113
+ START_FILE_NUMBER = 0
114
+ LAST_SAVED_BATCH_COUNT = 0
115
+
116
+ input_files_count = START_FILE_NUMBER
117
+ files_count = LAST_SAVED_BATCH_COUNT
118
+
119
+ melody_chords_f = []
120
+
121
+ stats = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
122
+
123
+ print('Processing MIDI files. Please wait...')
124
+ print('=' * 70)
125
+
126
+ for f in tqdm(filez[START_FILE_NUMBER:]):
127
+ try:
128
+ input_files_count += 1
129
+
130
+ fn = os.path.basename(f)
131
+ fn1 = fn.split('.mid')[0]
132
+
133
+ #=======================================================
134
+ # START PROCESSING
135
+
136
+ opus = TMIDIX.midi2opus(open(f, 'rb').read())
137
+
138
+ opus_events_matrix = []
139
+
140
+ itrack0 = 1
141
+
142
+ while itrack0 < len(opus):
143
+ for event in opus[itrack0]:
144
+ opus_events_matrix.append(event)
145
+ itrack0 += 1
146
+
147
+ #=======================================================
148
+
149
+ ms_score = TMIDIX.opus2score(TMIDIX.to_millisecs(opus))
150
+
151
+ ms_events_matrix = []
152
+
153
+ itrack1 = 1
154
+
155
+ while itrack1 < len(ms_score):
156
+ for event in ms_score[itrack1]:
157
+ if event[0] == 'note':
158
+ ms_events_matrix.append(event)
159
+ itrack1 += 1
160
+
161
+ ms_events_matrix.sort(key=lambda x: x[1])
162
+
163
+ #=======================================================
164
+
165
+ # Convering MIDI to score with MIDI.py module
166
+ score = TMIDIX.opus2score(opus)
167
+
168
+ events_matrix = []
169
+ full_events_matrix = []
170
+
171
+ itrack = 1
172
+ patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
173
+
174
+ while itrack < len(score):
175
+ for event in score[itrack]:
176
+ if event[0] == 'note' or event[0] == 'patch_change':
177
+ events_matrix.append(event)
178
+ full_events_matrix.append(event)
179
+ itrack += 1
180
+
181
+ full_events_matrix.sort(key=lambda x: x[1])
182
+ events_matrix.sort(key=lambda x: x[1])
183
+
184
+ events_matrix1 = []
185
+
186
+ for event in events_matrix:
187
+ if event[0] == 'patch_change':
188
+ patches[event[2]] = event[3]
189
+
190
+ if event[0] == 'note':
191
+ event.extend([patches[event[3]]])
192
+ events_matrix1.append(event)
193
+
194
+ if len(events_matrix1) > 0:
195
+
196
+ events_matrix1.sort(key=lambda x: x[1])
197
+
198
+ for e in events_matrix1:
199
+ if e[0] == 'note':
200
+ if e[3] == 9:
201
+ e[4] = ((abs(e[4]) % 128) + 128)
202
+ else:
203
+ e[4] = (abs(e[4]) % 128)
204
+
205
+ pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix1]).most_common()]
206
+ pitches_counts.sort(key=lambda x: x[0], reverse=True)
207
+
208
+ patches_counts = [[y[0],y[1]] for y in Counter([y[6] for y in events_matrix1]).most_common()]
209
+ patches_counts.sort(key=lambda x: x[1], reverse=True)
210
+
211
+ pitches_patches = sorted([[y[4], y[6]] for y in events_matrix1], reverse=True)
212
+ pitches_patches_counts = [[[y[0][0], y[0][1]], y[1]] for y in Counter([tuple(x) for x in pitches_patches]).most_common()]
213
+
214
+ midi_patches = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))
215
+ if len(midi_patches) == 0:
216
+ midi_patches = [None]
217
+
218
+ times = []
219
+ pt = ms_events_matrix[0][1]
220
+ start = True
221
+ for e in ms_events_matrix:
222
+ if (e[1]-pt) != 0 or start == True:
223
+ times.append((e[1]-pt))
224
+ start = False
225
+ pt = e[1]
226
+
227
+ times_sum = sum(times)
228
+
229
+ durs = [e[2] for e in ms_events_matrix]
230
+ vels = [e[5] for e in ms_events_matrix]
231
+
232
+ avg_time = int(sum(times) / len(times))
233
+ avg_dur = int(sum(durs) / len(durs))
234
+ avg_vel = int(sum(vels) / len(vels))
235
+
236
+ mode_time = statistics.mode(times)
237
+ mode_dur = statistics.mode(durs)
238
+ mode_vel = statistics.mode(vels)
239
+
240
+ median_time = int(statistics.median(times))
241
+ median_dur = int(statistics.median(durs))
242
+ median_vel = int(statistics.median(vels))
243
+
244
+ text_events_list = ['text_event',
245
+ 'text_event_08',
246
+ 'text_event_09',
247
+ 'text_event_0a',
248
+ 'text_event_0b',
249
+ 'text_event_0c',
250
+ 'text_event_0d',
251
+ 'text_event_0e',
252
+ 'text_event_0f']
253
+
254
+ text_events_count = len([e for e in full_events_matrix if e[0] in text_events_list])
255
+ lyric_events_count = len([e for e in full_events_matrix if e[0] == 'lyric'])
256
+
257
+ chords = []
258
+ pe = ms_events_matrix[0]
259
+ cho = []
260
+ for e in ms_events_matrix:
261
+ if (e[1] - pe[1]) == 0:
262
+ if e[3] != 9:
263
+ if (e[4] % 12) not in cho:
264
+ cho.append(e[4] % 12)
265
+ else:
266
+ if len(cho) > 0:
267
+ chords.append(sorted(cho))
268
+ cho = []
269
+ if e[3] != 9:
270
+ if (e[4] % 12) not in cho:
271
+ cho.append(e[4] % 12)
272
+
273
+ pe = e
274
+
275
+ if len(cho) > 0:
276
+ chords.append(sorted(cho))
277
+
278
+ 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])
279
+
280
+ tempo_change_count = len([f for f in full_events_matrix if f[0] == 'set_tempo'])
281
+
282
+ sixty_forth_note = [e for e in events_matrix1][64]
283
+ sixty_forth_note_idx = full_events_matrix.index(sixty_forth_note)
284
+
285
+ data = []
286
+ data.append(['total_number_of_tracks', itrack])
287
+ data.append(['total_number_of_opus_midi_events', len(opus_events_matrix)])
288
+ data.append(['total_number_of_score_midi_events', len(full_events_matrix)])
289
+ data.append(['average_median_mode_time_ms', [avg_time, median_time, mode_time]])
290
+ data.append(['average_median_mode_dur_ms', [avg_dur, median_dur, mode_dur]])
291
+ data.append(['average_median_mode_vel', [avg_vel, median_vel, mode_vel]])
292
+ data.append(['total_number_of_chords', len(set([y[1] for y in events_matrix1]))])
293
+ data.append(['total_number_of_chords_ms', len(times)])
294
+ data.append(['ms_chords_counts', ms_chords_counts])
295
+ data.append(['pitches_times_sum_ms', times_sum])
296
+ data.append(['total_pitches_counts', pitches_counts])
297
+ data.append(['total_patches_counts', patches_counts])
298
+ data.append(['midi_patches', midi_patches])
299
+ data.append(['total_pitches_patches_counts', pitches_patches_counts])
300
+ data.append(['tempo_change_count', tempo_change_count])
301
+ data.append(['text_events_count', text_events_count])
302
+ data.append(['lyric_events_count', lyric_events_count])
303
+ data.append(['midi_ticks', score[0]])
304
+ data.extend(full_events_matrix[:sixty_forth_note_idx])
305
+ data.append(full_events_matrix[-1])
306
+
307
+ melody_chords_f.append([fn1, data])
308
+
309
+ #=======================================================
310
+
311
+ # Processed files counter
312
+ files_count += 1
313
+
314
+ # Saving every 5000 processed files
315
+ if files_count % 10000 == 0:
316
+ print('SAVING !!!')
317
+ print('=' * 70)
318
+ print('Saving processed files...')
319
+ print('=' * 70)
320
+ print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')
321
+ print('=' * 70)
322
+ count = str(files_count)
323
+ TMIDIX.Tegridy_Any_Pickle_File_Writer(melody_chords_f, '/content/drive/MyDrive/LAMD_META_'+count)
324
+ melody_chords_f = []
325
+ print('=' * 70)
326
+
327
+ except KeyboardInterrupt:
328
+ print('Saving current progress and quitting...')
329
+ break
330
+
331
+ except Exception as ex:
332
+ print('WARNING !!!')
333
+ print('=' * 70)
334
+ print('Bad MIDI:', f)
335
+ print('Error detected:', ex)
336
+ print('=' * 70)
337
+ continue
338
+
339
+ # Saving last processed files...
340
+ print('=' * 70)
341
+ print('Saving processed files...')
342
+ print('=' * 70)
343
+ print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')
344
+ print('=' * 70)
345
+ count = str(files_count)
346
+ TMIDIX.Tegridy_Any_Pickle_File_Writer(melody_chords_f, '/content/drive/MyDrive/LAMD_META_'+count)
347
+
348
+ # Displaying resulting processing stats...
349
+ print('=' * 70)
350
+ print('Done!')
351
+ print('=' * 70)
352
+
353
+ print('Resulting Stats:')
354
+ print('=' * 70)
355
+ print('Total good processed MIDI files:', files_count)
356
+ print('=' * 70)
357
+
358
+ """# Congrats! You did it! :)"""
los_angeles_midi_dataset_search_and_explore.py CHANGED
@@ -42,6 +42,7 @@ import random
42
  import pickle
43
  from tqdm import tqdm
44
  import pprint
 
45
 
46
  from joblib import Parallel, delayed
47
  import multiprocessing
@@ -561,6 +562,27 @@ if len(cho) > 0:
561
 
562
  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])
563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564
  #==================================================
565
 
566
  print('=' * 70)
@@ -898,10 +920,24 @@ print('=' * 70)
898
 
899
  #@markdown NOTE: You can stop the search at any time to render partial results
900
 
 
 
901
  maximum_match_ratio_to_search_for = 1 #@param {type:"slider", min:0, max:1, step:0.01}
 
 
 
902
  pitches_counts_cutoff_threshold_ratio = 0 #@param {type:"slider", min:0, max:1, step:0.05}
903
  search_transposed_pitches = False #@param {type:"boolean"}
904
  skip_exact_matches = False #@param {type:"boolean"}
 
 
 
 
 
 
 
 
 
905
  render_MIDI_to_audio = False #@param {type:"boolean"}
906
  download_MIDI = False #@param {type:"boolean"}
907
 
@@ -909,7 +945,7 @@ print('=' * 70)
909
  print('MIDI Pitches Search')
910
  print('=' * 70)
911
 
912
- ratios = []
913
 
914
  for d in tqdm(meta_data):
915
 
@@ -917,34 +953,145 @@ for d in tqdm(meta_data):
917
  p_counts = d[1][10][1]
918
  p_counts.sort(reverse = True, key = lambda x: x[1])
919
  max_p_count = p_counts[0][1]
920
- trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)]
 
921
 
922
  if search_transposed_pitches:
923
  search_pitches = mult_pitches_counts
924
  else:
925
  search_pitches = [mult_pitches_counts[6]]
926
-
927
- rat = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
928
 
929
  for m in search_pitches:
930
 
 
 
931
  m.sort(reverse = True, key = lambda x: x[1])
932
  max_pitches_count = m[0][1]
933
- trimmed_pitches_counts = [y for y in m if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)]
 
934
 
935
- num_same_pitches = len(set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts]))
 
936
  same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in trimmed_p_counts]+[T[0] for T in trimmed_pitches_counts])))
937
 
938
  if skip_exact_matches:
939
  if same_pitches_ratio == 1:
940
  same_pitches_ratio = 0
941
 
942
- if same_pitches_ratio > maximum_match_ratio_to_search_for:
943
- same_pitches_ratio = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944
 
945
- rat.append(same_pitches_ratio)
946
 
947
- ratios.append(max(rat))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
948
 
949
  except KeyboardInterrupt:
950
  break
@@ -957,8 +1104,8 @@ for d in tqdm(meta_data):
957
  print('=' * 70)
958
  break
959
 
960
- max_ratio = max(ratios)
961
- max_ratio_index = ratios.index(max(ratios))
962
 
963
  print('FOUND')
964
  print('=' * 70)
 
42
  import pickle
43
  from tqdm import tqdm
44
  import pprint
45
+ import statistics
46
 
47
  from joblib import Parallel, delayed
48
  import multiprocessing
 
562
 
563
  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])
564
 
565
+ times = []
566
+ pt = ms_events_matrix[0][1]
567
+ start = True
568
+ for e in ms_events_matrix:
569
+ if (e[1]-pt) != 0 or start == True:
570
+ times.append((e[1]-pt))
571
+ start = False
572
+ pt = e[1]
573
+
574
+ durs = [e[2] for e in ms_events_matrix]
575
+ vels = [e[5] for e in ms_events_matrix]
576
+
577
+ avg_time = int(sum(times) / len(times))
578
+ avg_dur = int(sum(durs) / len(durs))
579
+
580
+ mode_time = statistics.mode(times)
581
+ mode_dur = statistics.mode(durs)
582
+
583
+ median_time = int(statistics.median(times))
584
+ median_dur = int(statistics.median(durs))
585
+
586
  #==================================================
587
 
588
  print('=' * 70)
 
920
 
921
  #@markdown NOTE: You can stop the search at any time to render partial results
922
 
923
+ #@markdown Match ratio control option
924
+
925
  maximum_match_ratio_to_search_for = 1 #@param {type:"slider", min:0, max:1, step:0.01}
926
+
927
+ #@markdown MIDI pitches search options
928
+
929
  pitches_counts_cutoff_threshold_ratio = 0 #@param {type:"slider", min:0, max:1, step:0.05}
930
  search_transposed_pitches = False #@param {type:"boolean"}
931
  skip_exact_matches = False #@param {type:"boolean"}
932
+
933
+ #@markdown Additional search options
934
+
935
+ add_pitches_counts_ratios = False #@param {type:"boolean"}
936
+ add_timings_ratios = False #@param {type:"boolean"}
937
+ add_durations_ratios = False #@param {type:"boolean"}
938
+
939
+ #@markdown Other options
940
+
941
  render_MIDI_to_audio = False #@param {type:"boolean"}
942
  download_MIDI = False #@param {type:"boolean"}
943
 
 
945
  print('MIDI Pitches Search')
946
  print('=' * 70)
947
 
948
+ final_ratios = []
949
 
950
  for d in tqdm(meta_data):
951
 
 
953
  p_counts = d[1][10][1]
954
  p_counts.sort(reverse = True, key = lambda x: x[1])
955
  max_p_count = p_counts[0][1]
956
+ trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)]
957
+ total_p_counts = sum([y[1] for y in trimmed_p_counts])
958
 
959
  if search_transposed_pitches:
960
  search_pitches = mult_pitches_counts
961
  else:
962
  search_pitches = [mult_pitches_counts[6]]
963
+
964
+ #===================================================
965
+
966
+ ratios_list = []
967
+
968
+ #===================================================
969
+
970
+ atrat = [0]
971
+
972
+ if add_timings_ratios:
973
+
974
+ source_times = [avg_time,
975
+ median_time,
976
+ mode_time]
977
+
978
+ match_times = meta_data[0][1][3][1]
979
+
980
+ times_ratios = []
981
+
982
+ for i in range(len(source_times)):
983
+ maxtratio = max(source_times[i], match_times[i])
984
+ mintratio = min(source_times[i], match_times[i])
985
+ times_ratios.append(mintratio / maxtratio)
986
+
987
+ avg_times_ratio = sum(times_ratios) / len(times_ratios)
988
+
989
+ atrat[0] = avg_times_ratio
990
+
991
+ #===================================================
992
+
993
+ adrat = [0]
994
+
995
+ if add_durations_ratios:
996
+
997
+ source_durs = [avg_dur,
998
+ median_dur,
999
+ mode_dur]
1000
+
1001
+ match_durs = meta_data[0][1][4][1]
1002
+
1003
+ durs_ratios = []
1004
+
1005
+ for i in range(len(source_durs)):
1006
+ maxtratio = max(source_durs[i], match_durs[i])
1007
+ mintratio = min(source_durs[i], match_durs[i])
1008
+ durs_ratios.append(mintratio / maxtratio)
1009
+
1010
+ avg_durs_ratio = sum(durs_ratios) / len(durs_ratios)
1011
+
1012
+ adrat[0] = avg_durs_ratio
1013
+
1014
+ #===================================================
1015
 
1016
  for m in search_pitches:
1017
 
1018
+ sprat = []
1019
+
1020
  m.sort(reverse = True, key = lambda x: x[1])
1021
  max_pitches_count = m[0][1]
1022
+ trimmed_pitches_counts = [y for y in m if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)]
1023
+ total_pitches_counts = sum([y[1] for y in trimmed_pitches_counts])
1024
 
1025
+ same_pitches = set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts])
1026
+ num_same_pitches = len(same_pitches)
1027
  same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in trimmed_p_counts]+[T[0] for T in trimmed_pitches_counts])))
1028
 
1029
  if skip_exact_matches:
1030
  if same_pitches_ratio == 1:
1031
  same_pitches_ratio = 0
1032
 
1033
+ sprat.append(same_pitches_ratio)
1034
+
1035
+ #===================================================
1036
+
1037
+ spcrat = [0]
1038
+
1039
+ if add_pitches_counts_ratios:
1040
+
1041
+ same_trimmed_p_counts = sorted([T for T in trimmed_p_counts if T[0] in same_pitches], reverse = True)
1042
+ same_trimmed_pitches_counts = sorted([T for T in trimmed_pitches_counts if T[0] in same_pitches], reverse = True)
1043
+
1044
+ same_trimmed_p_counts_ratios = [[s[0], s[1] / total_p_counts] for s in same_trimmed_p_counts]
1045
+ same_trimmed_pitches_counts_ratios = [[s[0], s[1] / total_pitches_counts] for s in same_trimmed_pitches_counts]
1046
+
1047
+ same_pitches_counts_ratios = []
1048
+
1049
+ for i in range(len(same_trimmed_p_counts_ratios)):
1050
+ mincratio = min(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])
1051
+ maxcratio = max(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])
1052
+ same_pitches_counts_ratios.append([same_trimmed_p_counts_ratios[i][0], mincratio / maxcratio])
1053
+
1054
+ same_counts_ratios = [s[1] for s in same_pitches_counts_ratios]
1055
+
1056
+ if len(same_counts_ratios) > 0:
1057
+ avg_same_pitches_counts_ratio = sum(same_counts_ratios) / len(same_counts_ratios)
1058
+ else:
1059
+ avg_same_pitches_counts_ratio = 0
1060
 
1061
+ spcrat[0] = avg_same_pitches_counts_ratio
1062
 
1063
+ #===================================================
1064
+
1065
+ r_list = [sprat[0]]
1066
+
1067
+ if add_pitches_counts_ratios:
1068
+ r_list.append(spcrat[0])
1069
+
1070
+ if add_timings_ratios:
1071
+ r_list.append(atrat[0])
1072
+
1073
+ if add_durations_ratios:
1074
+ r_list.append(adrat[0])
1075
+
1076
+ ratios_list.append(r_list)
1077
+
1078
+ #===================================================
1079
+
1080
+ avg_ratios_list = []
1081
+
1082
+ for r in ratios_list:
1083
+ avg_ratios_list.append(sum(r) / len(r))
1084
+
1085
+ #===================================================
1086
+
1087
+ final_ratio = max(avg_ratios_list)
1088
+
1089
+ if final_ratio > maximum_match_ratio_to_search_for:
1090
+ final_ratio = 0
1091
+
1092
+ final_ratios.append(final_ratio)
1093
+
1094
+ #===================================================
1095
 
1096
  except KeyboardInterrupt:
1097
  break
 
1104
  print('=' * 70)
1105
  break
1106
 
1107
+ max_ratio = max(final_ratios)
1108
+ max_ratio_index = final_ratios.index(max_ratio)
1109
 
1110
  print('FOUND')
1111
  print('=' * 70)