#!/usr/bin/python

import argparse
import os.path
import cPickle
import tempfile
import random
import hashlib

from features import mfcc
from features import logfbank
import scipy.io.wavfile as wav
from scikits.samplerate import resample
import numpy as n
from pydub import AudioSegment
from itertools import tee, izip
from annoy import AnnoyIndex

# We can't work with files that don't have this desired_samplerate
desired_samplerate = 44100
desired_channels = 2            # We expect this for corpus files
FORCE_RESAMPLE = False          # This can be really slow

#ANN_NTREES = 100
ANN_NTREES = 10
ANN_CANDIDATES = 10

IGNORE_SAME_FRAME = True

SECONDS_OUTPUT = 30.0
#SECONDS_OUTPUT = None

SEED = 0
random.seed(SEED)

def filename_to_mfcc_frames(filename, winlen, winstep):
    samplerate = desired_samplerate
    opts = {"samplerate": samplerate,
            "winlen": winlen,
            "winstep": winstep,
            "numcep": 13,
            "nfilt": 26,
            "nfft": 512
            }
    cache_filename = filename + "." + "_".join("%s=%s" % (k, v) for k, v in sorted(opts.items())) + ".pkl"

    if not os.path.exists(cache_filename):
        print "No cached version for %s" % filename
        mfcc_feat = perform_mfcc_on_filename(filename, opts)
        cPickle.dump(mfcc_feat, open(cache_filename, "wb"))
        print "\tWrote cache to %s" % cache_filename
    else:
#        print "\tReading cache from %s" % cache_filename
        mfcc_feat = cPickle.load(open(cache_filename, "rb"))
        if mfcc_feat is None:
            print "No MFCC for %s, perhaps has wrong samplerate" % filename