#!/usr/bin/env python3
# Copyright 2018 The Board of Trustees of the Leland Stanford Junior University
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Tiny wrapper for t2t-trainer that automatically loads genie.

Usage:
genie-evaluator
  --data_dir ./workdir
  --problem semparse_thingtalk_noquote
  --model genie_copy_transformer
  --hparams_set transformer_tiny_genie
  --output_dir ./workdir-small/model
  --t2t_usr_dir ./genie
  --eval_steps 10000000
  --eval_run_autoregressive
  --schedule evaluate
  --eval_on_test_data

"""

# Part of this code is derived from Tensor2Tensor, which is:
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import os
import fnmatch

from tensor2tensor.bin import t2t_trainer
import tensorflow as tf

import genieparser

flags = tf.flags
FLAGS = flags.FLAGS

LUI_prob = False
LUI_model = False

if 'semparse_thingtalk' in FLAGS.problem:
    LUI_prob = True
if "genie" in FLAGS.model:
    LUI_model = True
if LUI_prob != LUI_model:
    tf.logging.error('** Be advised that LUINetProblems should use LUINetModels while regular t2t.Problems should use t2t.Models **')
    sys.exit(1)

data_path = os.path.expanduser(FLAGS.data_dir)
test_dir = os.path.join(data_path, 'test_data')
if not os.path.exists(test_dir):
    os.makedirs(test_dir)

test_file = []
for file in os.listdir(data_path):
    if fnmatch.fnmatch(file, FLAGS.problem + '-' + 'test' + '*'):
        test_file.append(file)
if len(test_file) != 1:
    tf.logging.error('** Only having 1 test shard is allowed **')
    sys.exit(1)

try:
    os.rename(os.path.join(data_path, test_file[0]), os.path.join(test_dir, test_file[0].replace('test', 'dev')))
except OSError:
    pass

FLAGS.data_dir = test_dir


def main(argv):
    t2t_trainer.main(argv)

if __name__ == "__main__":
  tf.app.run()
