# Path: abkhazia/kaldi/path.py
# def kaldi_path():
#     """Return an environment for running the abkhazia recipes"""
#     env = os.environ
# 
#     env['LC_ALL'] = 'C'  # for expected sorting and joining behaviour
# 
#     kaldiroot = config.get('kaldi', 'kaldi-directory')
#     kaldisrc = os.path.join(kaldiroot, 'src')
# 
#     targets = ('bin', 'featbin', 'fgmmbin', 'fstbin', 'gmmbin',
#                'latbin', 'nnetbin', 'nnet2bin', 'sgmmbin', 'lmbin',
#                'kwsbin', 'ivectorbin', 'online2bin', 'sgmm2bin')
#     kaldibin = ':'.join((os.path.join(kaldisrc, target)
#                         for target in targets))
# 
#     fstbin = os.path.join(kaldiroot, 'tools', 'openfst', 'bin')
# 
#     platform = 'macosx' if os.uname()[0] == 'Darwin' else 'i686-m64'
#     lmbin = ':'.join([
#         os.path.join(kaldiroot, 'tools', 'irstlm', 'bin'),
#         os.path.join(kaldiroot, 'tools', 'srilm', 'bin'),
#         os.path.join(kaldiroot, 'tools', 'srilm', 'bin', platform),
#         os.path.join(kaldiroot, 'tools', 'sctk', 'bin')])
# 
#     if 'PATH' not in env:
#         # PATH isn't in the environment, should not occur
#         env['PATH'] = ':'.join([kaldibin, fstbin, lmbin])
#     else:
#         path = ':'.join([kaldibin, fstbin, lmbin])
#         if path not in env['PATH']:
#             env['PATH'] += ':' + path
# 
#     env['IRSTLM'] = os.path.join(kaldiroot, 'tools', 'irstlm')
# 
#     # was a bug -> error while loading shared libraries: libfstscript.so.1
#     fstlib = os.path.join(kaldiroot, 'tools', 'openfst', 'lib')
#     libfstscript = os.path.join(fstlib, 'libfstscript.so.1')
#     assert os.path.exists(libfstscript)
# 
#     if 'LD_LIBRARY_PATH' not in env:
#         env['LD_LIBRARY_PATH'] = fstlib
#     else:
#         if fstlib not in env['LD_LIBRARY_PATH']:
#             env['LD_LIBRARY_PATH'] += ':' + fstlib
# 
#     return env
# 
# Path: abkhazia/utils/path.py
# def list_directory(directory, abspath=False):
#     """Return os.listdir(directory) with .DS_Store filtered out"""
#     lsd = [e for e in os.listdir(directory) if e != '.DS_Store']
#     if abspath:
#         lsd = [os.path.abspath(os.path.join(directory, e)) for e in lsd]
#     return lsd


import os
import subprocess
from abkhazia.kaldi.path import kaldi_path
from abkhazia.utils.path import list_directory
    utt2spk = os.path.join(corpus_dir, 'utt2spk.txt')
    cmvn_scp = os.path.join(feat_dir, 'cmvn.scp')
    feats_scp = os.path.join(feat_dir, 'feats.scp')
    for f in (utt2spk, cmvn_scp, feats_scp):
        if not os.path.isfile(f):
            raise ValueError(f'file not found {f}')

    trans_files = [
        f for f in list_directory(trans_dir, abspath=True) if '/trans.' in f]
    if not trans_files:
        raise ValueError(f'no trans.* files in {trans_dir}')

    try:
        # merge all the trans_files in a single temporary file
        tmp = open(os.path.join(output_dir, 'trans'), 'w+b')
        for f in sorted(trans_files):
            tmp.write(open(f, 'rb').read())
        tmp.close()

        # commands to extract fMLLR features
        utt2spk = f'--utt2spk=ark:{utt2spk}'
        command1 = f'apply-cmvn {utt2spk} scp:{cmvn_scp} scp:{feats_scp} ark:-'
        command2 = f'add-deltas ark:- ark:-'
        command3 = (
            f'transform-feats {utt2spk} ark:{tmp.name} ark:- '
            f'ark,scp:{output_dir}/fmllr.ark,{output_dir}/fmllr.scp')
        command = ' | '.join((command1, command2, command3))

        # execute the command
        try:

# Path: abkhazia/kaldi/path.py
# def kaldi_path():
#     """Return an environment for running the abkhazia recipes"""
#     env = os.environ
# 
#     env['LC_ALL'] = 'C'  # for expected sorting and joining behaviour
# 
#     kaldiroot = config.get('kaldi', 'kaldi-directory')
#     kaldisrc = os.path.join(kaldiroot, 'src')
# 
#     targets = ('bin', 'featbin', 'fgmmbin', 'fstbin', 'gmmbin',
#                'latbin', 'nnetbin', 'nnet2bin', 'sgmmbin', 'lmbin',
#                'kwsbin', 'ivectorbin', 'online2bin', 'sgmm2bin')
#     kaldibin = ':'.join((os.path.join(kaldisrc, target)
#                         for target in targets))
# 
#     fstbin = os.path.join(kaldiroot, 'tools', 'openfst', 'bin')
# 
#     platform = 'macosx' if os.uname()[0] == 'Darwin' else 'i686-m64'
#     lmbin = ':'.join([
#         os.path.join(kaldiroot, 'tools', 'irstlm', 'bin'),
#         os.path.join(kaldiroot, 'tools', 'srilm', 'bin'),
#         os.path.join(kaldiroot, 'tools', 'srilm', 'bin', platform),
#         os.path.join(kaldiroot, 'tools', 'sctk', 'bin')])
# 
#     if 'PATH' not in env:
#         # PATH isn't in the environment, should not occur
#         env['PATH'] = ':'.join([kaldibin, fstbin, lmbin])
#     else:
#         path = ':'.join([kaldibin, fstbin, lmbin])
#         if path not in env['PATH']:
#             env['PATH'] += ':' + path
# 
#     env['IRSTLM'] = os.path.join(kaldiroot, 'tools', 'irstlm')
# 
#     # was a bug -> error while loading shared libraries: libfstscript.so.1
#     fstlib = os.path.join(kaldiroot, 'tools', 'openfst', 'lib')
#     libfstscript = os.path.join(fstlib, 'libfstscript.so.1')
#     assert os.path.exists(libfstscript)
# 
#     if 'LD_LIBRARY_PATH' not in env:
#         env['LD_LIBRARY_PATH'] = fstlib
#     else:
#         if fstlib not in env['LD_LIBRARY_PATH']:
#             env['LD_LIBRARY_PATH'] += ':' + fstlib
# 
#     return env
# 
# Path: abkhazia/utils/path.py
# def list_directory(directory, abspath=False):
#     """Return os.listdir(directory) with .DS_Store filtered out"""
#     lsd = [e for e in os.listdir(directory) if e != '.DS_Store']
#     if abspath:
#         lsd = [os.path.abspath(os.path.join(directory, e)) for e in lsd]
#     return lsd


# Path: abkhazia/features/extract_fmllr.py
import os
import subprocess
from abkhazia.kaldi.path import kaldi_path
from abkhazia.utils.path import list_directory

    utt2spk = os.path.join(corpus_dir, 'utt2spk.txt')
    cmvn_scp = os.path.join(feat_dir, 'cmvn.scp')
    feats_scp = os.path.join(feat_dir, 'feats.scp')
    for f in (utt2spk, cmvn_scp, feats_scp):
        if not os.path.isfile(f):
            raise ValueError(f'file not found {f}')

    trans_files = [
        f for f in list_directory(trans_dir, abspath=True) if '/trans.' in f]
    if not trans_files:
        raise ValueError(f'no trans.* files in {trans_dir}')

    try:
        # merge all the trans_files in a single temporary file
        tmp = open(os.path.join(output_dir, 'trans'), 'w+b')
        for f in sorted(trans_files):
            tmp.write(open(f, 'rb').read())
        tmp.close()

        # commands to extract fMLLR features
        utt2spk = f'--utt2spk=ark:{utt2spk}'
        command1 = f'apply-cmvn {utt2spk} scp:{cmvn_scp} scp:{feats_scp} ark:-'
        command2 = f'add-deltas ark:- ark:-'
        command3 = (
            f'transform-feats {utt2spk} ark:{tmp.name} ark:- '
            f'ark,scp:{output_dir}/fmllr.ark,{output_dir}/fmllr.scp')
        command = ' | '.join((command1, command2, command3))

        # execute the command
        try:

            subprocess.run(command, shell=True, check=True, env=kaldi_path())