import os
import sys
import numpy as np

# sys.path.append('E:\\wwj\\speechr\\meta learning\\meta-SR-master')
sys.path.append('/mnt/hgfs/wangwj/code/meta-SR-master')
import feat_extract.constants as c
import pickle  # For python3
from python_speech_features import *
# from feat_extract.voxceleb_wav_reader import read_voxceleb_structure


import scipy.io as sio
import scipy.io.wavfile





def extract_MFB(filename, mode):
    sr, audio = sio.wavfile.read(filename)

    # audio, sr = librosa.load(filename)
    features, energies = fbank(audio, samplerate=c.SAMPLE_RATE, nfilt=c.FILTER_BANK, winlen=0.025, winfunc=np.hamming)

    if c.USE_LOGSCALE:
        features = 20 * np.log10(np.maximum(features, 1e-5))

    if c.USE_DELTA:
        delta_1 = delta(features, N=1)
        delta_2 = delta(delta_1, N=1)

        features = normalize_frames(features, Scale=c.USE_SCALE)
        delta_1 = normalize_frames(delta_1, Scale=c.USE_SCALE)
        delta_2 = normalize_frames(delta_2, Scale=c.USE_SCALE)
        features = np.hstack([features, delta_1, delta_2])

    if c.USE_NORM:
        features = normalize_frames(features, Scale=c.USE_SCALE)
        total_features = features

    else:
        total_features = features


    speaker_label = 1  # set label as a folder name (recommended). Convert this to speaker index when training
    feat_and_label = {'feat': total_features, 'label': speaker_label}

    # if not os.path.exists('D:/code/wwj/RESNET-speaker-recognition/datasets/fftest'):
    #     os.makedirs('D:/code/wwj/RESNET-speaker-recognition/datasets/fftest')

    print(feat_and_label)



    # pickle.dump(feat_and_label, 'D:/code/wwj/RESNET-speaker-recognition/datasets/fftest')  # 序列化对象，将对象obj保存到文件file中



def normalize_frames(m, Scale=False):
    if Scale:
        return (m - np.mean(m, axis=0)) / (np.std(m, axis=0) + 2e-12)
    else:
        return (m - np.mean(m, axis=0))


class mode_error(Exception):
    def __str__(self):
        return "Wrong mode (type 'train' or 'test')"


def feat_extraction(dataroot_dir, mode):


    if (mode != 'train') and (mode != 'test'):
        raise mode_error

    extract_MFB('/mnt/hgfs/wangwj/code/VGG-Speaker-Recognition-master/datasets/ffmpeg_test/110.wav', mode=mode)
    # extract_MFB('D:/code/wwj/RESNET-speaker-recognition/datasets/voxceleb2/dev/wav/id00012/21Uxsk56VDQ/00002.wav', mode=mode)

    print("-" * 20 + " Feature extraction done " + "-" * 20)


if __name__ == '__main__':
    feat_extraction(dataroot_dir='/mnt/hgfs/wangwj/code/VGG-Speaker-Recognition-master/datasets/ffmpeg_test', mode='train')
    # feat_extraction(dataroot_dir='D:/code/wwj/RESNET-speaker-recognition/datasets/voxceleb2/dev/wav/id00012/21Uxsk56VDQ/', mode='train')