ST AI music
from music21 import converter, instrument, note, chord
def preprocess_midi(file_path):
midi = converter.parse(file_path)
notes = []
for element in midi.flat.notes:
if isinstance(element, note.Note):
notes.append(str(element.pitch))
elif isinstance(element, chord.Chord):
notes.append('.'.join(str(n) for n in element.normalOrder))
return notes
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
def build_model(input_shape):
model = Sequential([
LSTM(512, return_sequences=True, input_shape=input_shape),
Dropout(0.3),
LSTM(512, return_sequences=True),
Dropout(0.3),
LSTM(512),
Dense(256),
Dense(128),
Dense(1)
])
model.compile(optimizer='adam', loss='categorical_crossentropy')
return model
import numpy as np
def generate_notes(model, input_notes, num_notes):
notes = []
pattern = input_notes[:100] # Starting sequence
for _ in range(num_notes):
prediction = model.predict(np.array([pattern]))
index = np.argmax(prediction)
notes.append(index)
pattern.append(index)
pattern = pattern[1:]
return notes
import numpy as np
def generate_notes(model, input_notes, num_notes):
notes = []
pattern = input_notes[:100] # Starting sequence
for _ in range(num_notes):
prediction = model.predict(np.array([pattern]))
index = np.argmax(prediction)
notes.append(index)
pattern.append(index)
pattern = pattern[1:]
return notes
from music21 import stream, note, chord
def create_midi_file(notes, file_path):
output_notes = []
for n in notes:
new_note = note.Note(n)
new_note.quarterLength = 0.5
output_notes.append(new_note)
midi_stream = stream.Stream(output_notes)
midi_stream.write('midi', fp=file_path)
6from flask import Flask, request, jsonify
import your_music_generator_code
app = Flask(__name__)
@app.route('/generate', methods=['POST'])
def generate():
data = request.json
prompt = data['prompt']
generated_midi = your_music_generator_code.generate_music(prompt)
return jsonify({'status': 'success', 'midi_file': generated_midi})
if __name__ == '__main__':
app.run(debug=True)
Comments
Post a Comment