-
Notifications
You must be signed in to change notification settings - Fork 3
/
deep_music_genre.py
2018 lines (1651 loc) · 75.2 KB
/
deep_music_genre.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## **Imports**
import os
import math
import time
import pickle
import shutil
import music21
import numpy as np
from enum import Enum
import matplotlib.pyplot as plt
from typing import *
from fastai.callbacks import EarlyStoppingCallback, SaveModelCallback, ReduceLROnPlateauCallback
## **Utils**
### **Declaration of Helper Variables**
PIANO_TYPES = list(range(24)) + list(range(80, 96)) # Piano, Synths
PLUCK_TYPES = list(range(24, 40)) + list(range(104, 112)) # Guitar, Bass, Ethnic
BRIGHT_TYPES = list(range(40, 56)) + list(range(56, 80))
PIANO_RANGE = (21, 109) # https://en.wikipedia.org/wiki/Scientific_pitch_notation
#@title
#Using enums in python
class Track(Enum):
PIANO = 0 # discrete instruments - keyboard, woodwinds
PLUCK = 1 # continuous instruments with pitch bend: violin, trombone, synths
BRIGHT = 2
PERC = 3
UNDEF = 4
ype2inst = {
# use print_music21_instruments() to see supported types
Track.PIANO: 0, # Piano
Track.PLUCK: 24, # Guitar
Track.BRIGHT: 40, # Violin
Track.PERC: 114, # Steel Drum
}
# INFO_TYPES = set(['TIME_SIGNATURE', 'KEY_SIGNATURE'])
INFO_TYPES = set(['TIME_SIGNATURE', 'KEY_SIGNATURE', 'SET_TEMPO'])
#@title
def file2mf(fp):
mf = music21.midi.MidiFile()
if isinstance(fp, bytes):
mf.readstr(fp)
else:
mf.open(fp)
mf.read()
mf.close()
return mf
def mf2stream(mf): return music21.midi.translate.midiFileToStream(mf)
def is_empty_midi(fp):
if fp is None: return False
mf = file2mf(fp)
return not any([t.hasNotes() for t in mf.tracks])
def num_piano_tracks(fp):
music_file = file2mf(fp)
note_tracks = [t for t in music_file.tracks if t.hasNotes() and get_track_type(t) == Track.PIANO]
return len(note_tracks)
def is_channel(t, c_val):
return any([c == c_val for c in t.getChannels()])
def track_sort(t): # sort by 1. variation of pitch, 2. number of notes
return len(unique_track_notes(t)), len(t.events)
def is_piano_note(pitch):
return (pitch >= PIANO_RANGE[0]) and (pitch < PIANO_RANGE[1])
def unique_track_notes(t):
return { e.pitch for e in t.events if e.pitch is not None }
def compress_midi_file(fp, cutoff=6, min_variation=3, supported_types=set([Track.PIANO, Track.PLUCK, Track.BRIGHT])):
music_file = file2mf(fp)
info_tracks = [t for t in music_file.tracks if not t.hasNotes()]
note_tracks = [t for t in music_file.tracks if t.hasNotes()]
if len(note_tracks) > cutoff:
note_tracks = sorted(note_tracks, key=track_sort, reverse=True)
supported_tracks = []
for idx,t in enumerate(note_tracks):
if len(supported_tracks) >= cutoff: break
track_type = get_track_type(t)
if track_type not in supported_types: continue
pitch_set = unique_track_notes(t)
if (len(pitch_set) < min_variation): continue # must have more than x unique notes
if not all(map(is_piano_note, pitch_set)): continue # must not contain midi notes outside of piano range
# if track_type == Track.UNDEF: print('Could not designate track:', fp, t)
change_track_instrument(t, type2inst[track_type])
supported_tracks.append(t)
if not supported_tracks: return None
music_file.tracks = info_tracks + supported_tracks
return music_file
def get_track_type(t):
if is_channel(t, 10): return Track.PERC
i = get_track_instrument(t)
if i in PIANO_TYPES: return Track.PIANO
if i in PLUCK_TYPES: return Track.PLUCK
if i in BRIGHT_TYPES: return Track.BRIGHT
return Track.UNDEF
def get_track_instrument(t):
for idx,e in enumerate(t.events):
if e.type == 'PROGRAM_CHANGE': return e.data
return None
def change_track_instrument(t, value):
for idx,e in enumerate(t.events):
if e.type == 'PROGRAM_CHANGE': e.data = value
def print_music21_instruments():
for i in range(200):
try: print(i, music21.instrument.instrumentFromMidiProgram(i))
except: pass
### Vocab variables
#@title
#specifying data paths
path = 'debussy'
BPB = 4 # beats per bar
TIMESIG = f'{BPB}/4' # default time signature
PIANO_RANGE = (21, 108)
NOTE_RANGE = (1,127)
VALTSEP = -1 # separator value for numpy encoding
VALTCONT = -2 # numpy value for TCONT - needed for compressing chord array
SAMPLE_FREQ = 4
NOTE_SIZE = 128
DUR_SIZE = (10*BPB*SAMPLE_FREQ)+1 # Max length - 8 bars. Or 16 beats/quarternotes
MAX_NOTE_DUR = (8*BPB*SAMPLE_FREQ)
#tokenizing
BOS = 'xxbos'
PAD = 'xxpad'
EOS = 'xxeos'
MASK = 'xxmask' # Used for BERT masked language modeling.
#CSEQ = 'xxcseq' # Used for Seq2Seq translation - denotes start of chord sequence
#MSEQ = 'xxmseq' # Used for Seq2Seq translation - denotes start of melody sequence
#S2SCLS = 'xxs2scls' # deprecated
#NSCLS = 'xxnscls' # deprecated
SEP = 'xxsep'
IN = 'xxni' #null instrument
# Genre Tokens
ELECTRONIC = 'xxelec'
FOLK = 'xxfolk'
FUNK = 'xxfunk'
JAZZ = 'xxjazz'
POP = 'xxpop'
ROCK = 'xxrock'
# Instrument to be accepted
ACCEP_INS = dict()
ACCEP_INS['Piano'] = 0
ACCEP_INS['Guitar'] = 1
ACCEP_INS['Bass'] = 2
ACCEP_INS['WoodwindInstrument'] = 3
ACCEP_INS['BrassInstrument'] = 4
ACCEP_INS['StringInstrument'] = 5
ACCEP_INS['Misc'] = 6
ACCEP_INS_REV = {v:k for k,v in zip(ACCEP_INS.keys(), ACCEP_INS.values())}
NOTE_TOKS = [f'n{i}' for i in range(NOTE_SIZE)]
DUR_TOKS = [f'd{i}' for i in range(DUR_SIZE)]
#DONE
INS_TOKS = [f'i{i}' for i in range(len(ACCEP_INS.keys()))]
NOTE_START, NOTE_END = NOTE_TOKS[0], NOTE_TOKS[-1]
DUR_START, DUR_END = DUR_TOKS[0], DUR_TOKS[-1]
INS_START, INS_END = INS_TOKS[0], INS_TOKS[-1]
MTEMPO_SIZE = 10
MTEMPO_OFF = 'mt0'
MTEMPO_TOKS = [f'mt{i}' for i in range(MTEMPO_SIZE)]
SEQType = Enum('SEQType', 'Mask, Sentence, Melody, Chords, Empty')
# Important: SEP token must be last
#DONE
# Important: IN token must be second last
#SPECIAL_TOKS = [BOS, PAD, EOS, S2SCLS, MASK, CSEQ, MSEQ, NSCLS, SEP]
SPECIAL_TOKS = [BOS, PAD, EOS, MASK, ELECTRONIC, FOLK, FUNK, JAZZ, POP, ROCK, IN, SEP] # Important: SEP token must be last
#@title
ACCEP_INS
ACCEP_INS.keys() - {'Piano'}
#@title
ACCEP_INS_REV
### **Encoding Functions**
#@title
from fastai.torch_core import ParameterModule
def file2stream(fp):
if isinstance(fp, music21.midi.MidiFile): return music21.midi.translate.midiFileToStream(fp)
return music21.converter.parse(fp)
def npenc2stream(arr,bpm=120, instr_list = None):
"Converts numpy encoding to music21 stream"
chordarr = npenc2chordarr(np.array(arr)) # 1.
return chordarr2stream(chordarr,bpm=bpm, instr_list = instr_list) # 2.
# 2.
def stream2chordarr(s, note_size=NOTE_SIZE, sample_freq=SAMPLE_FREQ, max_note_dur=MAX_NOTE_DUR):
"Converts music21.Stream to 1- numpy array"
# assuming 4/4 time
# note x instrument x pitch
# FYI: midi middle C value=60
# (AS) TODO: need to order by instruments most played and filter out percussion or include the channel
highest_time = max(s.flat.getElementsByClass('Note').highestTime, s.flat.getElementsByClass('Chord').highestTime)
maxTimeStep = round(highest_time * sample_freq)+1
score_arr = np.zeros((maxTimeStep, len(s.parts), NOTE_SIZE))
def note_data(pitch, note):
return (pitch.midi, int(round(note.offset*sample_freq)), int(round(note.duration.quarterLength*sample_freq)))
ins=dict()
# print('---------------------------------------------------------------')
for idx,part in enumerate(s.parts):
notes=[]
iterate = False
for elem in part.flat:
# Verbose
# if isinstance(elem,music21.instrument.Instrument):
# print(elem)
# elif (not isinstance(elem, music21.note.Note)) and (not isinstance(elem, music21.chord.Chord)) and (not isinstance(elem, music21.note.Rest)):
# print(elem)
if isinstance(elem,music21.instrument.Instrument) and (elem.instrumentName is not None):
# Get the classes for each instrument
#Flawed logic
if elem.instrumentName.replace(" ", "") not in ACCEP_INS.keys():
classes = set(elem.classes) - {'Instrument', 'Music21Object', 'object', f'{elem.instrumentName.replace(" ", "")}'}
else:
classes = set(elem.classes) - {'Instrument', 'Music21Object', 'object'}
# Check for piano
if("KeyboardInstrument" in classes):
ins[idx] = 'Piano'
iterate = True
# Handle for guitar and bass
elif(elem.instrumentName == 'Guitar' or elem.instrumentName == 'Acoustic Guitar' or elem.instrumentName == 'Electric Guitar'):
ins[idx] = 'Guitar'
iterate = True
elif('Guitar' in classes and ('Bass' in elem.instrumentName)):
ins[idx] = 'Bass'
iterate = True
# Handle for remaining instruments
elif(len(classes.intersection(ACCEP_INS.keys())) != 0):
inter = list(classes.intersection(ACCEP_INS.keys()))
try:
assert len(inter) <= 1
except AssertionError:
print('Intersection with ACCEP_INS have multiple values: ',inter)
ins[idx] = inter[0]
iterate = True
else:
# print(f'instrument rejected : {elem.instrumentName}')
break
# if elem.instrumentName in ACCEP_INS.keys():
# ins[idx] = elem.instrumentName
# iterate = True
# else :
# print(f'instrument rejected : {elem.instrumentName}')
# break
elif isinstance(elem,music21.instrument.Instrument) and (elem.instrumentName is None):
ins[idx] = 'Misc'
iterate = True
if isinstance(elem, music21.note.Note):
notes.append(note_data(elem.pitch, elem))
if isinstance(elem, music21.chord.Chord):
for p in elem.pitches:
notes.append(note_data(p, elem))
# print('---------------------------------------------------------------')
# sort notes by offset (1), duration (2) so that hits are not overwritten and longer notes have priority
notes_sorted = sorted(notes, key=lambda x: (x[1], x[2]))
if(iterate == True):
for n in notes_sorted:
if n is None: continue
pitch,offset,duration = n
if max_note_dur is not None and duration > max_note_dur: duration = max_note_dur
score_arr[offset,idx, pitch] = duration
score_arr[offset+1:offset+duration, idx, pitch] = VALTCONT # Continue holding not
# def key_function(elem, x):
# print(x)
# key = list(x).index(elem)
# print(key)
# instrument = ins[key]
# pos = ACCEP_INS[instrument]
# return pos
# score_arr_sorted = sorted(score_arr, key=lambda x: key_function(x[1], x))
return score_arr, ins
def chordarr2npenc(chordarr, skip_last_rest=True):
# combine instruments
# print(chordarr)
result = []
wait_count = 0
for idx,timestep in enumerate(chordarr):
flat_time = timestep2npenc(timestep)
#DONE
#print(idx, flat_time)
if len(flat_time) == 0:
wait_count += 1
else:
# pitch, octave, duration, instrument
# DONE: Replaced -2 with (-2 - len(NOTE_TOKS) - len(DUR_TOKS)) so that in `npenc2idxenc`,
# `t[:, 2] = t[:, 2] + vocab.ins_range[0]` gives right mapping in vocal.itos
if wait_count > 0: result.append([VALTSEP, wait_count, -2 - len(NOTE_TOKS) - len(DUR_TOKS)])
result.extend(flat_time)
wait_count = 1
if wait_count > 0 and not skip_last_rest: result.append([VALTSEP, wait_count, -2 - len(NOTE_TOKS) - len(DUR_TOKS)])
return np.array(result,dtype = int)
#return np.array(result, dtype=int).reshape(-1, 2) # reshaping. Just in case result is empty
'''
def chordarr2npenc(chordarr, skip_last_rest=True):
# combine instruments
result = []
wait_count = 0
for idx,timestep in enumerate(chordarr):
flat_time = timestep2npenc(timestep)
if len(flat_time) == 0:
wait_count += 1
else:
# pitch, octave, duration, instrument
if wait_count > 0: result.append([VALTSEP, wait_count])
result.extend(flat_time)
wait_count = 1
if wait_count > 0 and not skip_last_rest: result.append([VALTSEP, wait_count])
return np.array(result, dtype=int).reshape(-1, 2) # reshaping. Just in case result is empty
'''
# Note: not worrying about overlaps - as notes will still play. just look tied
# http://web.mit.edu/music21/doc/moduleReference/moduleStream.html#music21.stream.Stream.getOverlaps
def timestep2npenc(timestep, note_range=NOTE_RANGE, enc_type='full'):
# inst x pitch
notes = []
for i,n in zip(*timestep.nonzero()):
d = timestep[i,n]
if d < 0: continue # only supporting short duration encoding for now
if n < note_range[0] or n >= note_range[1]: continue # must be within midi range
notes.append([n,d,i])
notes = sorted(notes, key=lambda x: x[0], reverse=True) # sort by note (highest to lowest)
if enc_type is None:
# note, duration
return [n[:2] for n in notes]
if enc_type == 'parts':
# note, duration, part
return [n for n in notes]
if enc_type == 'full':
# note_class, duration , instrument
return [[n, d, i] for n,d,i in notes]
'''
# Note: not worrying about overlaps - as notes will still play. just look tied
# http://web.mit.edu/music21/doc/moduleReference/moduleStream.html#music21.stream.Stream.getOverlaps
def timestep2npenc(timestep, note_range=PIANO_RANGE, enc_type=None):
# inst x pitch
notes = []
a, b = zip(*timestep.nonzero())
for i,n in zip(*timestep.nonzero()):
d = timestep[i,n]
if d < 0: continue # only supporting short duration encoding for now
if n < note_range[0] or n >= note_range[1]: continue # must be within midi range
notes.append([n,d,i])
notes = sorted(notes, key=lambda x: x[0], reverse=True) # sort by note (highest to lowest)
if enc_type is None:
# note, duration
return [n[:2] for n in notes]
if enc_type == 'parts':
# note, duration, part
return [n for n in notes]
if enc_type == 'full':
# note_class, duration, octave, instrument
return [[n%12, d, n//12, i] for n,d,i in notes]
'''
### **Decoding Functions**
ACCEP_INS.keys()
#@title
# 1.
def npenc2chordarr(npenc,note_size=NOTE_SIZE):
num_instruments = 1 if npenc.shape[1] <= 2 else npenc.max(axis=0)[-1]
max_len = npenc_len(npenc)
# score_arr = (steps, inst, note)
score_arr = np.zeros((max_len, num_instruments + 1, note_size))
idx = 0
for step in npenc:
n,d,i = (step.tolist()+[0])[:3] # or n,d,i
if n < VALTSEP: continue # special token
if n == VALTSEP:
idx += d
continue
score_arr[idx,i,n] = d
return score_arr
def npenc_len(npenc):
duration = 0
for t in npenc:
if t[0] == VALTSEP: duration += t[1]
return duration + 1
# 2.
def chordarr2stream(arr,sample_freq=SAMPLE_FREQ, bpm=120, instr_list = None):
duration = music21.duration.Duration(1. / sample_freq)
stream = music21.stream.Score()
stream.append(music21.meter.TimeSignature(TIMESIG))
stream.append(music21.tempo.MetronomeMark(number=bpm))
stream.append(music21.key.KeySignature(0))
for inst in range(arr.shape[1]):
p = partarr2stream(arr[:,inst,:],inst,duration)
#print(p.getInstrument())
if instr_list is not None and str(p.getInstrument()) not in instr_list:
#print('+', instr_list)
continue
stream.append(p)
stream = stream.transpose(0)
return stream
# 2b.
def partarr2stream(partarr,inst,duration):
"convert instrument part to music21 chords"
# part = music21.stream.Part()
# part.append(music21.instrument.Piano())
# part_append_duration_notes(partarr, duration, part) # notes already have duration calculated
l = len(ACCEP_INS_REV)
inst = inst%l
part = music21.stream.Part()
if(ACCEP_INS_REV[inst] == 'Piano'):
part.append(music21.instrument.Piano())
#DONE
elif(ACCEP_INS_REV[inst] == 'Bass'):
part.append(music21.instrument.AcousticBass())
elif(ACCEP_INS_REV[inst] == 'Guitar'):
part.append(music21.instrument.AcousticGuitar())
elif(ACCEP_INS_REV[inst] == 'WoodwindInstrument'):
part.append(music21.instrument.TenorSaxophone())
elif(ACCEP_INS_REV[inst] == 'BrassInstrument'):
part.append(music21.instrument.Trumpet())
elif(ACCEP_INS_REV[inst] == 'Trumpet'):
part.append(music21.instrument.Trumpet())
elif(ACCEP_INS_REV[inst] == 'Tenor Saxophone'):
part.append(music21.instrument.TenorSaxophone())
elif(ACCEP_INS_REV[inst] == 'Vibraphone'):
part.append(music21.instrument.Vibraphone())
elif(ACCEP_INS_REV[inst] == 'Baritone Saxophone'):
part.append(music21.instrument.BaritoneSaxophone())
elif(ACCEP_INS_REV[inst] == 'Acoustic Bass'):
part.append(music21.instrument.AcousticBass())
elif(ACCEP_INS_REV[inst] == 'Trombone'):
part.append(music21.instrument.Trombone())
elif(ACCEP_INS_REV[inst] == 'Flute'):
part.append(music21.instrument.Flute())
elif(ACCEP_INS_REV[inst] == 'Saxophone'):
part.append(music21.instrument.Saxophone())
elif(ACCEP_INS_REV[inst] == 'Electric Bass'):
part.append(music21.instrument.ElectricBass())
elif(ACCEP_INS_REV[inst] == 'Electric Guitar'):
part.append(music21.instrument.ElectricGuitar())
elif(ACCEP_INS_REV[inst] == 'Acoustic Guitar'):
part.append(music21.instrument.AcousticGuitar())
elif(ACCEP_INS_REV[inst] == 'Glockenspiel'):
part.append(music21.instrument.Glockenspiel())
elif(ACCEP_INS_REV[inst] == 'Vibraphone'):
part.append(music21.instrument.Vibraphone())
elif(ACCEP_INS_REV[inst] == 'Violin'):
part.append(music21.instrument.Violin())
else:
part.append(music21.instrument.Piano())
part_append_duration_notes(partarr, duration, part)
return part
def part_append_duration_notes(partarr, duration, stream):
"convert instrument part to music21 chords"
for tidx,t in enumerate(partarr):
note_idxs = np.where(t > 0)[0] # filter out any negative values (continuous mode)
if len(note_idxs) == 0: continue
notes = []
for nidx in note_idxs:
note = music21.note.Note(nidx)
note.duration = music21.duration.Duration(partarr[tidx,nidx]*duration.quarterLength)
notes.append(note)
for g in group_notes_by_duration(notes):
if len(g) == 1:
stream.insert(tidx*duration.quarterLength, g[0])
else:
chord = music21.chord.Chord(g)
stream.insert(tidx*duration.quarterLength, chord)
return stream
from itertools import groupby
# combining notes with different durations into a single chord may overwrite conflicting durations. Example: aylictal/still-waters-run-deep
def group_notes_by_duration(notes):
"separate notes into chord groups"
keyfunc = lambda n: n.duration.quarterLength
notes = sorted(notes, key=keyfunc)
return [list(g) for k,g in groupby(notes, keyfunc)]
# Midi -> npenc Conversion helpers
def is_valid_npenc(npenc, note_range=PIANO_RANGE, max_dur=DUR_SIZE,
min_notes=32, input_path=None, verbose=True):
if len(npenc) < min_notes:
if verbose: print('Sequence too short:', len(npenc), input_path)
return False
if (npenc[:,1] >= max_dur).any():
if verbose: print(f'npenc exceeds max {max_dur} duration:', npenc[:,1].max(), input_path)
return False
# https://en.wikipedia.org/wiki/Scientific_pitch_notation - 88 key range - 21 = A0, 108 = C8
if ((npenc[...,0] > VALTSEP) & ((npenc[...,0] < note_range[0]) | (npenc[...,0] >= note_range[1]))).any():
print(f'npenc out of piano note range {note_range}:', input_path)
return False
return True
# seperates overlapping notes to different tracks
def remove_overlaps(stream, separate_chords=True):
if not separate_chords:
return stream.flat.makeVoices().voicesToParts()
return separate_melody_chord(stream)
# seperates notes and chords to different tracks
def separate_melody_chord(stream):
new_stream = music21.stream.Score()
if stream.timeSignature: new_stream.append(stream.timeSignature)
new_stream.append(stream.metronomeMarkBoundaries()[0][-1])
if stream.keySignature: new_stream.append(stream.keySignature)
melody_part = music21.stream.Part(stream.flat.getElementsByClass('Note'))
melody_part.insert(0, stream.getInstrument())
chord_part = music21.stream.Part(stream.flat.getElementsByClass('Chord'))
chord_part.insert(0, stream.getInstrument())
new_stream.append(melody_part)
new_stream.append(chord_part)
return new_stream
# processing functions for sanitizing data
def compress_chordarr(chordarr):
return shorten_chordarr_rests(trim_chordarr_rests(chordarr))
def trim_chordarr_rests(arr, max_rests=4, sample_freq=SAMPLE_FREQ):
# max rests is in quarter notes
# max 1 bar between song start and end
start_idx = 0
max_sample = max_rests*sample_freq
for idx,t in enumerate(arr):
if (t != 0).any(): break
start_idx = idx+1
end_idx = 0
for idx,t in enumerate(reversed(arr)):
if (t != 0).any(): break
end_idx = idx+1
start_idx = start_idx - start_idx % max_sample
end_idx = end_idx - end_idx % max_sample
# if start_idx > 0 or end_idx > 0: print('Trimming rests. Start, end:', start_idx, len(arr)-end_idx, end_idx)
return arr[start_idx:(len(arr)-end_idx)]
def shorten_chordarr_rests(arr, max_rests=8, sample_freq=SAMPLE_FREQ):
# max rests is in quarter notes
# max 2 bar pause
rest_count = 0
result = []
max_sample = max_rests*sample_freq
for timestep in arr:
if (timestep==0).all():
rest_count += 1
else:
if rest_count > max_sample:
# old_count = rest_count
rest_count = (rest_count % sample_freq) + max_sample
# print(f'Compressing rests: {old_count} -> {rest_count}')
for i in range(rest_count): result.append(np.zeros(timestep.shape))
rest_count = 0
result.append(timestep)
for i in range(rest_count): result.append(np.zeros(timestep.shape))
return np.array(result)
# sequence 2 sequence convenience functions
def stream2npenc_parts(stream, sort_pitch=True):
chordarr = stream2chordarr(stream)
_,num_parts,_ = chordarr.shape
parts = [part_enc(chordarr, i) for i in range(num_parts)]
return sorted(parts, key=avg_pitch, reverse=True) if sort_pitch else parts
def chordarr_combine_parts(parts):
max_ts = max([p.shape[0] for p in parts])
parts_padded = [pad_part_to(p, max_ts) for p in parts]
chordarr_comb = np.concatenate(parts_padded, axis=1)
return chordarr_comb
def pad_part_to(p, target_size):
pad_width = ((0,target_size-p.shape[0]),(0,0),(0,0))
return np.pad(p, pad_width, 'constant')
def part_enc(chordarr, part):
partarr = chordarr[:,part:part+1,:]
npenc = chordarr2npenc(partarr)
return npenc
def avg_tempo(t, sep_idx=VALTSEP):
avg = t[t[:, 0] == sep_idx][:, 1].sum()/t.shape[0]
avg = int(round(avg/SAMPLE_FREQ))
return 'mt'+str(min(avg, MTEMPO_SIZE-1))
def avg_pitch(t, sep_idx=VALTSEP):
return t[t[:, 0] > sep_idx][:, 0].mean()
###Extra fastai utilities
#@title
def check_valid_ins(ins):
count = 0
ls = list(set(val for val in ins.values()))
for i in ls:
if i == 'Piano':
count+= 1
elif i == 'Acoustic Bass' or i == 'Electric Bass':
count += 1
elif i == 'Acoustic Guitar' or i == 'Electric Guitar':
count += 1
elif i == 'Violin':
count += 1
elif i == 'Saxophone':
count += 1
if(count>=3):
return True
return False
import time
#DONE
def fastai_num_track_filter (arg, num_ins_thresh = 1):
global time_taken_avg, processed_files
t1 = time.time()
# print('-> Processing file no. ', files_dict[arg])
# Try for inconsistent vocab and file errors
try:
filename, file_extension = os.path.splitext(arg)
if file_extension == '.mid':
item = MusicItem.from_file(arg, data_vocab)
data_vocab.textify(item.data)
elif file_extension == '.npy':
nparr = np.load(arg, allow_pickle=True)
item = MusicItem.from_npenc(nparr, data_vocab)
data_vocab.textify(item.data)
except:
print('\t file discarded : ', arg)
os.makedirs('/content/drive/MyDrive/datasets/discarded', exist_ok = True)
shutil.move(arg, os.path.join('/content/drive/MyDrive/datasets/discarded',os.path.basename(arg)))
# t2 = time.time()
# time_taken_avg = ((t2 - t1) + time_taken_avg*processed_files)/(processed_files + 1)
# processed_files += 1
# print(f'\t estimated_time : {time_taken_avg*len(files_dict)}')
return False
# t2 = time.time()
# time_taken_avg = ((t2 - t1) + time_taken_avg*processed_files)/(processed_files + 1)
# processed_files += 1
# Check for no. of instruments
# print(item.ins)
if (item.ins is not None) and (len(item.ins.keys()) >= num_ins_thresh):
print('\t file accepted : ', arg)
print(f'\t {item.ins}')
# print(f'\t estimated_time : {time_taken_avg*len(files_dict)}')
return True
#Else if we did not store the track -> instrument dictionary from MIDI file
elif item.ins is None:
# print(item.data.shape)
lst = list(item.data)
# print(lst)
cond_lst = [True if ( (x >= data_vocab.ins_range[0] and x < data_vocab.ins_range[1]) or (x == data_vocab.stoi['xxni']) ) else False for x in lst]
ins_idxs = item.data[cond_lst]
# print([data_vocab.itos[x] for index,x in enumerate(lst) if index%3 == 0])
uniq_ins = np.unique(ins_idxs)
num_ins = len(uniq_ins)
if num_ins >= num_ins_thresh:
print('\t file accepted : ', arg)
print(f'\t {[data_vocab.itos[x] for x in uniq_ins]}')
return True
else:
print('\t file discarded due to less instruments : ', arg)
return False
else:
print('\t file discarded due to less instruments : ', arg)
# print(f'\t estimated_time : {time_taken_avg*len(files_dict)}')
return False
# ins = dict()
# if not is_empty_midi(arg):
# s = file2stream(arg)
# for idx,part in enumerate(s.parts):
# for elem in part.flat:
# if (isinstance(elem,music21.instrument.Instrument)) and (elem.instrumentName is not None):
# # DONE
# # Get the classes for each instrument
# if elem.instrumentName.replace(" ", "") not in ACCEP_INS.keys():
# classes = set(elem.classes) - {'Instrument', 'Music21Object', 'object', f'{elem.instrumentName.replace(" ", "")}'}
# else:
# classes = set(elem.classes) - {'Instrument', 'Music21Object', 'object'}
# # Check for piano
# if("KeyboardInstrument" in classes):
# if('Piano' not in ins.keys()): ins['Piano'] = 1
# else: ins['Piano'] += 1
# # Handle for guitar and bass
# elif(elem.instrumentName == 'Guitar' or elem.instrumentName == 'Acoustic Guitar' or elem.instrumentName == 'Electric Guitar'):
# if('Guitar' not in ins.keys()): ins['Guitar'] = 1
# else: ins['Guitar'] += 1
# elif('Guitar' in classes and ('Bass' in elem.instrumentName)):
# if('Bass' not in ins.keys()): ins['Bass'] = 1
# else: ins['Bass'] += 1
# # Handle for remaining instruments
# else:
# inter = list(classes.intersection(ACCEP_INS.keys()))
# if(len(inter) != 0):
# if(inter[0] not in ins.keys()): ins[inter[0]] = 1
# else: ins[inter[0]] += 1
# elif isinstance(elem,music21.instrument.Instrument) and (elem.instrumentName is None):
# if('Misc' not in ins.keys()): ins['Misc'] = 1
# else: ins['Misc'] += 1
# else:
# break
# # if elem.instrumentName in (ACCEP_INS.keys()):
# # ins_count += 1
# # else :
# # break
## **Transformer-XL**
####TODO
#@title
'''
(i) Correct the filter function : fast_ai_filter_function
(ii) filter the dataset / enforce max duration + notes + instruments in : npenc2idxenc
(ii.v) Add xxbos, xxeos, xxpad etc
-> Balance the data (currently imbalanced towards piano, which also might be the cause for 'dense' outputs for piano in terms of num. notes each timestep)
-> One thing that could help with the above is to group multiple instruments together, eg: merging AcousticGuitar, ElectricGuitar, BassGuitar into StringInstrument
-> Filter output of model properly (.to_stream() fails many times due to corner cases violating 'partnerless' n or d or i
-> Fix the flawed logic of conversion of every song to 4/4 time signature by rounding off, and then add time signature tokens to model vocab
and dataset in order to get consistent output.
(iv) train :)
'''
###**vocab**
#@title
#SEE 'Vocab variables'for more details
# Vocab - token to index mapping
class MusicVocab():
"Contain the correspondence between numbers and tokens and numericalize."
def __init__(self, itos:Collection[str]):
self.itos = itos
self.stoi = {v:k for k,v in enumerate(self.itos)}
def numericalize(self, t:Collection[str]) -> List[int]:
"Convert a list of tokens `t` to their ids."
return [self.stoi[w] for w in t]
def textify(self, nums:Collection[int], sep=' ') -> List[str]:
"Convert a list of `nums` to their tokens."
items = [self.itos[i] for i in nums]
return sep.join(items) if sep is not None else items
#DONE
def to_music_item(self, idxenc, ins = None):
return MusicItem(idxenc, self, ins)
@property
def mask_idx(self): return self.stoi[MASK]
@property
def pad_idx(self): return self.stoi[PAD]
@property
def bos_idx(self): return self.stoi[BOS]
@property
def sep_idx(self): return self.stoi[SEP]
#DONE
@property
def ni_idx(self): return self.stoi[IN]
@property
#DONE: changed 'DUR_END' to 'INS_END'
def npenc_range(self): return (self.stoi[IN], self.stoi[INS_END]+1)
@property
def note_range(self): return self.stoi[NOTE_START], self.stoi[NOTE_END]+1
@property
def dur_range(self): return self.stoi[DUR_START], self.stoi[DUR_END]+1
#DONE
@property
def ins_range(self): return self.stoi[INS_START], self.stoi[INS_END]+1
def is_duration(self, idx):
return idx >= self.dur_range[0] and idx < self.dur_range[1]
def is_duration_or_pad(self, idx):
return idx == self.pad_idx or self.is_duration(idx)
#DONE
def is_note(self, idx):
return idx == self.sep_idx or (idx >= self.note_range[0] and idx < self.note_range[1])
def is_ins(self, idx):
return idx == self.ni_idx or (idx >= self.ins_range[0] and idx < self.ins_range[1])
def __getstate__(self):
return {'itos':self.itos}
def __setstate__(self, state:dict):
self.itos = state['itos']
self.stoi = {v:k for k,v in enumerate(self.itos)}
def __len__(self): return len(self.itos)
def save(self, path):
"Save `self.itos` in `path`"
pickle.dump(self.itos, open(path, 'wb'))
@classmethod
def create(cls) -> 'Vocab':
"Create a vocabulary from a set of `tokens`."
#DONE
#itos = SPECIAL_TOKS + NOTE_TOKS + DUR_TOKS + MTEMPO_TOKS
itos = SPECIAL_TOKS + NOTE_TOKS + DUR_TOKS + INS_TOKS + MTEMPO_TOKS
if len(itos)%8 != 0:
itos = itos + [f'dummy{i}' for i in range(len(itos)%8)]
return cls(itos)
@classmethod
def load(cls, path):
"Load the `Vocab` contained in `path`"
itos = pickle.load(open(path, 'rb'))
return cls(itos)
###**dataloader.py**
#@title
import fastai
#@title
#https://github.com/bearpelican/musicautobot/blob/master/musicautobot/music_transformer/dataloader.py
"Fastai Language Model Databunch modified to work with music"
from fastai.basics import *
# from fastai.basic_data import DataBunch
from fastai.text.data import LMLabelList
#from .transform import *
#from ..vocab import MusicVocab
class MusicDataBunch(DataBunch):
"Create a `TextDataBunch` suitable for training a language model."
@classmethod
def create(cls, train_ds, valid_ds, test_ds=None, path:PathOrStr='.', no_check:bool=False, bs=64, val_bs:int=None,
num_workers:int=0, device:torch.device=None, collate_fn:Callable=data_collate,
dl_tfms:Optional[Collection[Callable]]=None, bptt:int=70,
preloader_cls=None, shuffle_dl=False, transpose_range=(0,12), **kwargs) -> DataBunch:
"Create a `TextDataBunch` in `path` from the `datasets` for language modelling."
datasets = cls._init_ds(train_ds, valid_ds, test_ds)
preloader_cls = MusicPreloader if preloader_cls is None else preloader_cls
val_bs = ifnone(val_bs, bs)
datasets = [preloader_cls(ds, shuffle=(i==0), bs=(bs if i==0 else val_bs), bptt=bptt, transpose_range=transpose_range, **kwargs)
for i,ds in enumerate(datasets)]
val_bs = bs
dl_tfms = [partially_apply_vocab(tfm, train_ds.vocab) for tfm in listify(dl_tfms)]
dls = [DataLoader(d, b, shuffle=shuffle_dl) for d,b in zip(datasets, (bs,val_bs,val_bs,val_bs)) if d is not None]
return cls(*dls, path=path, device=device, dl_tfms=dl_tfms, collate_fn=collate_fn, no_check=no_check)
@classmethod
def from_folder(cls, path:PathOrStr, extensions='.npy', **kwargs):
files = get_files(path, extensions=extensions, recurse=True);
return cls.from_files(files, path, **kwargs)
@classmethod
def from_files(cls, files, path, processors=None, split_pct=0.1,
vocab=None, list_cls=None, **kwargs):
if vocab is None: vocab = MusicVocab.create()
if list_cls is None: list_cls = MusicItemList
src = (list_cls(items=files, path=path, processor=processors, vocab=vocab)
.filter_by_func(fastai_num_track_filter)
.split_by_rand_pct(split_pct, seed=6)
.label_const(label_cls=LMLabelList))
return src.databunch(**kwargs)
@classmethod
def empty(cls, path, **kwargs):
vocab = MusicVocab.create()
src = MusicItemList([], path=path, vocab=vocab, ignore_empty=True).split_none()
return src.label_const(label_cls=LMLabelList).databunch()
def partially_apply_vocab(tfm, vocab):
if 'vocab' in inspect.getfullargspec(tfm).args:
return partial(tfm, vocab=vocab)
return tfm
class MusicItemList(ItemList):
_bunch = MusicDataBunch
def __init__(self, items:Iterator, vocab:MusicVocab=None, **kwargs):
super().__init__(items, **kwargs)
self.vocab = vocab
self.copy_new += ['vocab']
def get(self, i):
o = super().get(i)
if is_pos_enc(o):
return MusicItem.from_idx(o, self.vocab)
return MusicItem(o, self.vocab)
def is_pos_enc(idxenc):
if len(idxenc.shape) == 2 and idxenc.shape[0] == 2: return True
return idxenc.dtype == np.object and idxenc.shape == (2,)
class MusicItemProcessor(PreProcessor):
"`PreProcessor` that transforms numpy files to indexes for training"
def process_one(self,item):
item, genre = item
item = MusicItem.from_npenc(item, vocab=self.vocab, genre = genre)
return item.to_idx()
def process(self, ds):
self.vocab = ds.vocab
super().process(ds)
class OpenNPFileProcessor(PreProcessor):
"`PreProcessor` that opens the filenames and read the texts."
def process_one(self,item):
genre = os.path.split(os.path.split(item)[0])[1].lower()
return (np.load(item, allow_pickle=True), genre) if isinstance(item, Path) else (item, genre)
class Midi2ItemProcessor(PreProcessor):
"Skips midi preprocessing step. And encodes midi files to MusicItems"
def process_one(self,item):
# print('Midi2ItemProcess process_one')
item = MusicItem.from_file(item, vocab=self.vocab)
print('item.to_idx(): ', item.to_idx())
return item.to_idx()
def process(self, ds):
self.vocab = ds.vocab
super().process(ds)
## For npenc dataset