| | Def generate_notes (model, network_input, note_name, notes_len): |
| | Randindex = np.random.randint (0, len (network_input) − 1) |
| | Notedic = dict ((i, j) for i, j in enumerate (note_name)) # restore values to tones |
| | Pattern = network_input [randindex] |
| | Prediction = [] |
| | # Randomly generate 1000 notes |
| | For note_index in range (1000): |
| | Prediction_input = np.reshape (pattern, (1, len(pattern), 1)) |
| | Prediction_input = prediction_input/float (notes_len) # normalize |
| | Prediction = model.predict (prediction_input, verbose = 0) |
| | Index = np.argmax (prediction) |
| | Result = notedic [index] |
| | Prediction.append (result) |
| | Pattern.append (index) |
| | Pattern = pattern [1 : len(pattern)] |
| | Return prediction |
| | # Generate mid music |
| | Def create_music(): |
| | Network_input, normal_network_input, notes_len, note_name = train() |
| | # Find the weight file with the smallest loss as the training parameter |
| | Files = os.listdir() |
| | Minloss = {} |
| | For i in files: |
| | If ‘weights’ in i: |
| | Num = i[11 : 15] |
| | Minloss [num] = i |
| | Best_weights = minloss [min(minloss.keys())] |
| | Model = get_model (normal_network_input, notes_len, best_weights) |
| | Prediction = generate_notes (model, network_input, note_name, notes_len) |
| | Offset = 0 |
| | Output_notes = [] |
| | # Generate note or chord objects |
| | For data in prediction: |
| | If (‘.’ in data) or data.isdigit(): |
| | Notes_in_chord = data.split (’,') |
| | Notes = [] |
| | For current_note in notes_in_chord: |
| | New_note = note.Note (int (current_note)) |
| | New_note.storedInstrument = instrument.Piano() |
| | Notes.append (new_note) |
| | New_chord = chord.Chord (notes) |
| | New_chord.offset = offset |
| | Output_notes.append (new_chord) |
| | Else: |
| | New_note = note.Note (data) |
| | New_note.offset = offset |
| | New_note.storedInstrument = instrument.Piano() |
| | Output_notes.append (new_note) |
| | Offset+ = 1 |
| | # Create a music stream |
| | Midi_stream = stream.Stream (output_notes) |
| | # Write MIDI file |
| | Midi_stream.write (‘midi’, fp = ‘output1.mid’) |