import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.animation as animation
from scipy.interpolate import make_interp_spline, BSpline
from datetime import date
import glob
import os

data_date = date.today()
loss_dir = "Loss/"+str(data_date)+"/"
list_of_files = glob.glob(loss_dir+"*")
latest_file = max(list_of_files, key=os.path.getctime)
print("Current File : ", latest_file)

fig = plt.figure()
ax  = fig.add_subplot(1,1,1)
props = dict(boxstyle="square", facecolor='wheat', alpha=0.5)
data = np.load(latest_file)

def init():
  disp_data =round(0.3*len(data))
  ax.set_ylim(0,np.max(data[-disp_data:])*1.5)
  ax.set_xlim(0,len(data))

def animate(i):
  ax.clear()
  data = np.load(latest_file)
  x = np.arange(len(data))
  smooth_data = np.linspace(x.min(), x.max(), round(len(data)/5))
  print(smooth_data)
  disp_data =round(0.2*len(data))
  spl = make_interp_spline(x, data, k=3)
  y_smooth = spl(smooth_data)
  # y_smooth = spline(x, data, smooth_data)
  # last_data = "loss = %.6f" % data[-1]

  ax.set_ylim(0,np.max(data[-disp_data:])*2)
  ax.set_xlim(0,len(data))
  # ax.text(0.05, 0.9, last_data, transform=ax.transAxes, bbox=props)
  # ax.set_yscale('log')
  ax.title.set_text("Loss of "+str(latest_file))
  ax.plot(smooth_data, y_smooth, color='tomato', alpha=0.8)
  # ax.plot(data, color='tomato', alpha=0.8)

ani = animation.FuncAnimation(fig, animate, interval=20,  init_func=init)
# ani.save(filename='loss_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'], dpi=300, bitrate=1800, metadata=dict(artist='Nino'))
plt.show()


