# Copyright (c) 2011-2014 Kyle Gorman and Michael Wagner
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Command-line driver for the module
"""

import logging
import os
import sys
import yaml

from bisect import bisect
from shutil import copyfile
from textgrid import MLF

from corpus import Corpus
from aligner import Aligner
from archive import Archive
from utilities import splitname, resolve_opts, \
                       ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES

from argparse import ArgumentParser

DICTIONARY = "eng.dict"
MODEL = "eng.zip"

LOGGING_FMT = "%(message)s"


# parse arguments
argparser = ArgumentParser(prog="{} -m aligner".format(sys.executable),
                           description="Prosodylab-Aligner")
argparser.add_argument("-c", "--configuration",
                       help="config file")
argparser.add_argument("-d", "--dictionary", metavar="DICT", action="append",
                       help="dictionary file (default: {}) (can specify multiple)".format(DICTIONARY))
argparser.add_argument("-s", "--samplerate", type=int,
                       help="analysis samplerate (in Hz)")
argparser.add_argument("-e", "--epochs", type=int,
                       help="# of epochs of training per round")
input_group = argparser.add_argument_group()
input_group.add_argument("-r", "--read",
                         help="source for a precomputed acoustic model")
input_group.add_argument("-t", "--train",
                         help="directory containing data for training")
output_group = argparser.add_mutually_exclusive_group(required=True)
output_group.add_argument("-a", "--align",
                          help="directory containing data to align")
output_group.add_argument("-w", "--write",
                          help="destination for computed acoustic model")
verbosity_group = argparser.add_mutually_exclusive_group()
verbosity_group.add_argument("-v", "--verbose", action="store_true",
                             help="Verbose output")
verbosity_group.add_argument("-V", "--extra-verbose", action="store_true",
                             help="Even more verbose output")
args = argparser.parse_args()

# hack to allow proper override of default dictionary
if not args.dictionary:
    args.dictionary = [DICTIONARY]

# set up logging
loglevel = logging.WARNING
if args.extra_verbose:
    loglevel = logging.DEBUG
elif args.verbose:
    loglevel = logging.INFO
logging.basicConfig(format=LOGGING_FMT, level=loglevel)

# input: pick one
if args.train:
    if args.read:
        logging.error("Cannot train on persistent model.")
        exit(1)
    logging.info("Preparing corpus '{}'.".format(args.train))
    opts = resolve_opts(args)
    corpus = Corpus(args.train, opts)
    logging.info("Preparing aligner.")
    aligner = Aligner(opts)
    logging.info("Training aligner on corpus '{}'.".format(args.train))
    aligner.HTKbook_training_regime(corpus, opts["epochs"],
                                    flatstart=(args.read is None))
else:
    if not args.read:
        args.read = MODEL
    logging.info("Reading aligner from '{}'.".format(args.read))
    # warn about irrelevant flags
    if args.configuration:
        logging.warning("Ignoring config flag (-c/--configuration).")
        args.configuration = None
    if args.epochs:
        logging.warning("Ignoring epochs flag (-e/--epochs).")
    if args.samplerate:
        logging.warning("Ignoring samplerate flag (-s/--samplerate).")
        args.samplerate = None
    # create archive from -r argument
    archive = Archive(args.read)
    # read configuration file therefrom, and resolve options with it
    args.configuration = os.path.join(archive.dirname, CONFIG)
    opts = resolve_opts(args)
    # initialize aligner and set it to point to the archive data
    aligner = Aligner(opts)
    aligner.curdir = archive.dirname

# output: pick one
if args.align:
    # check to make sure we're not aligning on the training data
    if (not args.train) or (os.path.realpath(args.train) !=
                            os.path.realpath(args.align)):
        logging.info("Preparing corpus '{}'.".format(args.align))
        corpus = Corpus(args.align, opts)
    logging.info("Aligning corpus '{}'.".format(args.align))
    aligned = os.path.join(args.align, ALIGNED)
    scores = os.path.join(args.align, SCORES)
    aligner.align_and_score(corpus, aligned, scores)
    logging.debug("Wrote MLF file to '{}'.".format(aligned))
    logging.debug("Wrote likelihood scores to '{}'.".format(scores))
    logging.info("Writing TextGrids.")
    size = MLF(aligned).write(args.align)
    if not size:
        logging.error("No paths found!")
        exit(1)
    logging.debug("Wrote {} TextGrids.".format(size))
elif args.write:
    # create and populate archive
    (_, basename, _) = splitname(args.write)
    archive = Archive.empty(basename)
    archive.add(os.path.join(aligner.curdir, HMMDEFS))
    archive.add(os.path.join(aligner.curdir, MACROS))
    # whatever this is, it's not going to work once you move the data
    if "dictionary" in opts:
        del opts["dictionary"]
    with open(os.path.join(archive.dirname, CONFIG), "w") as sink:
        yaml.dump(opts, sink)
    (basename, _) = os.path.splitext(args.write)
    archive_path = os.path.relpath(archive.dump(basename))
    logging.info("Wrote aligner to '{}'.".format(archive_path))
# else unreachable

logging.info("Success!")

[((87, 0, 87, 55), 'logging.basicConfig', 'logging.basicConfig', (), '', False, 'import logging\n'), ((159, 0, 159, 24), 'logging.info', 'logging.info', ({(159, 13, 159, 23): '"""Success!"""'}, {}), "('Success!')", False, 'import logging\n'), ((95, 11, 95, 29), 'utilities.resolve_opts', 'resolve_opts', ({(95, 24, 95, 28): 'args'}, {}), '(args)', False, 'from utilities import splitname, resolve_opts, ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES\n'), ((96, 13, 96, 37), 'corpus.Corpus', 'Corpus', ({(96, 20, 96, 30): 'args.train', (96, 32, 96, 36): 'opts'}, {}), '(args.train, opts)', False, 'from corpus import Corpus\n'), ((97, 4, 97, 38), 'logging.info', 'logging.info', ({(97, 17, 97, 37): '"""Preparing aligner."""'}, {}), "('Preparing aligner.')", False, 'import logging\n'), ((98, 14, 98, 27), 'aligner.Aligner', 'Aligner', ({(98, 22, 98, 26): 'opts'}, {}), '(opts)', False, 'from aligner import Aligner\n'), ((116, 14, 116, 32), 'archive.Archive', 'Archive', ({(116, 22, 116, 31): 'args.read'}, {}), '(args.read)', False, 'from archive import Archive\n'), ((118, 25, 118, 62), 'os.path.join', 'os.path.join', ({(118, 38, 118, 53): 'archive.dirname', (118, 55, 118, 61): 'CONFIG'}, {}), '(archive.dirname, CONFIG)', False, 'import os\n'), ((119, 11, 119, 29), 'utilities.resolve_opts', 'resolve_opts', ({(119, 24, 119, 28): 'args'}, {}), '(args)', False, 'from utilities import splitname, resolve_opts, ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES\n'), ((121, 14, 121, 27), 'aligner.Aligner', 'Aligner', ({(121, 22, 121, 26): 'opts'}, {}), '(opts)', False, 'from aligner import Aligner\n'), ((132, 14, 132, 47), 'os.path.join', 'os.path.join', ({(132, 27, 132, 37): 'args.align', (132, 39, 132, 46): 'ALIGNED'}, {}), '(args.align, ALIGNED)', False, 'import os\n'), ((133, 13, 133, 45), 'os.path.join', 'os.path.join', ({(133, 26, 133, 36): 'args.align', (133, 38, 133, 44): 'SCORES'}, {}), '(args.align, SCORES)', False, 'import os\n'), ((137, 4, 137, 38), 'logging.info', 'logging.info', ({(137, 17, 137, 37): '"""Writing TextGrids."""'}, {}), "('Writing TextGrids.')", False, 'import logging\n'), ((92, 8, 92, 58), 'logging.error', 'logging.error', ({(92, 22, 92, 57): '"""Cannot train on persistent model."""'}, {}), "('Cannot train on persistent model.')", False, 'import logging\n'), ((108, 8, 108, 69), 'logging.warning', 'logging.warning', ({(108, 24, 108, 68): '"""Ignoring config flag (-c/--configuration)."""'}, {}), "('Ignoring config flag (-c/--configuration).')", False, 'import logging\n'), ((111, 8, 111, 62), 'logging.warning', 'logging.warning', ({(111, 24, 111, 61): '"""Ignoring epochs flag (-e/--epochs)."""'}, {}), "('Ignoring epochs flag (-e/--epochs).')", False, 'import logging\n'), ((113, 8, 113, 70), 'logging.warning', 'logging.warning', ({(113, 24, 113, 69): '"""Ignoring samplerate flag (-s/--samplerate)."""'}, {}), "('Ignoring samplerate flag (-s/--samplerate).')", False, 'import logging\n'), ((130, 17, 130, 41), 'corpus.Corpus', 'Corpus', ({(130, 24, 130, 34): 'args.align', (130, 36, 130, 40): 'opts'}, {}), '(args.align, opts)', False, 'from corpus import Corpus\n'), ((140, 8, 140, 40), 'logging.error', 'logging.error', ({(140, 22, 140, 39): '"""No paths found!"""'}, {}), "('No paths found!')", False, 'import logging\n'), ((145, 23, 145, 44), 'utilities.splitname', 'splitname', ({(145, 33, 145, 43): 'args.write'}, {}), '(args.write)', False, 'from utilities import splitname, resolve_opts, ALIGNED, CONFIG, HMMDEFS, MACROS, SCORES\n'), ((146, 14, 146, 37), 'archive.Archive.empty', 'Archive.empty', ({(146, 28, 146, 36): 'basename'}, {}), '(basename)', False, 'from archive import Archive\n'), ((154, 20, 154, 48), 'os.path.splitext', 'os.path.splitext', ({(154, 37, 154, 47): 'args.write'}, {}), '(args.write)', False, 'import os\n'), ((127, 28, 127, 56), 'os.path.realpath', 'os.path.realpath', ({(127, 45, 127, 55): 'args.train'}, {}), '(args.train)', False, 'import os\n'), ((128, 28, 128, 56), 'os.path.realpath', 'os.path.realpath', ({(128, 45, 128, 55): 'args.align'}, {}), '(args.align)', False, 'import os\n'), ((138, 11, 138, 23), 'textgrid.MLF', 'MLF', ({(138, 15, 138, 22): 'aligned'}, {}), '(aligned)', False, 'from textgrid import MLF\n'), ((147, 16, 147, 53), 'os.path.join', 'os.path.join', ({(147, 29, 147, 43): 'aligner.curdir', (147, 45, 147, 52): 'HMMDEFS'}, {}), '(aligner.curdir, HMMDEFS)', False, 'import os\n'), ((148, 16, 148, 52), 'os.path.join', 'os.path.join', ({(148, 29, 148, 43): 'aligner.curdir', (148, 45, 148, 51): 'MACROS'}, {}), '(aligner.curdir, MACROS)', False, 'import os\n'), ((153, 8, 153, 29), 'yaml.dump', 'yaml.dump', ({(153, 18, 153, 22): 'opts', (153, 24, 153, 28): 'sink'}, {}), '(opts, sink)', False, 'import yaml\n'), ((152, 14, 152, 51), 'os.path.join', 'os.path.join', ({(152, 27, 152, 42): 'archive.dirname', (152, 44, 152, 50): 'CONFIG'}, {}), '(archive.dirname, CONFIG)', False, 'import os\n')]