import os
import numpy as np
import pretty_midi
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply, GaussianNoise
from keras.layers import BatchNormalization, Activation, Embedding, ZeroPadding2D
from keras.layers import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Sequential, Model
from keras.optimizers import Adam
from keras import losses
from keras.utils import to_categorical
from joblib import load, dump
import scipy.io.wavfile as wavfile

class Music():
    def __init__(self):
        self.latent_dim = 100
        self.midi_data = None
        self.optimizer = Adam(0.0002, 0.5)

        self.discriminator = self.build_discriminator()
        self.discriminator.compile(loss='binary_crossentropy', optimizer=self.optimizer, metrics=['accuracy'])
        
        self.generator = self.build_generator()
        z = Input(shape=(self.latent_dim,))
        sequence = self.generator(z)

        self.discriminator.trainable = False
        valid = self.discriminator(sequence)

        self.combined = Model(z, valid)
        self.combined.compile(loss='binary_crossentropy', optimizer=self.optimizer)
        self.model = None
        self.input_shape = None
        self.output_shape = None
        self.note_range = None
        self.n_timesteps = None
        self.n_features = None
        self.pitch_names = None
        self.durations = None
        self.velocities = None

        self.frequency = 180 # set the frequency of the sine wave
        self.duration = 5 # set the duration of the sine wave in seconds
        self.sampling_rate = 44100 # set the sampling rate
        self.amplitude = 32767 # set the amplitude
        self.output_folder = "output" # set the output folder

    def build_discriminator(self):
        model = Sequential()
        model.add(Input(shape=(self.input_shape,)))
        model.add(Dense(64))
        model.add(LeakyReLU(alpha=0.01))
        model.add(Dropout(0.5))
        model.add(Dense(1, activation='sigmoid'))
        model.summary()
        sequence = Input(shape=(self.midi_data.shape[1], self.midi_data.shape[2]))
        validity = model(sequence)
        return Model(sequence, validity)

    def build_generator(self):
        model = Sequential()
        model.add(Conv2DTranspose(256, (5, 5), strides=(2, 2), padding='same', input_shape=(100, 1, 1)))
        model.add(BatchNormalization())
        model.add(LeakyReLU(alpha=0.01))
        model.add(Conv2DTranspose(128, (5, 5), strides=(2, 2), padding='same'))
        model.add(BatchNormalization())
        model.add(LeakyReLU(alpha=0.01))
        model.add(Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same'))
        model.add(BatchNormalization())
        model.add(LeakyReLU(alpha=0.01))
        model.add(Conv2DTranspose(32, (5, 5), strides=(2, 2), padding='same'))
        model.add(BatchNormalization())
        model.add(LeakyReLU(alpha=0.01))
        model.add(Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', activation='tanh'))
        model.summary()

        noise = Input(shape=(self.latent_dim,))
        sequence = model(noise)

        return Model(noise, sequence)
       
    def load_data(self, path):
        self.midi_data = pretty_midi.PrettyMIDI(path)
        notes = []
        for instrument in self.midi_data.instruments:
            if not instrument.is_drum:
                for n in instrument.notes:
                    notes.append([n.start, n.end, n.pitch])
        self.midi_data = np.array(notes)

    def train(self, epochs, batch_size=128):
        # Load and rescale the data
        self.load_data()

        X_train = self.midi_data / 127.0
        
        # Adversarial ground truths
        valid = np.ones((batch_size, 1))
        fake = np.zeros((batch_size, 1))
        
        for epoch in range(epochs):
            # -------------------------
            #  Train Discriminator
            # -------------------------

            # Select a random batch of note sequences
            idx = np.random.randint(0, X_train.shape[0], batch_size)
            sequences = X_train[idx]

            # Generate a batch of new note sequences
            noise = np.random.normal(0, 1, (batch_size, self.latent_dim))
            generated_seq = self.generator.predict(noise)

            # Train the discriminator
            d_loss_real = self.discriminator.train_on_batch(sequences, valid)
            d_loss_fake = self.discriminator.train_on_batch(generated_seq, fake)
            d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)

            # -------------------------
            #  Train Generator
            # -------------------------


            noise = np.random.normal(0, 1, (batch_size, self.latent_dim))
            y_gen = np.ones(self.batch_size)
            g_loss = self.combined.train_on_batch(noise, y_gen)
            

            # Train the generator (to have the discriminator label samples as valid)
            g_loss = self.combined.train_on_batch(noise, valid)

            # Print the progress and save into loss lists
            if epoch % 100 == 0:
                print ("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, d_loss[0], 100*d_loss[1], g_loss))

            dump(self.generator, "models/music/generator.joblib")
            dump(self.discriminator, "models/music/discriminator.joblib")
            dump(self.combined, "models/music/combined.joblib")

    def load_models(self, model_name):
        self.generator = load("models/music/generator.joblib")
        self.discriminator = load("models/music/discriminator.joblib")
        self.combined = load("models/music/combined.joblib")

    def generate_music(self, duration):
        # use the model to generate music
        notes = []
        for i in range(duration):
            # get a random seed from the dataset
            seed = np.random.randint(0, len(self.data) - 1)
            input_notes = self.data[seed]
            # use the model to predict the next note
            prediction = self.model.predict(input_notes)
            # convert the prediction to a note
            index = np.argmax(prediction)
            notes.append(self.int_to_note[index])
        return notes
    
    def generate_sine_wave(self):
        # generate the sine wave
        t = np.linspace(0, self.duration, int(self.sampling_rate * self.duration), endpoint=False)
        sine_wave = self.amplitude * np.sin(2 * np.pi * self.frequency * t)
        return sine_wave

    def save_to_folder(self):
        # create the output folder if it doesn't exist
        if not os.path.exists(self.output_folder):
            os.makedirs(self.output_folder)
        
        # save the sine wave to the output folder
        sine_wave = self.generate_sine_wave()
        wavfile.write(os.path.join(self.output_folder, "sine_wave.wav"), self.sampling_rate, sine_wave)

# create an instance of the Music class
music = Music()
# call the save_to_folder method to save the sine wave
music.save_to_folder() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling