# -*- coding: utf-8 -*-
"""
Created on Thu Nov 14 21:42:39 2019

@author: Henri_2
"""

from music21 import converter, instrument, note, chord, stream

def create_midi(prediction_output):
    print('creating midi-file')
    """ convert the output from the prediction to notes and create a midi file
        from the notes """
    offset = 0
    output_notes = []

    # create note and chord objects based on the values generated by the model
    for pattern in prediction_output:
        try:
            # pattern is a chord
            if ('.' in pattern[1]) or pattern[1].isdigit():
                
                notes_in_chord = pattern[1].split('.')
                notes = []
                for current_note in notes_in_chord:
                    new_note = note.Note(int(current_note))
                    new_note.duration.type = pattern[0]
                    new_note.storedInstrument = instrument.Piano()
                    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[1])
                new_note.offset = offset
                new_note.duration.type = pattern[0]
                new_note.storedInstrument = instrument.Piano()
                output_notes.append(new_note)
        except KeyError:    
            continue
        except:
            continue

        # increase offset each iteration so that notes do not stack
        offset += 0.5

    midi_stream = stream.Stream(output_notes)
    

    midi_stream.write('midi', fp='test_output.mid')