import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # no need to use gpu

# bazel build -c opt --copt=-mavx2 //kws_streaming/colab:colab_notebook.par
# ./bazel-bin/kws_streaming/colab/colab_notebook.par

"""
Explanation: Copyright 2022 Google LLC
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
https://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.
Visualize models training/validation loss
Prepare colab
End of explanation
"""


import tensorflow as tf
import os
import numpy as np
import math
import os.path
import sys
import matplotlib.pyplot as plt

tf = tf.compat.v1

"""
Explanation: Imports
End of explanation
"""


def read_log(fname, tag="accuracy"):
  eval_acc = []
  eval_loss = []
  try:
    for event in tf.train.summary_iterator(fname):
      for value in event.summary.value:
        if value.tag == tag:
          eval_acc.append(value.simple_value)
  except:
    print("stop parsing " + fname)

  return eval_acc, eval_loss

def scan_log(log_path):
  acc = []
  found = False
  if os.path.isdir(log_path):
    for file in os.listdir(log_path):
      if file.endswith(".gtc"):
        validation_file = os.path.join(log_path, file)
        acc = []
        if os.path.isfile(validation_file):
          if found:
            raise ValueError("found duplicate log")
          acc, _ = read_log(validation_file)
          found = True
  return acc

def train_eval_log(model_path):
  log_path_train = os.path.join(model_path, "logs", "train")
  acc_train = scan_log(log_path_train)
  log_path_val = os.path.join(model_path, "logs", "validation")
  acc_val = scan_log(log_path_val)
  return acc_train, acc_val

"""
Explanation: Utils
End of explanation
"""


# set path to trained models
model_path1 = "/tmp/kws_streaming/models2/att_mh_rnn/"
model_path2 = "/tmp/kws_streaming/models2/tc_resnet/"

acc_train1, acc_val1 = train_eval_log(model_path1)
acc_train2, acc_val2 = train_eval_log(model_path2)

"""
Explanation: Read logs
End of explanation
"""


# smoothing filter
window = np.hanning(70)
window = window/window.sum()

plt.figure(figsize=(20, 10))

data_val1 = np.convolve(window, acc_val1, mode='valid')
data_tr1 = np.convolve(window, acc_train1, mode='valid')

data_val2 = np.convolve(window, acc_val2, mode='valid')
data_tr2 = np.convolve(window, acc_train2, mode='valid')

ratio1 = (float)(len(data_tr1)) / len(data_val1)
ratio2 = (float)(len(data_tr2)) / len(data_val2)

xx1 = ratio1 * np.arange(len(data_val1))
plt_val1, = plt.plot(xx1, data_val1, label='val1')
plt_train1, = plt.plot(data_tr1, label='train1')

xx2 = ratio2 * np.arange(len(data_val2))
plt_val2, = plt.plot(xx2, data_val2, label='val2')
plt_train2, = plt.plot(data_tr2, label='train2')
plt.ylim(0.6, 1.0)
plt.legend(handles=[plt_val1, plt_train1, plt_val2, plt_train2])

plt.figure(figsize=(20, 10))
plt_val1, = plt.plot(xx1, data_val1, label='val1')

plt_val2, = plt.plot(xx2, data_val2, label='val2')
plt.ylim(0.90, 1.0)
plt.legend(handles=[plt_val1, plt_val2])
plt.show()

"""
Explanation: Plot logs and compare models training/validation loss
End of explanation
"""


