# -*- coding: utf-8 -*-
"""ML_package_audio.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1L7O8Nf30rMCNWnLpz8VWcFL2k9jvZTB4
"""

import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from keras import models
from keras.layers import Dense, Activation,Dropout
from keras.models import Sequential
from keras.utils import to_categorical

class audios:
  def load_features(data_path):
  
    myaudios = []
    for path, subdirs, files in os.walk(data_path):
      for name in files:
          myaudios.append(os.path.join(path, name))

    df = pd.DataFrame(columns=['feature'])
    i=0
    for index,y in enumerate(myaudios):
      X, sample_rate = librosa.load(y,sr=22050*2,mono=True)
      sample_rate = np.array(sample_rate)
      mfccs = np.mean(librosa.feature.mfcc(y=X, n_mfcc=13), axis=0)
      feature = mfccs
      df.loc[i] = [feature]
      i=i+1
      df_features = pd.DataFrame(df['feature'].values.tolist())
      df_features.reset_index(drop=True,inplace=True)
      df_features = df_features.fillna(0)

    return df_features

  def load_filename(data_path):
    labels=[]
    for filename in os.listdir(data_path):
      for i in range(len(os.listdir(data_path+'/'+filename))):
        labels.append(filename)

    df_labels=pd.DataFrame(labels)
    y=pd.get_dummies(df_labels)
    return y  

  def predict_categorical(x,y,epochs,x_test,y_test):

  #model
    model = Sequential()
    model.add(Dense(units=1024, activation='relu',use_bias=True, input_shape=(x.shape[1],)))
    model.add(Dense(units=1024, activation='relu',use_bias=True))
    model.add(Dense(units=512, activation='relu',use_bias=True))
    model.add(Dense(units=256, activation='relu',use_bias=True))
    model.add(Dense(units=y.shape[1], activation='softmax'))

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

    model.fit(x,y, epochs = epochs,batch_size=128)

    nn_acc = model.evaluate(x_test, y_test)
    y_pred=model.predict(x_test)

    pred_label = []
    for i in range(len(y_pred)):
      for j in range(len(y_pred[i])):
        if (y_pred[i,j]==max(y_pred[i])):
          pred_label.append(dict[j])

    return y_pred,nn_acc  

if __name__=="__main__":
  None