Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mozart Ai For the Joy of Making Music by Luminosity-e

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.jit import script, trace
from music21 import stream, note, tempo, instrument, converter


class Attention(nn.Module):
def __init__(self, hidden_dim):
super(Attention, self).__init__()
self.hidden_dim = hidden_dim
self.attn = nn.Linear(self.hidden_dim * 2, hidden_dim)
self.v = nn.Parameter(torch.rand(hidden_dim))

def forward(self, hidden, encoder_outputs):
timestep = encoder_outputs.size(0)
h = hidden.repeat(timestep, 1)
attn_energies = self.score(h, encoder_outputs)
return F.softmax(attn_energies, dim=1).unsqueeze(1)

def score(self, hidden, encoder_outputs):
energy = F.relu(self.attn(torch.cat([hidden, encoder_outputs], 1)))
energy = energy.transpose(1, 0)
v = self.v.repeat(encoder_outputs.size(0), 1).transpose(1, 0)
energy = torch.sum(v * energy, dim=1)
return energy


class Mozart(nn.Module):
def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):
super(Mozart, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = layer_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, layer_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim * 2, output_dim)
self.attention = Attention(hidden_dim)
self.creator = "Luminosity Matthew Richard Kowalski"
self.name = "Mozart"

def forward(self, x):
h0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_()
c0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_()
out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))
attn_weights = self.attention(hn[-1], out)
context = attn_weights.bmm(out.transpose(0, 1))
out = self.fc(torch.cat([hn[-1], context[:, 0]], 1))
return out


class MemoizationTable:
def __init__(self, rows=10, cols=10, device='cpu'):
self.table = torch.zeros((rows, cols)).to(device)

def clear(self):
self.table.fill_(0)

def fill(self):
self.table.fill_(1)

def update_table(self, new_data):
self.table = new_data


def generate_music(model, length=100, temperature=1.0):
model.eval()
device = next(model.parameters()).device
initial_input = torch.zeros(1, 1, 1).to(device)
output_sequence = [initial_input]
with torch.no_grad():
for _ in range(length):
output = model(output_sequence[-1])
output = F.softmax(output / temperature, dim=1)
output_sequence.append(output.unsqueeze(1))
return torch.cat(output_sequence, dim=1)



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


def save_midi(output_sequence, filename):
stream_out = stream.Stream()
for output in output_sequence.squeeze():
pitch = int(output.item() * 88) + 21
n = note.Note()
n.pitch.midi = pitch
n.duration.quarterLength = 0.5
stream_out.append(n)
stream_out.insert(0, tempo.MetronomeMark(number=120))
stream_out.insert(0, instrument.Piano())

midi_stream = stream_out.transpose(0)
midi_stream.write("midi", fp=filename)


# Example usage:
output_sequence = generate_music(model, length=100, temperature=1.0)
save_midi(output_sequence, "output.mid")

Mozart AI Program
=================

This program utilizes an LSTM-based neural network to generate music compositions. It provides functionality for generating music sequences and saving them as MIDI files.

Dependencies
------------
- torch: PyTorch deep learning framework
- music21: Library for music notation processing

Classes
-------
- Attention: Attention mechanism module for the LSTM model.
- Mozart: LSTM-based music generation model inspired by Mozart.
- MemoizationTable: Table used for memoization during model training.
- generate_music: Function to generate music using the trained model.
- save_midi: Function to save the generated music sequence as a MIDI file.

Usage
-----
1. Import the required dependencies: `torch`, `torch.nn`, `torch.nn.functional`, `torch.jit.script`, `music21.stream`, `music21.note`, `music21.tempo`, `music21.instrument`, `music21.converter`.
2. Define the model architecture by creating the `Attention` and `Mozart` classes.
3. Initialize an instance of the `Mozart` model with the desired input, hidden, and output dimensions.
4. Optionally, specify the creator's name and the model's name.
5. Generate music using the `generate_music` function by passing the trained model, desired length, and temperature parameter.
6. Save the generated music sequence as a MIDI file using the `save_midi` function.

Example Usage
-------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.jit import script, trace
from music21 import stream, note, tempo, instrument, converter

# Define the model architecture

class Attention(nn.Module):
...

class Mozart(nn.Module):
...

# Initialize the model

model = Mozart(input_dim, hidden_dim, layer_dim, output_dim)
model.creator = "Luminosity Matthew Richard Kowalski"
model.name = "Mozart"

# Generate music

output_sequence = generate_music(model, length=100, temperature=1.0)

# Save the generated music as a MIDI file

save_midi(output_sequence, "output.mid")




This post first appeared on A Day Dream Lived., please read the originial post: here

Share the post

Mozart Ai For the Joy of Making Music by Luminosity-e

×

Subscribe to A Day Dream Lived.

Get updates delivered right to your inbox!

Thank you for your subscription

×