#python
"""This script reads in the fiat file with data, finds all manually segmented files and creates symlinks
to mfcc and lab files for training data set for HTK. Can be run with mfcc.bash
Arguments: name_of_mfcc_file (no extension) metadata_file
The metadata file is in fiat format; each line describes one utterance.
"""

import os
import sys
import errno

from gmisclib import die
from gmisclib import fiatio
from gmisclib import wavesurfer_lab as WS

import get_features as GF

RESP='/proj/aesop/proc'
MFCC='training/mfcc'
LAB='training/lab'

def convert_wav(fname):
	LONG_PHONE = 1.0	# seconds
	print 'convert', fname
	hdr, wslabs = WS.read(fname)
	Quantum = 1e-7
	Last_S_dur = 0.5
	htklabs=[]
	for (st, end, lab) in wslabs:
		st1 = int(round(st/Quantum))
		end1 = int(round(end/Quantum))
		htklabs.append((st1, end1, lab))
		if end-st > LONG_PHONE and lab in ['C', 'V', 'M']:
			die.warn("Unusually long %s in %s: %.3f - %.3f" % (lab, fname, st, end))
	if htklabs[-1][2] != 'S':
		htklabs.append((htklabs[-1][1], htklabs[-1][1]+int(round(Last_S_dur/Quantum)),
				'S'))
	return htklabs




def write_labels(labfile, labelinfo):
	for (st, end, lab) in labelinfo:
		print >> labfile, st, end, lab


def run(targetname):
	assert targetname and targetname in [ 'CC_voc_manual', 'CC_cons_manual' ]
	print "FNAME=", targetname
	metadatafile = open(sys.argv[2], 'r')
	mfcc = sys.argv[1]
	hdr, data, comments = fiatio.read(metadatafile)
	for line in data:
		d = os.path.join(RESP, line['d'], line['f'])
		print '# searching', d
		files=[name for name in os.listdir(d) if (name.endswith('lab') and targetname in name and not 'HTK' in name)]
		for fn in files:
			print '#\t', fn
			fname = '_'.join([line['subjectID'], os.path.basename(line['trans_real']).split('.')[0], fn.split('.')[0]])
			mfccname = os.path.join(MFCC, fname+'.mfcc')

			GF.link_mfcc_from_elsewhere(d, mfccname, dataid=mfcc)

			try:
				labfile = open(os.path.join(d, 'HTK_'+fn), 'w')
			except IOError, e:
				if e.errno == errno.ELOOP:
					os.remove(os.path.join(d, 'HTK_'+fn))
					labfile=open(os.path.join(d, 'HTK_'+fn), 'w')
			write_labels(labfile, convert_wav(os.path.join(d, fn)))
			GF.force_symlink(os.path.join(d, 'HTK_'+fn), os.path.join(LAB, fname+'.lab'))


if __name__ == '__main__':
	dataid = sys.argv[1]
	root = sys.argv[2]
	metadatafilenames = sys.argv[5:]
	whichpass = int(sys.argv[3])
	modeltype = sys.argv[4]
	run(dataid, metadatafilenames, modeltype, root, whichpass=whichpass)
