from __future__ import print_function
import scipy.io.wavfile as wavfile
import numpy as np
import os
from scipy import signal

import sys
import random

from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.initializations import normal, identity
from keras.optimizers import RMSprop
from keras.utils import np_utils
import numpy as np
np.random.seed(1337) 
from scipy.fftpack import fft
from scipy.signal import butter, lfilter
from sklearn.preprocessing import normalize

from keras.preprocessing import sequence
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM, SimpleRNN, GRU
from keras.models import model_from_json
import h5py

def challenge(filename):   
    model = model_from_json(open('fahad_features.json').read())
    model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
    model.load_weights('fahad_features.h5')
    rate, wf = wavfile.read(filename + ".wav")
    wf = signal.decimate(wf, 10)
    if len(wf) >= 8000:
          wf = wf[0:8000]
    else:
          wf = np.append(wf, np.zeros(8000 - len(wf)))
    wf = normalize(wf.reshape(1, -1)).reshape(-1)
    # d = signal.decimate(d,5)
    # d,cD = pywt.dwt(d,'db6')
    # point = np.array([d])
    # point = sequence.pad_sequences(point, maxlen=8000, truncating='pre') 
    features = np.zeros((15,1000))
    step_size = 500
    window_length = 1000 #try out different configs
    start_point = 0
    for i in range(15):
          segment = wf[start_point:start_point+window_length]
          segment = segment * np.hanning(window_length)
          segment.reshape(1,-1)
          nyquist = 0.5 * rate
          cutoff_freq = 4.0  # Hz
          w0, w1 = butter(5, cutoff_freq / nyquist, btype='low', analog=False)
          wf_low_pass = lfilter(w0, w1, segment)

          # FFT the filtered signal
          wf_low_pass_fft = np.abs(fft(wf_low_pass))
          wf_low_pass_fft = wf_low_pass_fft.reshape(-1)
          features[i] = np.array(wf_low_pass_fft)
          start_point += step_size
    point = np.array([features])
    predictions = model.predict_classes(point, batch_size=1, verbose=0)
    final_prediction = []
    for prediction in predictions:
        if prediction[0] >= 0.50:
            final_prediction.append(1)
        else:
            final_prediction.append(-1)
    print(prediction[0], final_prediction[0], filename) 

    f = open("answers.txt", "a")
    f.write(filename + "," + str(final_prediction[0])+"\n")
    f.close()
challenge(sys.argv[1])
