-
Notifications
You must be signed in to change notification settings - Fork 0
/
predict.py
60 lines (50 loc) · 1.7 KB
/
predict.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
import c
import torch
from music21 import converter, instrument, note, chord, stream
def sample(preds, temperature=1):
# helper function to sample an index from a probability array
probas = torch.softmax(preds/temperature, 1)
return torch.multinomial(probas,1)
def generate_song(model, start_note, length):
song = torch.tensor(start_note).view(1)
for i in range(length):
logits = model(song)
#probas = torch.softmax(logits,dim = 1)
#probas = sample(logits/temperature,1)
#predicted_labels = torch.multinomial(probas,1)
predicted_labels = sample(logits,1)
song = torch.cat((song.view(-1), predicted_labels[-1].view(-1)))
print(song)
return song
def ints_to_notes(song, int_to_str):
return [int_to_str[x] for x in song]
def create_midi(prediction, file_path):
offset = 0
output_notes = []
# create note and chord objects based on the values generated by the model
for pattern in prediction:
if pattern == "rest":
new_note = note.Rest()
new_note.offset = offset
output_notes.append(new_note)
# pattern is a chord
elif ' ' in pattern:
notes_in_chord = pattern.split(' ')
notes = []
for current_note in notes_in_chord:
new_note = note.Note(current_note)
new_note.storedInstrument = instrument.BassDrum()
notes.append(new_note)
new_chord = chord.Chord(notes)
new_chord.offset = offset
output_notes.append(new_chord)
# pattern is a note
else:
new_note = note.Note(pattern)
new_note.offset = offset
new_note.storedInstrument = instrument.BassDrum()
output_notes.append(new_note)
# increase offset each iteration so that notes do not stack
offset += 0.5
midi_stream = stream.Stream(output_notes)
midi_stream.write('midi', fp=file_path)