# -*- coding: utf-8 -*-

import pandas as pd  # 数据分析
import numpy as np  # 数据处理
import cv2
import tools as tl
from filterpy.kalman import KalmanFilter
from sklearn.utils.linear_assignment_ import linear_assignment
import time

# 数据和视频地址
video_file = 'video/144115194519432837_20170314_120930.mp4'
data_file = 'simple_data/data_70.csv'

# file = 'simple_data/complex.txt'
file = '144115194519432837_20170314_120930.mp4.txt'
# video_file = 'simple_data/in_one_1.mp4'
# data_file = 'simple_data/in_one_1.csv'

# video_file = 'simple_data/complex_1_75.mp4'
# data_file = 'simple_data/complex_1_75.csv'

# 读取数据和视频
data_final = pd.read_csv(data_file)
cap = cv2.VideoCapture(video_file)
# print data_final
# 读取视频第一帧
success,frame = cap.read()
cap_fps=cap.get(cv2.CAP_PROP_FPS)
cap_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
cap_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_0 = np.zeros((cap_width, cap_height, 3), np.int)

# 初始化检测框、帧数统计
track_window_data = [[0, 0, 0, 0]]*10
frame_count = 1
numframes = cap.get(7)

# 初始化数据驱使的检测框
data_flag = 0
data_number = 1
frame_cerrent = data_final['frame'][data_flag]
frame_next = data_final['frame'][data_flag + 1]
track_window_data[0] = [data_final['xmin'][data_flag],
                   data_final['ymin'][data_flag],
                   data_final['length'][data_flag],
                   data_final['height'][data_flag]]

# 扫描同一帧数的检测框
while (frame_cerrent == frame_next):
    data_flag = data_flag + 1
    track_window_data[data_number] = [data_final['xmin'][data_flag],
                                      data_final['ymin'][data_flag],
                                      data_final['length'][data_flag],
                                      data_final['height'][data_flag]]
    data_number = data_number + 1
    frame_next = data_final['frame'][data_flag + 1]

def iou(bb_test,bb_gt):
  """
  计算两个检测框的IOU（Intersection Over Union）检测评价函数，交并比
  检测框形式[x1,y1,x2,y2]
  """
  xx1 = np.maximum(bb_test[0], bb_gt[0])
  yy1 = np.maximum(bb_test[1], bb_gt[1])
  xx2 = np.minimum(bb_test[2], bb_gt[2])
  yy2 = np.minimum(bb_test[3], bb_gt[3])
  w = np.maximum(0., xx2 - xx1)
  h = np.maximum(0., yy2 - yy1)
  wh = w * h
  o = wh / ((bb_test[2]-bb_test[0])*(bb_test[3]-bb_test[1])
    + (bb_gt[2]-bb_gt[0])*(bb_gt[3]-bb_gt[1]) - wh)
  return(o)

def convert_bbox_to_z(bbox):
  """
  输入检测框[x1,y1,x2,y2]
  输出检测框[x,y,s,r] ：(x,y)为中心点坐标，s为面积，r为长宽比
  """
  w = bbox[2]-bbox[0]
  h = bbox[3]-bbox[1]
  x = bbox[0]+w/2.
  y = bbox[1]+h/2.
  s = w*h    #面积
  r = w/float(h)   #长宽比
  return np.array([x,y,s,r]).reshape((4,1))

def convert_x_to_bbox(x,score=None):
  """
  输入检测框[x,y,s,r]
  输出检测框[x1,y1,x2,y2]
  """
  w = np.sqrt(x[2]*x[3])
  h = x[2]/w
  if(score==None):
    return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.]).reshape((1,4))
  else:
    return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.,score]).reshape((1,5))

class KalmanBoxTracker(object):
  """
  个体跟踪目标检测框的内部状态
  """
  count = 0
  def __init__(self,bbox):
    """
    初始化检测框
    """
    #定义连续速度模型
    self.kf = KalmanFilter(dim_x=7, dim_z=4)
    self.kf.F = np.array([[1,0,0,0,1,0,0],[0,1,0,0,0,1,0],[0,0,1,0,0,0,1],[0,0,0,1,0,0,0],  [0,0,0,0,1,0,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,1]])
    self.kf.H = np.array([[1,0,0,0,0,0,0],[0,1,0,0,0,0,0],[0,0,1,0,0,0,0],[0,0,0,1,0,0,0]])

    self.kf.R[2:,2:] *= 10.
    self.kf.P[4:,4:] *= 1000. #给一个不可观测初始速度一个高不确定性
    self.kf.P *= 10.
    self.kf.Q[-1,-1] *= 0.01
    self.kf.Q[4:,4:] *= 0.01

    self.kf.x[:4] = convert_bbox_to_z(bbox)
    self.time_since_update = 0
    self.id = KalmanBoxTracker.count
    KalmanBoxTracker.count += 1
    self.history = []
    self.hits = 0
    self.hit_streak = 0
    self.age = 0

  def update(self,bbox):
    """

    根据检测结果更新速度状态
    """
    self.time_since_update = 0
    self.history = []
    self.hits += 1
    self.hit_streak += 1
    self.kf.update(convert_bbox_to_z(bbox))

  def predict(self):
    """
    预测速度状态
    """
    if((self.kf.x[6]+self.kf.x[2])<=0):
      self.kf.x[6] *= 0.0
    self.kf.predict()
    self.age += 1
    if(self.time_since_update>0):
      self.hit_streak = 0
    self.time_since_update += 1
    self.history.append(convert_x_to_bbox(self.kf.x))
    return self.history[-1]

  def get_state(self):
    """
    获取当前估计的检测框值[x1,y1,x2,y2]
    """
    return convert_x_to_bbox(self.kf.x)

def associate_detections_to_trackers(detections,trackers,iou_threshold = 0.3):
  """
  给跟踪对象分配检测框[x1,y1,x2,y2]

  返回3个列表：匹配、未匹配的检测框、未匹配的预测框
  """
  if(len(trackers)==0):
    return np.empty((0,2),dtype=int), np.arange(len(detections)), np.empty((0,5),dtype=int)
  iou_matrix = np.zeros((len(detections),len(trackers)),dtype=np.float32)

  for d,det in enumerate(detections):
    for t,trk in enumerate(trackers):
      iou_matrix[d,t] = iou(det,trk)
  matched_indices = linear_assignment(-iou_matrix)

  unmatched_detections = []
  for d,det in enumerate(detections):
    if(d not in matched_indices[:,0]):
      unmatched_detections.append(d)
  unmatched_trackers = []
  for t,trk in enumerate(trackers):
    if(t not in matched_indices[:,1]):
      unmatched_trackers.append(t)

  #根据低交并比值（low IOU）过滤匹配
  matches = []
  for m in matched_indices:
    if(iou_matrix[m[0],m[1]]<iou_threshold):
      unmatched_detections.append(m[0])
      unmatched_trackers.append(m[1])
    else:
      matches.append(m.reshape(1,2))
  if(len(matches)==0):
    matches = np.empty((0,2),dtype=int)
  else:
    matches = np.concatenate(matches,axis=0)

  return matches, np.array(unmatched_detections), np.array(unmatched_trackers)

class Sort(object):
  def __init__(self,max_age=18,min_hits=1.5):
    """
    设置关键参数
    """
    self.max_age = max_age
    self.min_hits = min_hits
    self.trackers = []
    self.frame_count = 0

  def update(self,dets):
    """
    参数:
      dets: 检测框列表，一个numpy队列[[x,y,w,h,label],[x,y,w,h,label],...]
    （该函数每帧调用一次，即使没有检测框校正）

    返回：
      目标框列表，一个numpy队列[[x,y,w,h,ID],[x,y,w,h,ID],...]
    （输入输出的队列大小不等）
    """
    self.frame_count += 1
    #根据检测获得预测
    trks = np.zeros((len(self.trackers),5))
    # kLine = np.zeros((len(self.trackers),15))
    to_del = []
    ret = []
    for t,trk in enumerate(trks):
      pos = self.trackers[t].predict()[0]
      trk[:] = [pos[0], pos[1], pos[2], pos[3], 0]
      if(np.any(np.isnan(pos))):
        to_del.append(t)
    trks = np.ma.compress_rows(np.ma.masked_invalid(trks))
    for t in reversed(to_del):
      self.trackers.pop(t)
    matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(dets,trks)

    #根据检测，更新以配对的
    for t,trk in enumerate(self.trackers):
      if(t not in unmatched_trks):
        d = matched[np.where(matched[:,1]==t)[0],0]
        trk.update(dets[d,:][0])

    #给未匹配的检测建立新Tracker
    for i in unmatched_dets:
        trk = KalmanBoxTracker(dets[i,:])
        self.trackers.append(trk)
        # kLine = ((trk[0] + ((trk[2] - 2 * d[0]) / 2), trk[1] + ((trk[3] - 2 * trk[1]) / 2)))
    i = len(self.trackers)
    for trk in reversed(self.trackers):
        d = trk.get_state()[0]
        if((trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits)):
          ret.append(np.concatenate((d,[trk.id+1])).reshape(1,-1)) # +1 as MOT benchmark requires positive
        i -= 1
        #删除寿命到期的Tracker
        if(trk.time_since_update > self.max_age):
          self.trackers.pop(i)
    if(len(ret)>0):
      return np.concatenate(ret)
    return np.empty((0,5))

# class KalmanLine(object):
#     def __init__(self, label):
#
#         self.label = label
#         self.lines = []

    # def getKalmanLine(no):
    #     kalmanLine = []
# 初始化Camshift算法驱使的检测框
cam_xmin = data_final['xmin'][0]
cam_ymin = data_final['ymin'][0]
cam_length = data_final['length'][0]-20
cam_height = data_final['height'][0]-40
track_window_cam = (cam_xmin, cam_ymin, cam_length, cam_height)
# print track_window_cam

# ROI-感兴趣区域-图像采集
roi = frame[cam_ymin:cam_ymin+cam_height, cam_xmin:cam_xmin+cam_length]
# cv2.imshow('test', roi)
# k = cv2.waitKey(0) & 0xff
hsv_roi =  cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)

# Setup the termination criteria, either 10 iteration or move by atleast 1 pt
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 1, 1 )

mot_tracker = Sort()
total_time = 0.0
colours = np.random.rand(128, 3)
seq = np.loadtxt(file, delimiter=' ', usecols=(0,1,2,3,6,7)).astype('float')
np.set_printoptions(suppress=True)
seq_dets = seq[seq[:, 5] > 0.7]
KalmanLine_1 = []
KalmanLine_2 = []
KalmanLine_3 = []
KalmanLine_4 = []
KalmanLine_5 = []
Kid_1 = 1
Kid_2 = 2
Kid_3 = 3
Kid_4 = 4
Kid_5 = 5
Kno_1 = Kno_2 = Kno_3 =Kno_4 = Kno_5 = 0

while(success):
    success, frame = cap.read()
    img = frame.copy()

    dets = seq_dets[seq_dets[:, 4] == frame_count, 0:4]
    dets[:, 2:4] += dets[:, 0:2]
    # dets.astype('int')

    start_time = time.time()
    trackers = mot_tracker.update(dets)
    cycle_time = time.time() - start_time
    total_time += cycle_time

    for d in trackers:
        # cv2.rectangle(img,(d[0],d[1]),(d[2]-d[0],d[3]-d[1]), (0, 255, 0), 2)
        d = d.astype(np.uint32)
        color = (colours[d[4] % 128, :]*127)
        cv2.rectangle(img, (d[0], d[1]), (d[2] - d[0], d[3] - d[1]),color, 2)
        cv2.putText(img, str(d[4]), (d[0], d[1] - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 2)
        for case in tl.switch(d[4]%5):
            if case(0):
                color1 = (colours[d[4] % 128, :] * 127)
                if Kno_1 == d[4]:
                    KalmanLine_1.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_1) - 1):
                    #     cv2.line(img, KalmanLine_1[i], KalmanLine_1[i + 1], color, 2)
                else:
                    Kno_1 = d[4]
                    KalmanLine_1 = []
                    KalmanLine_1.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_1) - 1):
                    #     cv2.line(img, KalmanLine_1[i], KalmanLine_1[i + 1], color, 2)
                break
            if case(1):
                color2 = (colours[d[4] % 128, :] * 127)
                if Kno_2 == d[4]:
                    KalmanLine_2.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_2) - 1):
                    #     cv2.line(img, KalmanLine_2[i], KalmanLine_2[i + 1], color, 2)
                else:
                    Kno_2 = d[4]
                    KalmanLine_2 = []
                    KalmanLine_2.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_2) - 1):
                    #     cv2.line(img, KalmanLine_2[i], KalmanLine_2[i + 1], color, 2)
                break
            if case(2):
                color3 = (colours[d[4] % 128, :] * 127)
                if Kno_3 == d[4]:
                    KalmanLine_3.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_3) - 1):
                    #     cv2.line(frame, KalmanLine_3[i], KalmanLine_3[i + 1], color, 2)
                else:
                    Kno_3 = d[4]
                    KalmanLine_3 = []
                    KalmanLine_3.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_3) - 1):
                    #     cv2.line(frame, KalmanLine_3[i], KalmanLine_3[i + 1], color, 2)
                break
            if case(3):
                color4 = (colours[d[4] % 128, :] * 127)
                if Kno_4 == d[4]:
                    KalmanLine_4.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_4) - 1):
                    #     cv2.line(frame, KalmanLine_4[i], KalmanLine_4[i + 1], color, 2)
                else:
                    Kno_4 = d[4]
                    KalmanLine_4 = []
                    KalmanLine_4.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_4) - 1):
                    #     cv2.line(frame, KalmanLine_4[i], KalmanLine_4[i + 1], color, 2)
                break
            if case(4):
                color5 = (colours[d[4] % 128, :] * 127)
                if Kno_5 == d[4]:
                    KalmanLine_5.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_5) - 1):
                    #     cv2.line(frame, KalmanLine_5[i], KalmanLine_5[i + 1], color, 2)
                else:
                    Kno_5 = d[4]
                    KalmanLine_5 = []
                    KalmanLine_5.append((int(d[0] + ((d[2] - 2 * d[0]) / 2)),int(d[1] + ((d[3] - 2 * d[1]) / 2))))
                    # for i in range(len(KalmanLine_5) - 1):
                    #     cv2.line(frame, KalmanLine_5[i], KalmanLine_5[i + 1], color, 2)
                break
        if len(KalmanLine_1) == 80:
            del KalmanLine_1[0]
        if len(KalmanLine_2) == 80:
            del KalmanLine_2[0]
        if len(KalmanLine_3) == 80:
            del KalmanLine_3[0]
        if len(KalmanLine_4) == 80:
            del KalmanLine_4[0]
        if len(KalmanLine_5) == 80:
            del KalmanLine_5[0]

        # 数据驱使的检测框
    # if frame_count == frame_cerrent:
    #     x1, y1, w1, h1 = track_window_data[0]
    #     cv2.rectangle(frame, (x1, y1), (x1 + w1, y1 + h1), (255, 0, 0), 2)
    #
    #     for case in tl.switch(data_number):
    #         # if case(1):
    #         #     cv2.imshow('TRACKING', frame)
    #         #     break
    #         if case(2):
    #             x2, y2, w2, h2 = track_window_data[1]
    #             cv2.rectangle(frame, (x2, y2), (x2 + w2, y2 + h2), (255, 0, 0), 2)
    #             # cv2.imshow('TRACKING', frame)
    #             break
    #         if case(3):
    #             x2, y2, w2, h2 = track_window_data[1]
    #             x3, y3, w3, h3 = track_window_data[2]
    #             cv2.rectangle(frame, (x2, y2), (x2 + w2, y2 + h2), (255, 0, 0), 2)
    #             cv2.rectangle(frame, (x3, y3), (x3 + w3, y3 + h3), (255, 0, 0), 2)
    #             # cv2.imshow('TRACKING', frame)
    #             break
    #         if case(4):
    #             x2, y2, w2, h2 = track_window_data[1]
    #             x3, y3, w3, h3 = track_window_data[2]
    #             x4, y4, w4, h4 = track_window_data[3]
    #             cv2.rectangle(frame, (x2, y2), (x2 + w2, y2 + h2), (255, 0, 0), 2)
    #             cv2.rectangle(frame, (x3, y3), (x3 + w3, y3 + h3), (255, 0, 0), 2)
    #             cv2.rectangle(frame, (x4, y4), (x4 + w4, y4 + h4), (255, 0, 0), 2)
    #             # cv2.imshow('TRACKING', frame)
    #             break
    #
    #     track_window_data = [[0, 0, 0, 0]] * 10
    #     data_flag = data_flag + 1
    #     data_number = 1
    #     frame_cerrent = data_final['frame'][data_flag]
    #     frame_next = data_final['frame'][data_flag + 1]
    #     track_window_data[0] = [data_final['xmin'][data_flag],
    #                             data_final['ymin'][data_flag],
    #                             data_final['length'][data_flag],
    #                             data_final['height'][data_flag]]
    #     while (frame_cerrent == frame_next):
    #         data_flag = data_flag + 1
    #         track_window_data[data_number] = [data_final['xmin'][data_flag],
    #                                           data_final['ymin'][data_flag],
    #                                           data_final['length'][data_flag],
    #                                           data_final['height'][data_flag]]
    #         data_number = data_number + 1
    #         frame_next = data_final['frame'][data_flag + 1]

    for i in range(len(KalmanLine_1) - 1):
        cv2.line(img, KalmanLine_1[i], KalmanLine_1[i + 1], color1, 2)
    for i in range(len(KalmanLine_2) - 1):
        cv2.line(img, KalmanLine_2[i], KalmanLine_2[i + 1], color2, 2)
    for i in range(len(KalmanLine_3) - 1):
        cv2.line(img, KalmanLine_3[i], KalmanLine_3[i + 1], color3, 2)
    for i in range(len(KalmanLine_4) - 1):
        cv2.line(img, KalmanLine_4[i], KalmanLine_4[i + 1], color4, 2)
    for i in range(len(KalmanLine_5) - 1):
        cv2.line(img, KalmanLine_5[i], KalmanLine_5[i + 1], color5, 2)

    cv2.putText(img, str('Tracking Mode'), (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
                0.8, (255, 0, 0), 2)
    cv2.putText(img, str('Frame:') + str(frame_count), (10, 60), cv2.FONT_HERSHEY_SIMPLEX,
                0.8, (255, 0, 0), 2)
    cv2.putText(frame, str('Original'), (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
                0.8, (255, 0, 0), 2)
    cv2.putText(frame, str('Frame:') + str(frame_count), (10, 60), cv2.FONT_HERSHEY_SIMPLEX,
                0.8, (255, 0, 0), 2)

    if len(trackers) != 0:
        cv2.imwrite("simple_data/video/img_" + str(frame_count) + ".png", img)
        cv2.imwrite("simple_data/video/frame_" + str(frame_count) + ".png", frame)

    # 键盘控制
    cv2.imshow('TRACKING', img)
    # cv2.imshow('Original',frame)
    k = cv2.waitKey(1) & 0xff
    for case in tl.switch(k):
        if case(ord('n')):
            k = cv2.waitKey(1000) & 0xff
            continue
        if case(ord(' ')):
            k = cv2.waitKey(0) & 0xff
            continue
        if case(ord('c')):
            cv2.imwrite(str(frame_count) + "_img.jpg", img)
            cv2.imwrite(str(frame_count) + "_frame.jpg", frame)
            print(chr(k))
            continue
        if case(27):
            break
        if case():
            continue
    if k == 27:
        break

    frame_count = frame_count + 1

cv2.destroyAllWindows()
cap.release()


# -*- coding: UTF-8 -*-

from django.shortcuts import render
from mainApp.models import SiteSetting, Item

def index(request):
    story_list = Item.objects.filter(page__name="index").order_by('order')
    site_settings = SiteSetting.objects.all().first()

    return render(request, 'index.html', {"story_list": story_list, "title": "Home", "site_settings": site_settings,
                                          "page": "index"})

def venue(request):
    story_list = Item.objects.filter(page__name="venue").order_by('order')
    site_settings = SiteSetting.objects.all().first()
    return render(request, 'venue.html', {"story_list": story_list, "title": "Venue", "site_settings": site_settings})

def author_instructions(request):
    site_settings = SiteSetting.objects.all().first()

    story_list = [{"headline": "Abstract Submission Information",
                  "id": "AbstractInformation",
                   "table_class":
                       "

All authors interested in submitting a paper for the conference should "
                       " submit a short abstract to for review, this should be around 300 words "
                       "in total and summarise the themes of the full paper. This should be "
                       "written in the 'Abstract' box at the bottom of the 'Upload Abstract'"
                       " page, along with all other required info.

"},

                    {"headline": "Speaker Information",
                  "id": "SpeakerInformation",
                   "table_class":
                       "

Presentations should be in MS PowerPoint or PDF format. Please keep the use"
                       " of video and audio to a minimum as it could prove problematic.
"
                       "
"
                       "
All presentations should be emailed to us a week before the conference. If authors wish"
                       " to make any changes to their presentations please let us know as soon as possible and send"
                       "the relevant files to us at least 24 hours before you are due to speak.
"
                       "
"
                       "
The timeslots allocated to presenters are 20min: 15 minutes for your presentation and a"
                       " further 5 minutes for questions from the audience. The session chairs will remind you when"
                       " your time has finished. Please keep these times in mind.
"
                       "
"
                       "
All speakers should be in the relevant room, in which their presentation will take"
                       " place, at least 5 minutes before their session starts.
"
                       "
"
                       "
Please note that speakers are not exempt from registration fees.

"},

                  {"headline": "Author Information",
                  "id": "AuthorInformation",
                   "table_class":
                       "

Please submit all papers by 6 June 2019 by emailing them to us. If you are worried "
                       "about making the deadline then please contact us, so that an extension can be arranged.
"
                       "
"
                       "
Here is the official template to use for all papers."
                       " This template can also be used for abstracts.
"
                       "
"
                       "
All papers should be submitted in PDF format and should not be numbered. There is no "
                       "specific page number requirement for papers, although most tend to be around the 8 "
                       "page mark.
"
                       "
"
                       "
In addition, you must also fill out and sign a Copyright Release form "
                       "(found here) and email a scanned copy of that to us, "
                       "so that your paper can be included in the Official Conference Proceedings.
"
                       "
"
                       "
Please note that authors are not exempt from registration fees. Any additional co-authors "
                       "that wish to attend the conference are subject to a discounted rate.

"},

                  {"headline": "Exhibitor Information",
                  "id": "ExhibitorInformation",
                   "table_class":
                       "

All exhibitors should arrive at the conference venue at least half an hour before the "
                       "conference starts on Day 1.
"
                       "
"
                       "
All material that exhibitors wish to display should be supplied by the exhibitor and "
                       "relevant delivery and collection services to the venue arranged.
"
                       "
"
                       "
Please let us know when delivery is scheduled, so that we can make sure to make venue "
                       "staff aware.
"
                       "
"
                       "
Should you want to bring heavy/bulky exhibits please let us know beforehand as this "
                       "may not be possible in all cases.
"
                       "
"
                       "
All exhibition packages include a free registration, so you can take part in conference "
                       "sessions. All breaks will take place in the exhibition room(s).

"},
                  ]

    return render(request, 'baseTemplates/infoPageBase.html', {"story_list": story_list,
                                                               "site_settings": site_settings}, )

def accomodation(request):
    site_settings = SiteSetting.objects.all().first()
    return render(request, 'accomodation.html', {"site_settings": site_settings})

def contactus(request):
    site_settings = SiteSetting.objects.all().first()
    return render(request, 'contactUs.html', {"site_settings": site_settings})

def otherconferences(request):
    site_settings = SiteSetting.objects.all().first()
    return render(request, 'otherConferences.html', {"site_settings": site_settings})

def travel(request):
    story_list = Item.objects.filter(page__name="travel").order_by('order')
    site_settings = SiteSetting.objects.all().first()
    return render(request, 'baseTemplates/infoPageBase.html', {"story_list": story_list, "title": "Travel",
                                                               "site_settings": site_settings})

def cookies(request):
    site_settings = SiteSetting.objects.all().first()
    return render(request, 'cookies.html', {"site_settings": site_settings})

def robots(request):
    return render(request, 'robots.txt')


#bl_info = {
#    "name": "Extension Add",
#    "author": "marvin.k.breuer",
#    "version": (0, 1, 0),
#    "blender": (2, 72, 0),
#    "location": "View3D > Toolbar",
#    "warning": "",
#    "description": "Toolkit Extension",
#    "wiki_url": "",
#    "category": "User Panel",
#}

import bpy
from bpy import *
# property group containing all properties for the gui in the panel
#Dropdown Arrow ### general display properties = arrow tooltips
class DropdownMetaTool_UV_Props(bpy.types.PropertyGroup):
    """
    Fake module like class
    bpy.context.window_manager.metawindowtool_uv
    """
    ### UV Unwrap Tools
    display_tab_unwrap = bpy.props.BoolProperty(name = "UV Tools", description = "Display UV Tools", default = True)
    display_tab_uvut = bpy.props.BoolProperty(name = "UV Utility", description = "Display UV Utility Tools", default = False)
    display_tab_uvsure = bpy.props.BoolProperty(name = "SureUVW", description = "Display SureUVW Tools", default = False)
    display_tab_unwrapset = bpy.props.BoolProperty(name = "UV Unwrap", description = "Display UV Unwrap Tools", default = False)
    display_tab_uvnext = bpy.props.BoolProperty(name = "TextureSpace / Freestyle", description = "Display TextureSpace / Freestyle Tools", default = False)

#############################################################
###----------------  UV Mapping  -------------------------###
###----------------  UV Mapping  -------------------------###
#############################################################

# Sub Location
class SubLoc_UVS():
    """UV Tools"""
    bl_category="META"
    #bl_region_type = 'TOOLS'
    bl_region_type = 'UI'
    bl_space_type = 'VIEW_3D'

    @classmethod
    def poll(cls, context):
        return context.scene.osc_uvs

## Sub Panel
class META_TAB_UVS(SubLoc_UVS, bpy.types.Panel):
    """UV Tool"""
    bl_idname = "meta.uvtools"
    bl_label = "[UV UNWRAP]"

    def draw(self, context):
        lt = context.window_manager.metawindowtool_uv
        wm = context.window_manager
        scn = context.scene
        obj = context.object
        scene = context.scene
        layout = self.layout

############################-------------------------------------------------------
#######  UV Mapping  #######-------------------------------------------------------
#######  UV Mapping  #######-------------------------------------------------------
############################-------------------------------------------------------

### Objectmode ###

        col = layout.column(align=True)

        obj = context
        if obj and obj.mode == 'OBJECT':

            if lt.display_tab_unwrap:
                box = layout.box()
                row = box.row()
                row.prop(lt, "display_tab_unwrap", text="", icon='TRIA_DOWN')
            else:
                box = layout.box()
                row = box.row()
                row.prop(lt, "display_tab_unwrap", text="", icon='TRIA_RIGHT')

            row.label("UvTools...")

            if lt.display_tab_unwrap:

                col = layout.column(align=True)
                box = col.column(align=True).box().column()
                col_top = box.column(align=True)

                row = col_top.row(align=True)
                row.operator("transform.translate", text ="Move Texture Space").texture_space = True

                row = col_top.row(align=True)
                row.operator("uv.uv_equalize" , text ="UV Equalize")

######  UV Utility  ######-------------------------------------------------
######  UV Utility  ######-------------------------------------------------

                if lt.display_tab_uvut:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_uvut", text="", icon='DISCLOSURE_TRI_DOWN_VEC')
                else:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_uvut", text="", icon='DISCLOSURE_TRI_RIGHT_VEC')

                row.label("UV Utility...")

                if lt.display_tab_uvut:

                    col = layout.column(align=True)
                    box = col.column(align=True).box().column()
                    col_top = box.column(align=True)

                    row = col_top.row(align=True)
                    row.operator("uvutil.change_index", text="Drop Active UV Back")

                    col_top = box.column(align=True)
                    row = col_top.row(align=True)
                    row.prop(scene, "UVTexRenderActive")

                    col_top = box.column(align=True)
                    row = col_top.row(align=True)
                    row.operator("uvutil.select_index", text="Select UVTexCoord")
                    row = col_top.row(align=True)
                    row.prop(scene, "UVTexIndex", text="UVTexCoord")

                    col_top = box.column(align=True)
                    row = col_top.row(align=True)
                    row.operator("uvutil.select_name", text="Select UV Name")
                    row = col_top.row(align=True)
                    row.prop(scene, "UVTexGetName", text="")

                    col_top = box.column(align=True)
                    row = col_top.row(align=True)
                    row.operator("uvutil.remove_active", text="Remove Active UV")

######  SureUVW  ######-------------------------------------------------
######  SureUVW  ######-------------------------------------------------

                if lt.display_tab_uvsure:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_uvsure", text="", icon='DISCLOSURE_TRI_DOWN_VEC')
                else:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_uvsure", text="", icon='DISCLOSURE_TRI_RIGHT_VEC')

                row.label("SureUVW...")

                if lt.display_tab_uvsure:

                    col = layout.column(align=True)
                    box = col.column(align=True).box().column()
                    col_top = box.column(align=True)

                    row = col_top.row(align=True)

                    row.label("Press this button first:")
                    row = col_top.row(align=True)
                    row.operator("object.sureuvw_operator",text="Show active texture on object").action='showtex'
                    row = col_top.row(align=True)
                    row.label("UVW Mapping:")
                    row = col_top.row(align=True)
                    row.operator("object.sureuvw_operator",text="UVW Box Map").action='box'
                    row = col_top.row(align=True)
                    row.operator("object.sureuvw_operator",text="Best Planar Map").action='bestplanar'
                    row = col_top.row(align=True)
                    row.label("1. Make Material With Raster Texture!")
                    row = col_top.row(align=True)
                    row.label("2. Set Texture Mapping Coords: UV!")
                    row = col_top.row(align=True)
                    row.label("3. Use Addon buttons")

#################################-------------------------------------------------------
#######  UV Mapping Edit  #######-------------------------------------------------------
#######  UV Mapping Edit  #######-------------------------------------------------------
#################################-------------------------------------------------------

### Editmode ###

        obj = context
        if obj and obj.mode == 'EDIT_MESH':

            if lt.display_tab_unwrap:
                box = layout.box()
                row = box.row()
                row.prop(lt, "display_tab_unwrap", text="", icon='TRIA_DOWN')
            else:
                box = layout.box()
                row = box.row()
                row.prop(lt, "display_tab_unwrap", text="", icon='TRIA_RIGHT')

            row.label("UVTools...")

            if lt.display_tab_unwrap:

                col = layout.column(align=True)
                box = col.column(align=True).box().column()
                col_top = box.column(align=True)

                row = col_top.row(align=True)

                row.operator("mesh.mark_seam").clear = False
                row.operator("mesh.mark_seam", text="Clear Seam").clear = True

                box = col.column(align=True).box().column()
                col_top = box.column(align=True)

                row = col_top.row(align=True)
                row.operator("uv.copy_uv")
                row.operator("uv.paste_uv")

                row = col_top.row(align=True)
                row.operator("uv.copy_uv_sel_seq","Copy UV Sel. Seq.")
                row.operator("uv.paste_uv_sel_seq","Paste UV Sel. Seq.")

                row = col_top.row(align=True)
                row.menu("uv.copy_uv_map","Copy UV Map")
                row.menu("uv.paste_uv_map","Paste UV Map")

                box = col.column(align=True).box().column()
                col_top = box.column(align=True)

                row = col_top.row(align=True)
                row.alignment = 'CENTER'
                row.operator("uv.reproject_image", text ="Reproject Image")

######  Unwrap  ######-------------------------------------------------
######  Unwrap  ######-------------------------------------------------

                if lt.display_tab_unwrapset:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_unwrapset", text="", icon='DISCLOSURE_TRI_DOWN_VEC')
                else:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_unwrapset", text="", icon='DISCLOSURE_TRI_RIGHT_VEC')

                row.label("Unwrap...")

                if lt.display_tab_unwrapset:

                    col = layout.column(align=True)
                    box = col.column(align=True).box().column()
                    col_top = box.column(align=True)

                    row = col_top.row(align=True)
                    row.operator("uv.unwrap", text="Unwrap")
                    row.operator("uv.reset",text="Reset")

                    row = col_top.row(align=True)
                    row.operator("uv.smart_project", text="Smart UV Project")

                    row = col_top.row(align=True)
                    row.operator("uv.lightmap_pack", text="Lightmap Pack")

                    row = col_top.row(align=True)
                    row.operator("uv.follow_active_quads", text="Follow Active Quads")

                    box = col.column(align=True).box().column()
                    col_top = box.column(align=True)

                    row = col_top.row(align=True)
                    row.operator("uv.cube_project", text="Cube Project")

                    row = col_top.row(align=True)
                    row.operator("uv.cylinder_project", text="Cylinder Project")

                    row = col_top.row(align=True)
                    row.operator("uv.sphere_project", text="Sphere Project")

                    row = col_top.row(align=True)
                    row.operator("uv.tube_uv_unwrap", text="Tube Project")

                    box = col.column(align=True).box().column()
                    col_top = box.column(align=True)

                    row = col_top.row(align=True)
                    row.operator("uv.project_from_view", text="Project from View").scale_to_bounds = False

                    row = col_top.row(align=True)
                    row.operator("uv.project_from_view", text="Project from View > Bounds").scale_to_bounds = True

######  TexSpace / Freestyle  ######-------------------------------------------------
######  TexSpace / Freestyle  ######-------------------------------------------------

                if lt.display_tab_uvnext:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_uvnext", text="", icon='DISCLOSURE_TRI_DOWN_VEC')
                else:
                    box = layout.box()
                    row = box.row()
                    row.prop(lt, "display_tab_uvnext", text="", icon='DISCLOSURE_TRI_RIGHT_VEC')

                row.label("TexSpace... / Freestyle")

                if lt.display_tab_uvnext:

                    col = layout.column(align=True)
                    box = col.column(align=True).box().column()
                    col_top = box.column(align=True)

                    row = col_top.row(align=True)
                    row.label(text="Texture Space:")

                    row = col_top.row(align=True)
                    row.operator("transform.translate", text ="Move").texture_space = True
                    row.operator("mesh.mark_seam", text="Scale").clear = True

                    col_top = box.column(align=True)
                    row = col_top.row(align=True)
                    row.label(text="Freestyle:")

                    row = col_top.row(align=True)
                    row.operator("mesh.mark_freestyle_face", text="Mark Face").clear=False
                    row.operator("mesh.mark_freestyle_face", text="Clear Face").clear=True

############------------############
############  REGISTER  ############
############------------############

def register():
    bpy.utils.register_class(META_TAB_UVS)
    bpy.utils.register_class(DropdownMetaTool_UV_Props)
    bpy.types.WindowManager.metawindowtool_uv = bpy.props.PointerProperty(type = DropdownMetaTool_UV_Props)

def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()


from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import poluchka

urlpatterns = patterns('',
                       #            url(r'^polls/', include('polls.urls')),
                       #           url(r'^fin/', include('finances.urls')),
                       url(r'^buh/', include('poluchka.urls')),
                       (r'^ajax_filtered_fields/',
                        include('ajax_filtered_fields.urls')),
                       url(r'^chained/', include('chained_selects.urls')),
                       # Examples:
                       # url(r'^$', 'mydj.views.home', name='home'),
                       # url(r'^mydj/', include('mydj.foo.urls')),

                       # Uncomment the admin/doc line below to enable admin documentation:
                       # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

                       # Uncomment the next line to enable the admin:
                       url(r'^admin/', include(admin.site.urls)),
                       url(
                           r'^admin/jsi18n', 'django.views.i18n.javascript_catalog',
                       name='jsi18n'),  # hack to use admin form widgets
                       url(r'^admin/poluchka/', include(poluchka.urls)),
                       )


import datetime
import os

from sqlalchemy import (Column, DateTime, ForeignKey, Integer, String,
                        UniqueConstraint, all_, or_)
from sqlalchemy.orm import Query, Session

from . import commons
from .team import Team

class Upload(commons.base):
    __tablename__ = 'TblUpload'
    upload_id = Column('UploadId', Integer, primary_key=True,
                       autoincrement='ignore_fk')
    team_id = Column('TeamId', Integer, ForeignKey(
        'TblTeam.TeamId', ondelete='CASCADE'))
    name = Column('AudioName', String(50))
    upload_time = Column('Time', DateTime, default=datetime.datetime.now())
    duration = Column('Duration', Integer)
    description = Column('Description', String(150))
    status = Column('Status', String)
    speaker = Column('speakers', Integer, default=0)
    __table_args__ = (UniqueConstraint(
        'TeamId', 'AudioName', name='unique_constraint'),)

    @staticmethod
    def get(id):
        sess = Session(bind=commons.engine)
        row = sess.query(Upload).filter_by(upload_id=id).first()
        sess.close()
        return row

    @staticmethod
    def add_new(source: str, group, date, default_date, duration, description, status, speakers):
        if not speakers:
            speakers = "0"
        sess = Session(bind=commons.engine)
        tree = os.path.split(source)
        team_number = Team.add_if_needed(group)
        if date == default_date:
            added = Upload(name=tree[-1], team_id=team_number,
                               duration=duration, description=description, status=status, speaker=int(speakers))
        else:
            added = Upload(name=tree[-1], team_id=team_number,
                               upload_time=date, duration=duration, description=description, status=status,  speaker=int(speakers))
        sess.add(added)
        sess.commit()
        sess.close()
        filerow = sess.query(Upload).filter_by(
            name=tree[-1], team_id=team_number).first()
        return filerow.upload_id

    def update_upload(upload):
        sess = Session(bind=commons.engine)
        edit = sess.query(Upload).filter_by(upload_id=upload.upload_id).first()
        edit.name = upload.name
        edit.team_id = upload.team_id
        edit.duration = upload.duration
        edit.description = upload.description
        edit.upload_time = upload.upload_time
        if edit.speaker != upload.speaker:
            edit.status = '1'
            edit.speaker = upload.speaker
        sess.commit()
        sess.close()

    @staticmethod
    def update_status_by_id(filename: int, value=1):
        sess = Session(bind=commons.engine)
        edit = sess.query(Upload).filter_by(upload_id=filename).first()
        edit.status = value
        sess.commit()
        sess.close()

    @staticmethod
    def get_all(offset, size):
        sess = Session(bind=commons.engine)
        all = sess.query(Upload).filter(
            Upload.status.isnot("0")).offset(offset).limit(size)
        sess.close()
        return all

    @staticmethod
    def get_count():
        sess = Session(bind=commons.engine)
        count = sess.query(Upload).filter(
            Upload.status.isnot("0")).count()
        sess.close()
        return count

    @staticmethod
    def delete_by_id(id):
        sess = Session(bind=commons.engine)
        find = sess.query(Upload).filter_by(upload_id=id).first()
        sess.delete(find)
        sess.commit()
        sess.close()

    @staticmethod
    def get_by(team_or_name, size):
        sess = Session(bind=commons.engine)
        teams=sess.query(Team.team_id).filter(Team.team_name.ilike("%{0}%".format(team_or_name))).subquery()
        results = sess.query(Upload).filter(
            or_(
                Upload.name.ilike("%{0}%".format(team_or_name)),
                Upload.team_id.in_(teams)
            )
        ).limit(size)
        sess.close()
        return results

    @staticmethod
    def get_by_id(id):
        sess = Session(bind=commons.engine)
        result = sess.query(Upload).filter_by(upload_id=id).first()
        sess.close()
        return result

    @staticmethod
    def get_by_status(stat=1):
        """
        defaults to getting on single instance of copied and unprocessed element
        """
        sess = Session(bind=commons.engine)
        copied = sess.query(Upload).filter_by(status=stat).first()
        sess.close()
        return copied


from benchbuild.utils.wrapping import wrap
from benchbuild.projects.benchbuild.group import BenchBuildGroup
from benchbuild.settings import CFG
from benchbuild.utils.compiler import lt_clang, lt_clang_cxx
from benchbuild.utils.downloader import Wget
from benchbuild.utils.run import run

from plumbum import local
from benchbuild.utils.cmd import make, tar

from os import path

class MCrypt(BenchBuildGroup):
    """ MCrypt benchmark """

    NAME = 'mcrypt'
    DOMAIN = 'encryption'
    VERSION = '2.6.8'

    src_dir = "mcrypt-{0}".format(VERSION)
    SRC_FILE = src_dir + ".tar.gz"
    src_uri = "http://sourceforge.net/projects/mcrypt/files/MCrypt/{0}" \
        .format(VERSION) + SRC_FILE

    libmcrypt_dir = "libmcrypt-2.5.8"
    libmcrypt_file = libmcrypt_dir + ".tar.gz"
    libmcrypt_uri = "http://sourceforge.net/projects/mcrypt/files/Libmcrypt/2.5.8/" + \
        libmcrypt_file

    mhash_dir = "mhash-0.9.9.9"
    mhash_file = mhash_dir + ".tar.gz"
    mhash_uri = "http://sourceforge.net/projects/mhash/files/mhash/0.9.9.9/" + \
        mhash_file

    def download(self):
        Wget(self.src_uri, self.SRC_FILE)
        tar('xfz', self.SRC_FILE)

        Wget(self.libmcrypt_uri, self.libmcrypt_file)
        tar('xfz', self.libmcrypt_file)

        Wget(self.mhash_uri, self.mhash_file)
        tar('xfz', self.mhash_file)

    def configure(self):
        mcrypt_dir = self.src_dir
        mhash_dir = self.mhash_dir
        libmcrypt_dir = self.libmcrypt_dir

        # Build mhash dependency
        with local.cwd(mhash_dir):
            configure = local["./configure"]
            with local.env(CC=lt_clang(self.cflags, self.ldflags,
                                       self.compiler_extension),
                           CXX=lt_clang_cxx(self.cflags, self.ldflags,
                                            self.compiler_extension)):
                run(configure["--prefix=" + self.builddir])
                run(make["-j", CFG["jobs"], "install"])

        # Builder libmcrypt dependency
        with local.cwd(libmcrypt_dir):
            configure = local["./configure"]
            with local.env(CC=lt_clang(self.cflags, self.ldflags,
                                       self.compiler_extension),
                           CXX=lt_clang_cxx(self.cflags, self.ldflags,
                                            self.compiler_extension)):
                run(configure["--prefix=" + self.builddir])
                run(make["-j", CFG["jobs"], "install"])

        with local.cwd(mcrypt_dir):
            configure = local["./configure"]
            with local.env(CC=lt_clang(self.cflags, self.ldflags,
                                       self.compiler_extension),
                           CXX=lt_clang_cxx(self.cflags, self.ldflags,
                                            self.compiler_extension),
                           LD_LIBRARY_PATH=path.join(self.builddir, "lib") +
                           ":" + CFG["ld_library_path"],
                           LDFLAGS="-L" + path.join(self.builddir, "lib"),
                           CFLAGS="-I" + path.join(self.builddir, "include")):
                run(configure["--disable-dependency-tracking",
                              "--enable-static", "--disable-shared",
                              "--with-libmcrypt=" + self.builddir,
                              "--with-libmhash=" + self.builddir])

    def build(self):
        with local.cwd(self.src_dir):
            run(make["-j", CFG["jobs"]])

    def run_tests(self, experiment, run):
        mcrypt_dir = path.join(self.src_dir, "src", ".libs")
        aestest = wrap(path.join(mcrypt_dir, "lt-aestest"), experiment)
        run(aestest)
        ciphertest = wrap(path.join(mcrypt_dir, "lt-ciphertest"), experiment)
        run(ciphertest)


from flask import Flask, request, jsonify
from flask_marshmallow import Marshmallow
import requests

order = Flask(__name__)

Order_IP = '192.168.1.115'          #second order server(host)
Cat_IP = '192.168.1.114:5000'       #second catalog server

@order.route('/buy/<id>' ,methods=['POST','GET'])   #received buy request
def get_quantity(id):
    request = 'http://' + Cat_IP + '/quantity/' + id        #generating the quantity request
    quantity = int(requests.get(request).content)           #sending a request to catalog to server to know the quantity of the book
    if quantity > 0:                                        #chacks if the ammount if sufficient
        request = 'http://' + Cat_IP + '/update/' + id      #generating the update request
        requests.get(request)                               #sending the request the catalog server
        return 'The book has been purchased successfully'   #return response to front-end server
    else:
        return 'This book is out of stock'                  #return response to front-end server

if __name__ == "__main__":
    order.run(host = Order_IP)
    order.run(debug=True)


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from os import path
import math

plt.style.use('fivethirtyeight')
sns.set(style="ticks", color_codes=True, rc={"lines.linewidth": 2.5})
sns.set(font_scale=2.5)

nchain_filenames = [    "OldResults/Robots/AntBulletEnv",
                        "OldResults/RobotsGen/AntBulletEnv",
                        "OldResults/RobotsExtremeGen/AntBulletEnv",
                        "OldResults/Robots/InvertedDoublePendulumBulletEnv",
                        "OldResults/RobotsGen/InvertedDoublePendulumBulletEnv",
                        "OldResults/RobotsExtremeGen/InvertedDoublePendulumBulletEnv"
                    ]

# HalfCheetahBulletEnv
# HopperBulletEnv

NUM_RESAMPLES = 100

mirl_tags = [   [2.0],
                [2.0],
                [2.0],
                [2.0],
                [2.0],
                [2.0]]
mirl_env_strings = []
for env in mirl_tags:
    env_tags = []
    for tag in env:
        env_tags.append(str(tag).replace(".", "p"))
    mirl_env_strings.append(env_tags)

clac_tags = [   [0.025],
                [0.025],
                [0.025],
                [2.0],
                [2.0],
                [2.0]]
clac_env_strings = []
for env in clac_tags:
    env_tags = []
    for tag in env:
        env_tags.append(str(tag).replace(".", "p"))
    clac_env_strings.append(env_tags)

sac_tags = [    [0.04],
                [0.04],
                [0.04],
                [2.0],
                [2.0],
                [2.0]]

sac_env_strings = []
for env in sac_tags:
    env_tags = []
    for tag in env:
        env_tags.append(str(tag).replace(".", "p"))
    sac_env_strings.append(env_tags)

All_Data = pd.DataFrame()
ROUNDING_VALUE = -3

agents = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15,16,17,18,19,20]
print(agents)

for index, nchain_filename in enumerate(nchain_filenames):
    clac_tag_strings = clac_env_strings[index]
    for tag in clac_tag_strings:
        for agent_id in agents:
            for resample_num in range(NUM_RESAMPLES):

                clac_model_name = "CLAC" + "_" + str(tag) + "_" + str(agent_id) + "_" + str(resample_num)
                clac_model_file = nchain_filename + "/results/" + clac_model_name + ".pkl"

                if(not path.exists(clac_model_file)):
                    continue

                clac_data = pd.read_pickle(clac_model_file)

                if(clac_data.empty):
                    continue

                #clac_data = clac_data.iloc[-1:]
                clac_data["Resample"] = resample_num
                clac_data["Resample"] = math.ceil(resample_num / 2.) * 2  # resample_num
                clac_data["Environment"] = nchain_filename
                clac_data["Timestep"] = clac_data["Timestep"].astype(float).round(ROUNDING_VALUE)
                clac_data.loc[clac_data['Model'].str.contains('CLAC'), 'Model'] = 'CLAC'

                All_Data = All_Data.append(clac_data, sort="full")

    sac_tag_strings = sac_env_strings[index]
    for tag in sac_tag_strings:
        for agent_id in agents:
            for resample_num in range(NUM_RESAMPLES):

                sac_model_name = "SAC" + "_" + str(tag) + "_" + str(agent_id) + "_" + str(resample_num)
                sac_model_file = nchain_filename +  "/results/" + sac_model_name + ".pkl"

                if(not path.exists(sac_model_file)):
                    continue

                sac_data = pd.read_pickle(sac_model_file)

                if(sac_data.empty):
                    continue

                #sac_data = sac_data.iloc[-1:]
                sac_data["Resample"] = resample_num
                sac_data["Resample"] = math.ceil(resample_num / 2.) * 2 # resample_num
                sac_data["Environment"] = nchain_filename
                sac_data["Timestep"] = sac_data["Timestep"].astype(float).round(ROUNDING_VALUE)
                sac_data.loc[sac_data['Model'].str.contains('SAC'), 'Model'] = 'SAC'

                All_Data = All_Data.append(sac_data, sort="full")

    mirl_tag_strings = mirl_env_strings[index]
    for tag in mirl_tag_strings:
        for agent_id in agents:
            for resample_num in range(NUM_RESAMPLES):

                mirl_model_name = "MIRL" + "_" + str(tag) + "_" + str(agent_id) + "_" + str(resample_num)
                mirl_model_file = nchain_filename + "/results/" + mirl_model_name + ".pkl"

                if(not path.exists(mirl_model_file)):
                    continue

                mirl_data = pd.read_pickle(mirl_model_file)

                if(mirl_data.empty):
                    continue

                #clac_data = clac_data.iloc[-1:]
                mirl_data["Resample"] = resample_num
                mirl_data["Resample"] = math.ceil(resample_num / 2.) * 2  # resample_num
                mirl_data["Environment"] = nchain_filename
                mirl_data["Timestep"] = mirl_data["Timestep"].astype(float).round(ROUNDING_VALUE)
                mirl_data.loc[mirl_data['Model'].str.contains('CLAC'), 'Model'] = 'MIRL'

                All_Data = All_Data.append(mirl_data, sort="full")

print("Done Loading Results")
print(All_Data)
#print(clac_data.loc[clac_data['Model'].str.contains('MIRL'), 'Model'])

Normal_Ant = All_Data.loc[All_Data["Environment"] == nchain_filenames[0]]
Gen_Ant = All_Data.loc[All_Data["Environment"] == nchain_filenames[1]]
Ext_Ant = All_Data.loc[All_Data["Environment"] == nchain_filenames[2]]

clac_ant = Normal_Ant.loc[Normal_Ant["Model"] == "CLAC"]
sac_ant = Normal_Ant.loc[Normal_Ant["Model"] == "SAC"]
mirl_ant = Normal_Ant.loc[Normal_Ant["Model"] == "MIRL"]

Normal_Walker = All_Data.loc[All_Data["Environment"] == nchain_filenames[3]]
Gen_Walker = All_Data.loc[All_Data["Environment"] == nchain_filenames[4]]
Ext_Walker = All_Data.loc[All_Data["Environment"] == nchain_filenames[5]]

Normal_Walker = Normal_Walker.loc[Normal_Walker["Timestep"] < 50000]
Gen_Walker = Gen_Walker.loc[Gen_Walker["Resample"] < 50]
Ext_Walker = Ext_Walker.loc[Ext_Walker["Resample"] < 50]

clac_walker = Normal_Walker.loc[Normal_Walker["Model"] == "CLAC"]
sac_walker = Normal_Walker.loc[Normal_Walker["Model"] == "SAC"]
mirl_walker = Normal_Walker.loc[Normal_Walker["Model"] == "MIRL"]

fig, axes = plt.subplots(2, 3 , sharey='row')
Ant_axes, Walker_axes = axes

#InvertedPendulumBulletEnv_Data_0 = All_Data.loc[All_Data["Resample"] == 0]
#InvertedPendulumBulletEnv_Data_1 = All_Data.loc[All_Data["Resample"] == NUM_RESAMPLES - 1]

sac_pal = ["blue"]
clac_pal = ["orange"]

"""ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Coefficient", legend="full", ci=99, data=clac_ant, ax=Ant_axes[0])
ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Coefficient", legend="full", ci=99, data=sac_ant, ax=Ant_axes[1])
ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Coefficient", legend="full", ci=99, data=mirl_ant, ax=Ant_axes[2])

ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Coefficient", legend="full", ci=99, data=clac_walker, ax=Walker_axes[0])
ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Coefficient", legend="full", ci=99, data=sac_walker, ax=Walker_axes[1])
ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Coefficient", legend="full", ci=99, data=mirl_walker, ax=Walker_axes[2])
"""

ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Model", legend="full", ci="sd", data=Normal_Ant, ax=Ant_axes[0])
ax0 = sns.lineplot(x="Resample", y="Episode Reward", hue="Model", legend="full", ci="sd", data=Gen_Ant, ax=Ant_axes[1])
ax0 = sns.lineplot(x="Resample", y="Episode Reward", hue="Model", legend="full", ci="sd", data=Ext_Ant, ax=Ant_axes[2])

ax0 = sns.lineplot(x="Timestep", y="Episode Reward", hue="Model", legend="full", ci="sd", data=Normal_Walker, ax=Walker_axes[0])
ax0 = sns.lineplot(x="Resample", y="Episode Reward", hue="Model", legend="full", ci="sd", data=Gen_Walker, ax=Walker_axes[1])
ax0 = sns.lineplot(x="Resample", y="Episode Reward", hue="Model", legend="full", ci="sd", data=Ext_Walker, ax=Walker_axes[2])

Ant_axes[0].set_title('Normal', fontsize=48)
Ant_axes[1].set_title('Randomization', fontsize=48)
Ant_axes[2].set_title('Extreme', fontsize=48)

Ant_axes[0].set_ylabel('', fontsize=48)
Walker_axes[0].set_ylabel('', fontsize=48)

#Ant_axes[0].get_xaxis().set_ticks([])
#Ant_axes[1].get_xaxis().set_ticks([])
#Ant_axes[2].get_xaxis().set_ticks([])

Walker_axes[0].set_xlabel('Time Step', fontsize=48)
Walker_axes[1].set_xlabel('Resample Step', fontsize=48)
Walker_axes[2].set_xlabel('Resample Step', fontsize=48)

Ant_axes[0].set_xlabel('')
Ant_axes[1].set_xlabel('')
Ant_axes[2].set_xlabel('')

Ant_axes[1].set_ylabel('', fontsize=48)
Ant_axes[2].set_ylabel('', fontsize=48)

Walker_axes[1].set_ylabel('', fontsize=48)
Walker_axes[2].set_ylabel('', fontsize=48)

Ant_axes[0].set_ylabel('Ant Walker Reward', fontsize=32)
Walker_axes[0].set_ylabel('Double Pendulum Reward', fontsize=32)

Ant_axes[0].get_legend().remove()
Ant_axes[1].get_legend().remove()

Walker_axes[0].get_legend().remove()
Walker_axes[1].get_legend().remove()
Walker_axes[2].get_legend().remove()

#Ant_axes[0].get_legend().remove()
#Ant_axes[1].get_legend().remove()

#fig.text(0.01, 0.5, 'Average Reward', va='center', rotation='vertical' , fontsize=48)

plt.subplots_adjust(wspace=0.05, hspace=0.2)
fig.suptitle('Robot Generalization Results', fontsize=64)
plt.show()


"""Script for fine-tuning Pegasus
Example usage:
  # use XSum dataset as example, with first 1000 docs as training data
  from datasets import load_dataset
  dataset = load_dataset("xsum")
  train_texts, train_labels = dataset['train']['document'][:1000], dataset['train']['summary'][:1000]

  # use Pegasus Large model as base for fine-tuning
  model_name = 'google/pegasus-large'
  train_dataset, _, _, tokenizer = prepare_data(model_name, train_texts, train_labels)
  trainer = prepare_fine_tuning(model_name, tokenizer, train_dataset)
  trainer.train()

Reference:
  https://huggingface.co/transformers/master/custom_datasets.html
"""

import torch
from transformers import PegasusForConditionalGeneration, PegasusTokenizer, Trainer, TrainingArguments
from datasets import load_dataset
import sys
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "3"

class PegasusDataset(torch.utils.data.Dataset):
    def __init__(self, encodings, labels):
        self.encodings = encodings
        self.labels = labels
    def __getitem__(self, idx):
        item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
        item['labels'] = torch.tensor(self.labels['input_ids'][idx])  # torch.tensor(self.labels[idx])
        return item
    def __len__(self):
        return len(self.labels['input_ids'])  # len(self.labels)

def prepare_data(model_name,
                 train_texts, train_labels,
                 val_texts=None, val_labels=None,
                 test_texts=None, test_labels=None):
  """
  Prepare input data for model fine-tuning
  """
  tokenizer = PegasusTokenizer.from_pretrained(model_name)

  prepare_val = False if val_texts is None or val_labels is None else True
  prepare_test = False if test_texts is None or test_labels is None else True

  def tokenize_data(texts, labels):
    encodings = tokenizer(texts, truncation=True, padding=True)
    decodings = tokenizer(labels, truncation=True, padding=True)
    dataset_tokenized = PegasusDataset(encodings, decodings)
    return dataset_tokenized

  train_dataset = tokenize_data(train_texts, train_labels)
  val_dataset = tokenize_data(val_texts, val_labels) if prepare_val else None
  test_dataset = tokenize_data(test_texts, test_labels) if prepare_test else None

  return train_dataset, val_dataset, test_dataset, tokenizer

def prepare_fine_tuning(model_name, tokenizer, train_dataset, val_dataset=None, freeze_encoder=False, output_dir='./pegasus_results'):
  """
  Prepare configurations and base model for fine-tuning
  """
  torch_device = 'cuda' if torch.cuda.is_available() else 'cpu'
  model = PegasusForConditionalGeneration.from_pretrained(model_name).to(torch_device)

  if freeze_encoder:
    for param in model.model.encoder.parameters():
      param.requires_grad = False

  if val_dataset is not None:
    training_args = TrainingArguments(
      output_dir=output_dir,           # output directory
      num_train_epochs=2,             #total number of training epochs
      per_device_train_batch_size=1,  # batch size per device during training, can increase if memory allows
      per_device_eval_batch_size=1,   # batch size for evaluation, can increase if memory allows
      save_steps=5,                    # number of updates steps before checkpoint saves
      save_total_limit=1,              # limit the total amount of checkpoints and deletes the older checkpoints
      evaluation_strategy='steps',     # evaluation strategy to adopt during training
      eval_steps=2,                    # number of update steps before evaluation
      warmup_steps=5,                  # number of warmup steps for learning rate scheduler
      weight_decay=0.01,               # strength of weight decay
      logging_dir='./pegasus_logs',            # directory for storing logs
      logging_steps=2,
      gradient_accumulation_steps = 256
    )

    trainer = Trainer(
      model=model,                         # the instantiated 🤗 Transformers model to be trained
      args=training_args,                  # training arguments, defined above
      train_dataset=train_dataset,         # training dataset
      eval_dataset=val_dataset,            # evaluation dataset
      tokenizer=tokenizer
    )

  else:
    training_args = TrainingArguments(
      output_dir=output_dir,           # output directory
      num_train_epochs=2,            # total number of training epochs
      per_device_train_batch_size=1,   # batch size per device during training, can increase if memory allows
      save_steps=5,                  # number of updates steps before checkpoint saves
      save_total_limit=1,              # limit the total amount of checkpoints and deletes the older checkpoints
      warmup_steps=5,                # number of warmup steps for learning rate scheduler
      weight_decay=0.01,               # strength of weight decay
      logging_dir='./pegasus_logs',            # directory for storing logs
      logging_steps=2,
      gradient_accumulation_steps = 256
    )

    trainer = Trainer(
      model=model,                         # the instantiated 🤗 Transformers model to be trained
      args=training_args,                  # training arguments, defined above
      train_dataset=train_dataset,         # training dataset
      tokenizer=tokenizer
    )

  return trainer

if __name__=='__main__':
    # use CNN/DM dataset as example, with first 1000 docs as training data
    dataset = load_dataset("cnn_dailymail", '3.0.0')
    train_texts, train_labels = dataset['train']['article'][:10000], dataset['train']['highlights'][:10000]
    valid_texts, valid_labels = dataset['validation']['article'][:500], dataset['validation']['highlights'][:500]
    test_texts, test_labels = dataset['test']['article'][:500], dataset['test']['highlights'][:500]

    # use Pegasus Large model as base for fine-tuning
    # use Pegasus Large model as base for fine-tuning
    model_name = 'google/pegasus-large'
    train_dataset, val_dataset, test_dataset, tokenizer = prepare_data(model_name, train_texts, train_labels, val_texts = valid_texts, val_labels=valid_labels,
                test_texts=test_texts, test_labels=test_labels)

    trainer = prepare_fine_tuning(model_name, tokenizer, train_dataset)
    trainer.train()
    trainer.evaluate(test_dataset)


'''
Created on Jun 29, 2014

@author: Federico Reghenzani <federico.dev@reghe.net>
'''

import web.login
import threading
import web.bottle

class HttpServer(threading.Thread):
    '''
    classdocs
    '''

    urls = (
            '/' , 'index'
            )

    @staticmethod
    def start_server(ip, port):
        hs = HttpServer(ip, port)
        hs.start()

    def __init__(self, ip : str, port : int):
        '''
        Constructor for http server object. This do nothing: save only
        port and ip address
        '''
        threading.Thread.__init__(self)
        self._ip = ip;
        self._port = port;

    def run(self) -> None:
        '''
        The main thread execution: it manages all requests from web
        '''

        web.bottle.run(host=self._ip, port=self._port, debug=True)