from __future__ import division, absolute_import
from PIL import ImageTk, Image
from timeit import time
from tkinter import *
from tkinter.ttk import *
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torch.autograd import Variable
from PIL import ImageTk, Image
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
from deep_sort import preprocessing
from deep_sort import nn_matching
from deep_sort.detection import Detection
from deep_sort.tracker import Tracker
from tools import generate_detections as gdet
from deep_sort.detection import Detection as ddet
from glob import glob
from tkinter import *
from tkinter.ttk import *
from PIL import ImageTk, Image
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import Canvas
from tkinter.scrolledtext import ScrolledText
from tkcalendar import Calendar, DateEntry
from timeit import time
from timeit import default_timer as timer
from keras import backend as K
from keras.models import load_model
from PIL import Image, ImageFont, ImageDraw
from yolo3.model import yolo_eval
from yolo3.utils import letterbox_image
import matplotlib.pyplot as plt
import matplotlib.pylab as plt
import os
import sys
import datetime
import random
import torch
import cv2
import time
import numpy as np
import tkinter as tk
import colorsys
import csv

def _get_class():
        global classes_path
        classes_path = os.path.expanduser(classes_path)
        with open(classes_path) as f:
            class_names = f.readlines()
        class_names = [c.strip() for c in class_names]
        return class_names

def _get_anchors():
        global anchors_path
        anchors_path = os.path.expanduser(anchors_path)
        with open(anchors_path) as f:
            anchors = f.readline()
            anchors = [float(x) for x in anchors.split(',')]
            anchors = np.array(anchors).reshape(-1, 2)
        return anchors

def generate():
        global input_image_shape
        hsv_tuples = [(x / len(class_names), 1., 1.)
                      for x in range(len(class_names))]
        colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
        colors = list(
            map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
                colors))
        random.seed(10101)
        random.shuffle(colors)
        random.seed(None)
        input_image_shape = K.placeholder(shape=(2, ))
        boxes, scores, classes = yolo_eval(yolo_model.output, anchors,
                len(class_names), input_image_shape,
                score_threshold=score, iou_threshold=iou)
        return boxes, scores, classes

def detect_image(image):
        global input_image_shape
        if is_fixed_size:
            boxed_image = letterbox_image(image, tuple(reversed(model_image_size)))
        else:
            new_image_size = (image.width - (image.width % 32),
                              image.height - (image.height % 32))
            boxed_image = letterbox_image(image, new_image_size)
        image_data = np.array(boxed_image, dtype = "float32")
        image_data /= 255.
        image_data = np.expand_dims(image_data, 0)

        out_boxes, out_scores, out_classes = sess.run(
            [boxes, scores, classes],
            feed_dict={
                yolo_model.input: image_data,
                input_image_shape: [image.size[1], image.size[0]],
                K.learning_phase(): 0
            })
        return_boxs = []
        for i, c in reversed(list(enumerate(out_classes))):
            predicted_class = class_names[c]
            if predicted_class != "person":
                continue
            box = out_boxes[i]
            x = int(box[1])
            y = int(box[0])
            w = int(box[3]-box[1])
            h = int(box[2]-box[0])
            if x < 0 :
                w = w + x
                x = 0
            if y < 0 :
                h = h + y
                y = 0
            return_boxs.append([x,y,w,h])

        return return_boxs

def close_session():
        sess.close()

yellowCount = np.array([])
redCount = np.array([])
groupMax= np.array([])
model_path = "model_data/yolo.h5"
anchors_path = "model_data/yolo_anchors.txt"
classes_path = "model_data/coco_classes.txt"
model_path = os.path.expanduser(model_path)
yolo_model = load_model(model_path, compile=False)
score = 0.5
iou = 0.5
class_names = _get_class()
anchors = _get_anchors()
sess = K.get_session()
model_image_size = (416, 416)
input_image_shape = [0, 0]
is_fixed_size = model_image_size != (None, None)
boxes, scores, classes = generate()
model_filename = "model_data/mars-small128.pb"
encoder = gdet.create_box_encoder(model_filename, batch_size = 1)
metric = nn_matching.NearestNeighborDistanceMetric("cosine", 0.3, None)
tracker = Tracker(metric)
vectorGroup1 = []
vectorGroup2 = []
vectorCountYellow = []
vectorCountRed = []

def move_window(event):
    root.geometry("+{0}+{1}".format(event.x_root, event.y_root))

def change_on_hovering(event):
    global close_button
    close_button["bg"] = "red"

def return_to_normalstate(event):
    global close_button
    close_button["bg"] = "#2e2e2e"

def dist(x1, y1, x2, y2):
        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)

def pairFigure():
        global yellowCount, redCount
        with open("output/group.csv", "r") as file:
                reader = csv.reader(file)
                count = 0
                for row in reader:
                        count += 1
                        if (count % 2 == 1):
                                yellowCount = np.append(yellowCount, int(row[2]))
                                redCount = np.append(redCount, int(row[3]))
        dateAxis = np.array([])
        valueAxis = np.row_stack((yellowCount, redCount))
        maxAxis = max(np.amax(yellowCount), np.amax(redCount))
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        ax1.plot(valueAxis[0, :], label = "Số lượng cặp người có khoảng cách gần nhau", color = "y")
        ax1.plot(valueAxis[1, :], label = "Số lượng cặp người có khoảng cách rất gần nhau", color = "r")
        axes = plt.axes()
        maxAxis = max(5, max(np.amax(yellowCount), np.amax(redCount)))
        axes.set_ylim([0, maxAxis])
        axesNumber = []
        for i in range(int(maxAxis) + 1): axesNumber.append(i)
        axes.set_yticks(axesNumber)
        plt.xticks(dateAxis)
        plt.xlabel("Biểu đồ số lượng cặp người có khoảng cách gần và rất gần nhau theo thời gian")
        handles, labels = ax1.get_legend_handles_labels()
        lgd = ax1.legend(loc = "best")
        ax1.grid('on')
        plt.savefig("output/pairFigure.jpg")

def groupFigure():
        global groupMax
        with open("output/group.csv", "r") as file:
                reader = csv.reader(file)
                count = 0
                for row in reader:
                        count += 1
                        if (count % 2 == 1):
                                groupMax = np.append(groupMax, int(row[0]))
        dateAxis = np.array([])
        maxAxis = np.amax(groupMax)
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        ax1.plot(groupMax, label = "Số lượng người trong nhóm lớn nhất", color = "b")
        axes = plt.axes()
        maxAxis = np.amax(groupMax)
        axes.set_ylim([0, maxAxis])
        axesNumber = []
        for i in range(int(maxAxis) + 1): axesNumber.append(i)
        axes.set_yticks(axesNumber)
        plt.xticks(dateAxis)
        plt.xlabel("Biểu đồ số lượng người trong nhóm lớn nhất theo thời gian")
        handles, labels = ax1.get_legend_handles_labels()
        lgd = ax1.legend(loc = "best")
        ax1.grid('on')
        plt.savefig("output/groupFigure.jpg")

def openVideo():
        global countFrame, vectorGroup1, vectorGroup2, vectorCountYellow, vectorCountRed
        filename = filedialog.askopenfilename(initialdir = "/home/", title = "Chọn video", filetypes = [("Video", [".mp4", ".avi"] )])
        directoryText.set(" " + filename)
        videoCapture = cv2.VideoCapture(filename)
        w = int(videoCapture.get(3))
        h = int(videoCapture.get(4))
        fourcc = cv2.VideoWriter_fourcc(*'MJPG')
        out = cv2.VideoWriter("result.avi", fourcc, 15, (w, h))
        outGroup1 = cv2.VideoWriter("outGroup1.avi", cv2.VideoWriter_fourcc(*'DIVX'), 15, (180, 180))
        outGroup2 = cv2.VideoWriter("outGroup2.avi", cv2.VideoWriter_fourcc(*'DIVX'), 15, (180, 180))
        countFrame = 0
        statusText.set(" Đang phân tích")
        def videoStream():
                global countFrame, vectorGroup1, vectorGroup2, vectorCountYellow, vectorCountRed
                ret, frame = videoCapture.read()
                if (ret != True):
                        return
                countFrame += 1
                image = Image.fromarray(frame[..., ::-1])
                boxs = detect_image(image)
                features = encoder(frame, boxs)
                detections = [Detection(bbox, 1.0, feature) for bbox, feature in zip(boxs, features)]
                boxes = np.array([d.tlwh for d in detections])
                scores = np.array([d.confidence for d in detections])
                indices = preprocessing.non_max_suppression(boxes, 1.0, scores)
                detections = [detections[i] for i in indices]
                tracker.predict()
                tracker.update(detections)
                det = [[] for _ in range(len(detections))]
                for i in range(len(detections)):
                        det[i] = detections[i]
                        bbox = det[i].to_tlbr()
                        cv2.circle(frame, (int((bbox[0] + bbox[2]) // 2), int((bbox[1] + bbox[3]) // 2)), 3, (0, 255, 0), 3)
                        l = int(min(bbox[2] - bbox[0], bbox[3] - bbox[1]))
                edge = [[] for _ in range(len(detections))]
                countRed = 0
                countYellow = 0
                for i in range(len(detections)):
                        for j in range(i + 1, len(detections)):
                                bbox1 = detections[i].to_tlbr()
                                bbox2 = detections[j].to_tlbr()
                                x1 = int((bbox1[0] + bbox1[2]) // 2)
                                y1 = int((bbox1[1] + bbox1[3]) // 2)
                                x2 = int((bbox2[0] + bbox2[2]) // 2)
                                y2 = int((bbox2[1] + bbox2[3]) // 2)
                                if (min(y1, y2) <= h // 3):
                                        if (dist(x1, y1, x2, y2) <= 30 * 30):
                                                cv2.line(frame, (x1, y1), (x2, y2), (0, 0, 255), 3)
                                                edge[i].append(j)
                                                edge[j].append(i)
                                                countRed += 1
                                        else:
                                                if (dist(x1, y1, x2, y2) <= 100 * 100):
                                                        cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 255), 3)
                                                        edge[i].append(j)
                                                        edge[j].append(i)
                                                        countYellow += 1
                                else:
                                        if (min(y1, y2) <= h // 2):
                                                if (dist(x1, y1, x2, y2) <= 100 * 100):
                                                        cv2.line(frame, (x1, y1), (x2, y2), (0, 0, 255), 3)
                                                        edge[i].append(j)
                                                        edge[j].append(i)
                                                        countRed += 1
                                                else:
                                                        if (dist(x1, y1, x2, y2) <= 150 * 150):
                                                                cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 255), 3)
                                                                edge[i].append(j)
                                                                edge[j].append(i)
                                                                countYellow += 1
                                        else:
                                                if (dist(x1, y1, x2, y2) <= 130 * 130):
                                                        cv2.line(frame, (x1, y1), (x2, y2), (0, 0, 255), 3)
                                                        edge[i].append(j)
                                                        edge[j].append(i)
                                                        countRed += 1
                                                else:
                                                        if (dist(x1, y1, x2, y2) <= 250 * 250):
                                                                cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 255), 3)
                                                                edge[i].append(j)
                                                                edge[j].append(i)
                                                                countYellow += 1
                cv2.putText(frame, "So luong cap gan nhau: " + str(countYellow), (int(w - 650), int(h - 70)), 0, 5e-3 * 200, (0, 255, 255), 3)
                cv2.putText(frame, "So luong cap rat gan nhau: " + str(countRed), (int(w - 650), int(h - 40)), 0, 5e-3 * 200, (0, 0, 255), 3)
                vectorCountYellow.append(countYellow)
                vectorCountRed.append(countRed)
                out.write(frame)
                cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
                cv2image = cv2.resize(cv2image, (755, 520))
                img = Image.fromarray(cv2image)
                imgtk = ImageTk.PhotoImage(image = img)
                lmain.imgtk = imgtk
                lmain.configure(image = imgtk)
                mark = [True for _ in range(len(detections))]
                component = [[[], 0] for _ in range(len(detections))]
                componentCount = -1
                def DFS(u):
                        component[componentCount][0].append(u)
                        mark[u] = False
                        for v in edge[u]:
                                if (mark[v] == True): DFS(v)
                for i in range(len(detections)):
                        if (mark[i] == True):
                                componentCount += 1
                                DFS(i)
                for i in range(componentCount):
                        component[i][1] = len(component[i][0])
                def takeSecond(elem):
                        return elem[1]
                component.sort(key = takeSecond, reverse = True)
                if (componentCount >= 1):
                        xMin = 100000
                        yMin = 100000
                        xMax = 0
                        yMax = 0
                        for i in component[0][0]:
                                bbox = det[i].to_tlbr()
                                xMax = max(xMax, max(bbox[0], bbox[2]))
                                xMin = min(xMin, min(bbox[0], bbox[2]))
                                yMax = max(yMax, max(bbox[1], bbox[3]))
                                yMin = min(yMin, min(bbox[1], bbox[3]))
                        cropFrame = frame[int(yMin) : int(yMax), int(xMin) : int(xMax)]
                        cv2.imwrite("temp.jpg", cropFrame)
                        cv2image13 = cv2.imread("temp.jpg")
                        cv2image13 = cv2.resize(cv2image13, (180, 180))
                        outGroup1.write(cv2image13)
                        cv2image13 = cv2.cvtColor(cv2image13, cv2.COLOR_BGR2RGBA)
                        img13 = Image.fromarray(cv2image13)
                        imgtk13 = ImageTk.PhotoImage(image = img13)
                        lmain13.imgtk13 = imgtk13
                        lmain13.configure(image = imgtk13)
                        group1Text.set(" Số người trong nhóm: " + str(len(component[0][0])))
                        vectorGroup1.append(len(component[0][0]))
                else:
                        cv2image13 = cv2.imread("avatar.jpg")
                        cv2image13 = cv2.resize(cv2image13, (180, 180))
                        outGroup1.write(cv2image13)
                        vectorGroup1.append(0)
                if (componentCount >= 2):
                        xMin = 100000
                        yMin = 100000
                        xMax = 0
                        yMax = 0
                        for i in component[1][0]:
                                bbox = det[i].to_tlbr()
                                xMax = max(xMax, max(bbox[0], bbox[2]))
                                xMin = min(xMin, min(bbox[0], bbox[2]))
                                yMax = max(yMax, max(bbox[1], bbox[3]))
                                yMin = min(yMin, min(bbox[1], bbox[3]))
                        cropFrame = frame[int(yMin) : int(yMax), int(xMin) : int(xMax)]
                        cv2.imwrite("temp.jpg", cropFrame)
                        cv2image14 = cv2.imread("temp.jpg")
                        cv2image14 = cv2.resize(cv2image14, (180, 180))
                        outGroup2.write(cv2image14)
                        cv2image14 = cv2.cvtColor(cv2image14, cv2.COLOR_BGR2RGBA)
                        img14 = Image.fromarray(cv2image14)
                        imgtk14 = ImageTk.PhotoImage(image = img14)
                        lmain14.imgtk14 = imgtk14
                        lmain14.configure(image = imgtk14)
                        group2Text.set(" Số người trong nhóm: " + str(len(component[1][0])))
                        vectorGroup2.append(len(component[1][0]))
                else:
                        cv2image14 = cv2.imread("avatar.jpg")
                        cv2image14 = cv2.resize(cv2image14, (180, 180))
                        outGroup2.write(cv2image14)
                        vectorGroup2.append(0)
                progress["value"] += 100 / int(videoCapture.get(cv2.CAP_PROP_FRAME_COUNT))
                if (int(countFrame) == int(videoCapture.get(cv2.CAP_PROP_FRAME_COUNT))):
                        out.release()
                        outGroup1.release()
                        outGroup2.release()
                        statusText.set(" Đã phân tích xong")
                        progress["value"] = 100
                        rows = zip(vectorGroup1, vectorGroup2, vectorCountYellow, vectorCountRed)
                        with open("group.csv", "w") as f:
                                writer = csv.writer(f)
                                for row in rows:
                                        writer.writerow(row)
                        pairFigure()
                        groupFigure()
                        return
                else:
                        lmain.after(1, videoStream)
        videoStream()

def playVideo():
        global vector, pos
        filename = filedialog.askopenfilename(initialdir = "/home/", title = "Chọn video", filetypes = [("Video", [".mp4", ".avi"] )])
        directoryText.set(" " + filename)
        statusText.set(" Đang phân tích")
        pos = 0
        with open("output/group.csv", "r") as f:
                reader = csv.reader(f)
                pos = 0
                for row in reader:
                        pos += 1
                        if (pos % 2 == 1):
                                vector.append(row)
        videoCapture = cv2.VideoCapture("output/result.avi")
        pos = -1
        def videoStream():
                global pos, vector
                ret, frame = videoCapture.read()
                pos += 1
                if (ret != True):
                        statusText.set(" Đã phân tích xong")
                        progress["value"] = 100
                        return
                group1Text.set(" Số người trong nhóm: " + str(vector[pos][0]))
                group2Text.set(" Số người trong nhóm: " + str(vector[pos][1]))
                cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
                cv2image = cv2.resize(cv2image, (755, 520))
                img = Image.fromarray(cv2image)
                imgtk = ImageTk.PhotoImage(image = img)
                lmain.imgtk = imgtk
                lmain.configure(image = imgtk)
                progress["value"] += 100 / int(videoCapture.get(cv2.CAP_PROP_FRAME_COUNT))
                lmain.after(1, videoStream)
        videoStream()

def choosingName():
    imageList5.delete(0, END)
    imageList5.insert(END, "18/5/2020")
    imageList5.insert(END, "19/5/2020")
    imageList5.insert(END, "20/5/2020")
    imageList5.insert(END, "21/5/2020")

root = Tk()
root.overrideredirect(True)
root.title("Hệ thống hỗ trợ giám sát chấp hành giãn cách xã hội phòng chống dịch bệnh truyền nhiễm cho doanh nghiệp")
root.geometry('1230x725')
root.resizable(0, 0)
title_bar = tk.Frame(root, bg = "#2e2e2e", relief = "raised", bd = 2, height = 30, highlightthickness = 0)
title_bar.pack(side = TOP, fill = "both")
close_button = tk.Button(title_bar, text = 'X', command = root.destroy, bg = "#2e2e2e", padx = 2, pady = 2, activebackground = "red", bd = 0, font = "bold", fg = "white", highlightthickness = 0)
close_button.pack(side = RIGHT)
title = Label(title_bar, text = " ")
title.config(font = ("Courier", 12), background = "#2e2e2e", foreground = "#ffffff")
title.pack(side = LEFT)
app3 = Frame(title_bar)
app3.pack(side = LEFT)
lmain3 = Label(app3)
lmain3.grid(padx = 0, pady = 0, ipadx = 0, ipady = 0, sticky = E + S)
cv2image3 = cv2.imread("icon.png")
cv2image3 = cv2.cvtColor(cv2image3, cv2.COLOR_BGR2RGBA)
cv2image3 = cv2.resize(cv2image3, (15, 15))
img3 = Image.fromarray(cv2image3)
imgtk3 = ImageTk.PhotoImage(image = img3)
lmain3.imgtk3 = imgtk3
lmain3.configure(image = imgtk3)
title = Label(title_bar, text = " Import Keras - Vietnam Online Hackathon")
title.config(font = ("Courier", 12), background = "#2e2e2e", foreground = "#ffffff")
title.pack(side = LEFT)
title_bar.bind("<B1-Motion>", move_window)
close_button.bind("<Enter>", change_on_hovering)
close_button.bind("<Leave>", return_to_normalstate)
app7 = Frame(root)
app7.pack(side = TOP, fill = "both")
lmain7 = Label(app7)
lmain7.grid(padx = 0, pady = 0, ipadx = 0, ipady = 0, sticky = E + S)
cv2image7 = cv2.imread("banner.png")
cv2image7 = cv2.cvtColor(cv2image7, cv2.COLOR_BGR2RGBA)
cv2image7 = cv2.resize(cv2image7, (1226, 100))
img7 = Image.fromarray(cv2image7)
imgtk7 = ImageTk.PhotoImage(image = img7)
lmain7.imgtk7 = imgtk7
lmain7.configure(image = imgtk7)
tabParent = ttk.Notebook(root)
class1 = ttk.Frame(tabParent)
class2 = ttk.Frame(tabParent)
class3 = ttk.Frame(tabParent)
class4 = ttk.Frame(tabParent)
tabParent.add(class1, text = "Quan sát")
tabParent.add(class2, text = "Thống kê")
tabParent.add(class3, text = "Quản lý nhân viên")
tabParent.add(class4, text = "Quản lý khách hàng")
tabParent.pack(side = TOP, expand = 1, fill = "both")
videoFrame = LabelFrame(class1, text = "Hình ảnh trực tiếp từ camera quan sát", width = 775, height = 540)
videoFrame.grid(row = 1, rowspan = 4, column = 1, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = W + N + S)
settingFrame = LabelFrame(class1, text = "Hệ thống", width = 210)
settingFrame.grid(row = 1, column = 3, padx = 5, pady = 5, ipadx = 0, ipady = 5, sticky = W + E + N)
infoFrame = LabelFrame(class1, text = "Thông tin", width = 210)
infoFrame.grid(row = 2, rowspan = 2, column = 3, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = W + E + N)
exportFrame = LabelFrame(class1, text = "Xuất", width = 210)
exportFrame.grid(row = 4, column = 3, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = W + E + N)
groupFrame = LabelFrame(class1, text = "Nhóm nhiều người gần nhau nhất", width = 195)
groupFrame.grid(row = 1, rowspan = 2, column = 2, padx = 5, pady = 5, ipadx = 0, ipady = 5, sticky = E + W + N + S)
Button(exportFrame, text = "Dữ liệu", width = 14).grid(row = 1, column = 1, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + W + N + S)
Button(exportFrame, text = "Video", width = 14).grid(row = 1, column = 2, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + W + N + S)
app9 = Frame(class1)
app9.grid(row = 3, rowspan = 2, column = 2, padx = 5, pady = 0, ipadx = 0, ipady = 0, sticky = E + W + N + S)
lmain9 = Label(app9)
lmain9.grid(padx = 0, pady = 0, ipadx = 0, ipady = 0, sticky = E + S)
cv2image9 = cv2.imread("logo.jpg")
cv2image9 = cv2.cvtColor(cv2image9, cv2.COLOR_BGR2RGBA)
cv2image9 = cv2.resize(cv2image9, (205, 70))
img9 = Image.fromarray(cv2image9)
imgtk9 = ImageTk.PhotoImage(image = img9)
lmain9.imgtk9 = imgtk9
lmain9.configure(image = imgtk9)
lmain = Label(videoFrame)
lmain.grid(padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + W + N + S)
cv2image = cv2.imread("default.png")
cv2image = cv2.cvtColor(cv2image, cv2.COLOR_BGR2RGBA)
cv2image = cv2.resize(cv2image, (755, 520))
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image = img)
lmain.imgtk = imgtk
lmain.configure(image = imgtk)
Button(settingFrame, text = "Mở tập tin video", command = playVideo).grid(row = 1, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = W + E)
Label(settingFrame, text = " Đường dẫn tập tin").grid(row = 3, sticky = W)
directoryText = StringVar()
directory = Entry(settingFrame, width = 32, textvariable = directoryText)
directory.grid(row = 4, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = W)
Label(settingFrame, text = " Trạng thái phân tích").grid(row = 6, sticky = W)
statusText = StringVar()
status = Entry(settingFrame, width = 32, textvariable = statusText)
status.grid(row = 7, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = W)
statusText.set(" Đang chờ tập tin")
Label(settingFrame, text = " Ngày giờ hệ thống").grid(row = 9, sticky = W)
curTime = Entry(settingFrame, width = 32)
curTime.insert(15, time.strftime(" %m/%d/%Y, %H:%M:%S %p"))
curTime.grid(row = 10, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = W)
progress = Progressbar(settingFrame, orient = HORIZONTAL, mode = "determinate")
progress.grid(row = 11, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = N + W + E + S)
progress["value"] = 0
app8 = Frame(infoFrame)
app8.pack(side = TOP, fill = "both")
lmain8 = Label(app8)
lmain8.grid(padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + S)
cv2image8 = cv2.imread("info.png")
cv2image8 = cv2.cvtColor(cv2image8, cv2.COLOR_BGR2RGBA)
cv2image8 = cv2.resize(cv2image8, (195, 200))
img8 = Image.fromarray(cv2image8)
imgtk8 = ImageTk.PhotoImage(image = img8)
lmain8.imgtk8 = imgtk8
lmain8.configure(image = imgtk8)
countFrame = 0
pos = 0
vector = []
app13 = Frame(groupFrame)
app13.grid(row = 1, padx = 5, pady = 2, ipadx = 0, ipady = 0, sticky = W + E + N + S)
lmain13 = Label(app13)
lmain13.grid(row = 1, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + S)
cv2image13 = cv2.imread("avatar.jpg")
cv2image13 = cv2.cvtColor(cv2image13, cv2.COLOR_BGR2RGBA)
cv2image13 = cv2.resize(cv2image13, (180, 180))
img13 = Image.fromarray(cv2image13)
imgtk13 = ImageTk.PhotoImage(image = img13)
lmain13.imgtk13 = imgtk13
lmain13.configure(image = imgtk13)
group1Text = StringVar()
group1 = Entry(groupFrame, textvariable = group1Text)
group1.grid(row = 2, padx = 10, pady = 2, ipadx = 0, ipady = 0, sticky = W + E + N + S)
group1Text.set(" Số người trong nhóm: ")
app14 = Frame(groupFrame)
app14.grid(row = 3, padx = 5, pady = 2, ipadx = 0, ipady = 0, sticky = W + E + N + S)
lmain14 = Label(app14)
lmain14.grid(row = 3, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + S)
cv2image14 = cv2.imread("avatar.jpg")
cv2image14 = cv2.cvtColor(cv2image14, cv2.COLOR_BGR2RGBA)
cv2image14 = cv2.resize(cv2image14, (180, 180))
img14 = Image.fromarray(cv2image14)
imgtk14 = ImageTk.PhotoImage(image = img14)
lmain14.imgtk14 = imgtk14
lmain14.configure(image = imgtk14)
group2Text = StringVar()
group2 = Entry(groupFrame, textvariable = group2Text)
group2.grid(row = 4, padx = 10, pady = 2, ipadx = 0, ipady = 0, sticky = W + E + N + S)
group2Text.set(" Số người trong nhóm: ")
app16 = Frame(class2)
app16.grid(row = 1, column = 1, padx = 60, pady = 25, ipadx = 0, ipady = 0, sticky = W + E + N + S)
lmain16 = Label(app16)
lmain16.grid(row = 3, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + S)
cv2image16 = cv2.imread("output/pairFigure.jpg")
cv2image16 = cv2.cvtColor(cv2image16, cv2.COLOR_BGR2RGBA)
cv2image16 = cv2.resize(cv2image16, (500, 500))
img16 = Image.fromarray(cv2image16)
imgtk16 = ImageTk.PhotoImage(image = img16)
lmain16.imgtk16 = imgtk16
lmain16.configure(image = imgtk16)
app17 = Frame(class2)
app17.grid(row = 1, column = 2,  padx = 5, pady = 25, ipadx = 0, ipady = 0, sticky = W + E + N + S)
lmain17 = Label(app17)
lmain17.grid(row = 3, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + S)
cv2image17 = cv2.imread("output/groupFigure.jpg")
cv2image17 = cv2.cvtColor(cv2image17, cv2.COLOR_BGR2RGBA)
cv2image17 = cv2.resize(cv2image17, (500, 500))
img17 = Image.fromarray(cv2image17)
imgtk17 = ImageTk.PhotoImage(image = img17)
lmain17.imgtk17 = imgtk17
lmain17.configure(image = imgtk17)
filterDateFrame = LabelFrame(class4, text = "Lịch sử")
filterDateFrame.grid(row = 2, column = 2, padx = 350, pady = 25, ipadx = 0, ipady = 0, sticky = E + W + N + S)
app5 = Frame(filterDateFrame)
app5.grid(row = 1, column = 1, columnspan = 2, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + W + N + S)
lmain5 = Label(app5)
lmain5.grid(padx = 0, pady = 0, ipadx = 0, ipady = 0, sticky = E + W + N + S)
cv2image5 = cv2.imread("null.png")
cv2image5 = cv2.cvtColor(cv2image5, cv2.COLOR_BGR2RGBA)
cv2image5 = cv2.resize(cv2image5, (450, 450))
img5 = Image.fromarray(cv2image5)
imgtk5 = ImageTk.PhotoImage(image = img5)
lmain5.imgtk = imgtk5
lmain5.configure(image = imgtk5)
imageList5 = Listbox(filterDateFrame, width = 5, height = 15, font = ('times', 13))
imageList5 = tk.Listbox(filterDateFrame, width = 8, height = 15, font = ('times', 13))
imageList5.grid(row = 1, column = 3, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + W + N + S)
imageList5.bind("<ButtonRelease-1>")
mynumber = tk.StringVar()
combobox = ttk.Combobox(filterDateFrame, textvariable = mynumber)
combobox["values"] = tuple(["Pham Huy", "Thiet Gia", "Minh Nhat", "Anh Hao"])
combobox.grid(row = 2, column = 1, columnspan = 2, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + W + N + S)
button = ttk.Button(filterDateFrame, text = "Chọn tên", command = choosingName)
button.grid(row = 2, column = 3, padx = 5, pady = 5, ipadx = 0, ipady = 0, sticky = E + W + N + S)


#!/usr/bin/env python
"""
Use MCTS with different custom policies
"""
from time import perf_counter
from numpy import array as A
from envs.game_2048 import Game2048
from policies.policy_mcts import PolicyMcts
from models.cbs import Roller
# from policies.policy_mixte import PolicyMaximizeRewardOnCorner
# from policies.policy_mixte import PolicyMaximizeSameNeighbors
# from policies.policy_mixte import PolicyMinimizeNbTile
# from policies.policy_mixte import PolicyMaximizeReward
from policies.policy_mixte import PolicyRandom

env = Game2048(size=3)
# for policy in [PolicyRandom, PolicyMaximizeReward, PolicyMinimizeNbTile, PolicyMaximizeSameNeighbors]:
for policy in [PolicyRandom]:
    pol = policy(env)
    print(pol.__class__.__name__)
    best_model = PolicyMcts(pol, env)
    for i in [20]:
        best_model.nb = i
        print(f'  Depth {i}')
        roller = Roller(env, best_model, nb=10, verbose=0)
        cronos = perf_counter()
        wins = roller()
        elapsed = perf_counter() - cronos
        max_states = A(roller.max_states)
        print(wins, roller.reward, max_states.max(), max_states.mean(), f'elapsed {elapsed:.2f} seconds')
        print(f'  wins: {wins}%, reward: {roller.reward}, max_states max: {max_states.max()}, max_states max: {max_states.mean()}, elapsed {elapsed:.2f} seconds')


from flask import Flask, render_template, url_for, request, jsonify
import pandas as pd
import numpy as np
import data as dt
import datetime
app = Flask(__name__)

@app.route('/shinobu', methods = ['GET'])
def kawaii():
    return render_template("index.html")
#mainblock
@app.route('/', methods = ['GET'])
def profile():
    return render_template("profile.html")
@app.route('/data', methods = ['GET'])
def data():
    data = pd.read_csv('s_data.csv')
    dataset = []
    for i in range(len(data)):
        temp = []
        for x in data.iloc[i]:
            temp.append(x)
        dataset.append(temp)
    dataset2 = dt.data_to_analysis
    return render_template("data.html",dataset = dataset,data=dataset2)
@app.route('/analysis', methods = ['GET'])
def analysis():
    dataset = dt.data_to_analysis
    return render_template("analysis.html",data = dataset)

@app.route('/notifications', methods = ['GET'])
def notifications():
    return render_template("notifications.html")
@app.route('/payment', methods = ['GET'])
def payment():
    return render_template("payment.html")

@app.route('/dataformat')
def send_to():
    return '{"id": 0, "I": 1.5, "U":3.1, "P":36, "T":1.2, "I_max":3.6, "U_max":36, "timecode": "2020-08-14-19:48"}'
@app.route('/postdata', methods = ['POST'])
def postJSON():
    response = request.get_json(force=True)
    data = pd.read_csv('s_data.csv')
    data = dt.data_add(data,response)
    dt.save_data(data,'s_data.csv','csv')
    #dt.html_update(response)
    return 'Recieved'

@app.route('/charts')
def charts():
    dataset = dt.data_to_analysis
    return render_template("charts.html",data = dataset)

@app.route('/background_plot')#This page accessable only for js script
def background_process():
    date_start = request.args.get('date_start', 0, type= str)
    date_end = request.args.get('date_end', 0, type= str)
    region = request.args.get('region', 0, type= int)
    city = request.args.get('city', 0, type= str)
    street = request.args.get('street', 0, type= str)
    building = request.args.get('building', 0, type= int)
    flat = request.args.get('flat', 0, type= int)
    dep = int(request.args.get('dep', 0, type= int))
    dep_value = int(request.args.get('dep_value', 0, type= int))
    typee = request.args.get('typee', 0, type= int)
    if dep_value == 1:
        id_req = dt.get_id(region, city, street, building, flat)
        return jsonify(dt.get_temperature(dt.load_id(id_req),dep))
    else:
        if typee == 2:
            if city == "Город":
                return jsonify(dt.get_mean_region(dt.load_region(region),dep))
            else:
                id_req = dt.get_id(region, city, street, building, flat)
                return jsonify(dt.get_mean(dt.load_id(id_req),id_req,dep))
        else:
            if city == "Город":
                return jsonify(dt.get_plot_data_region(dt.load_region(region),date_start,date_end,dep))
            else:
                id_req = dt.get_id(region, city, street, building, flat)
                return jsonify(dt.get_plot_data(dt.load_id(id_req),date_start,date_end,id_req,dep))

    #return jsonify(dt.get_plot_data(dt.load_id(id_req),date_start,date_end,id_req,dep))

@app.route('/background_select', methods = ['GET'])
def select():
    regions_cities = dt.regions_cities
    region = request.args.get('region', 0, type= int)
    if region == 0:
        cities = regions_cities[region]
        return jsonify(city = data)
    else:
        cities = regions_cities[region]
        return jsonify(city = cities)
@app.route('/background_analysis', methods = ['GET'])
def do_analysis():
    date_start = request.args.get('date_start', 0, type= str)
    output = {'y': ['6', '1', '2'], 'x1': [1, 2], 'x2': [1, 2,5, 4]}
    return jsonify(dt.get_neural(date_start))
@app.route('/background_data', methods = ['GET'])
def bg_data():
    date_start = request.args.get('date_start', 0, type= str)
    date_end = request.args.get('date_end', 0, type= str)
    region = request.args.get('region', 0, type= int)
    city = request.args.get('city', 0, type= str)
    street = request.args.get('street', 0, type= str)
    building = request.args.get('building', 0, type= int)
    flat = request.args.get('flat', 0, type= int)

    if city == "Город":
        return jsonify(dt.get_data_region(dt.load_region(region),date_start,date_end))
    else:
        id_req = dt.get_id(region, city, street, building, flat)
        return jsonify(dt.get_data(dt.load_id(id_req),date_start,date_end,id_req,1))

@app.route('/time', methods = ['GET'])
def time():
   return(datetime.datetime.now().isoformat()[:10] + '-' + datetime.datetime.now().isoformat()[11:-7])
if __name__ == '__main__':
    app.jinja_env.auto_reload = True
    app.debug = True
    app.run(host = '0.0.0.0')


import  requests
from bs4 import BeautifulSoup
import operator

def start(url):
    word_list = []
    source_code = requests.get(url).text
    soup = BeautifulSoup(source_code, "html.parser")

    for post_text in soup.findAll('a', {'class': 'title text-semibold'}):
        content = post_text.string       # Get only the text
        words = content.lower().split()  # covert all words to lowercase. split() returns a list of the woords seperated by whitespaces

        for each_word in words:
            word_list.append(each_word)
    clean_up_list(word_list)

def clean_up_list(mylist):
    clean_list = []
    for word in mylist:
        symbols = "0123456789!\"£$%^&*(){}_-:@~<>?[];'#,./'"
        for i in range(0, len(symbols)):
            word = word.replace(symbols[i], "")
        if len(word) > 0:
            #print(word)
            clean_list.append(word)
    create_dictionary(clean_list)

def create_dictionary(clean_list):
    word_count = {}

    # The word is the key each time you find a word that is not in the dictinary.
    for word in clean_list:
        if word in word_count:
            word_count[word] += 1   # using the word as the key, increments the value stored
        else:
            word_count[word] = 1    # stores the value one with the wword as its key
    for key, value in sorted(word_count.items(), key=operator.itemgetter(1)):       # 1 is sort by value. O is sort by key
        print(key, value)

start('https://thenewboston.com/forum/category.php?id=15')


from Controller.database_controller import sendToDB, queryDB, query
from Data.watch_history import WatchHistory
'''
class TestTimer:
    def __init__(self, lapsed):
        self.timeLapsed = lapsed'''

timer = WatchHistory(10, 40, 30)

sendToDB(timer.startTime, timer.stopTime, timer.timeLapsed)
watches = query()
for i in watches:
    print(i.timeLapsed)
    print()


from src.map_module.tile_types.wall_tiles.types import *

# ===== reference list =====
_WALL_TILE_LIST = [
    AirWallTile,
    TreeWallTile,
    SeaweedWallTile,
    BerryBushWallTile,
    SurfaceRockWallTile,
    DeepRockWallTile,
    CopperVeinWallTile,
    IronVeinWallTile,
    SilverVeinWallTile,
    GoldVeinWallTile,
    WoodenTreasureChestWallTile,
    WaterTreasureChestWallTile,
    MagicTreasureChestWallTile,
    PlankWallTile,
    StoneBrickWallTile
]

# ===== allows for quicker reference by tiles id =====
WALL_TILES_BY_ID = {}
for wt in _WALL_TILE_LIST:
    WALL_TILES_BY_ID[wt.id] = wt


# Exercise 7: 10001 prime

# First, we need to make function that will help us check if number is prime
def is_prime(number):
    int(number)
    prime = True  # True = prime, False = not prime

    # All of numbers below and equal to 1 are not prime
    if number <= 1:
        return False

    else:
        # Prime number is a number, that divides (without a remainder) only by 1 and by itself
        for j in range(2, number):
            # If number % j is equal to 0, then number have other dividers and isn't prime
            if number % j == 0:
                return False
    # if number passed the loop, then it is prime
        if prime is True:
            return True

counter = 0  # It will count how many primes we had
number = 1  # It's current number
while True:
    boolean = is_prime(number)  # Check if number is prime

    if boolean is True:  # if it is, add 1 to counter
        counter += 1

    if counter == 10001:  # Check if counter == 10001, if it is - print current number
        print(number)
        break

    number += 1  # Make current number bigger by one and check again


import os
import glob
import cv2 as cv
from PIL import Image
import numpy as np
from tqdm import tqdm

from datasets.voc import VOCSegmentation
from datasets.utils.random_sampling import sample_points_for_singal_object

class GenerateDataPairs():
    def __init__(self, root_dir, save_dir='./voc2012', image_set='train', n_pairs:int=1, minimum_object_area:int=100) -> None:

        assert image_set in ['train', 'val', 'trainval']
        assert isinstance(n_pairs, int)
        self.n_pairs = n_pairs if n_pairs > 0 else 1
        self.minimum_object_area = minimum_object_area if minimum_object_area > 0 else 100

        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
        save_dir = os.path.join(save_dir, image_set) # save_dir/image_set
        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
        image_dir = os.path.join(save_dir, 'images') # image_dir
        if not os.path.exists(image_dir):
            os.mkdir(image_dir)
        label_dir = os.path.join(save_dir, 'labels') # label_dir
        if not os.path.exists(label_dir):
            os.mkdir(label_dir)
        interactive_dir = os.path.join(save_dir, 'interactives') # interactive_dir
        if not os.path.exists(interactive_dir):
            os.mkdir(interactive_dir)
        self.image_dir = image_dir
        self.label_dir = label_dir
        self.interactive_dir = interactive_dir

        self.dataset = VOCSegmentation(root_dir, image_set=image_set)

        self.generate()

    def check_object_area(self, object_binary_mask, minimum_object_area=100):
        contours, hierarchy = cv.findContours(object_binary_mask, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
        max_area = 0
        for c in contours:
            cur_area = cv.contourArea(c)
            if cur_area > max_area:
                max_area = cur_area
        return (max_area > minimum_object_area)

    def generate(self):
        for i, data in enumerate(tqdm(self.dataset)):
            # if i > 0:
            #     break
            image, label, name = data
            label_np = np.array(label)
            have_object_flag = False
            for id in np.unique(label_np):
                if id == 0 or id == 255: # skip background and object's contour
                    continue
                for k in range(self.n_pairs):
                    if self.check_object_area(np.uint8((label_np == id) * 255), 400):
                        object_interative_map = sample_points_for_singal_object(label_np, id) # [2, h, w]
                        if (not np.any(object_interative_map[0])) or (not np.any(object_interative_map[1])):
                            break
                        have_object_flag = True
                        fg_save_path = os.path.join(self.interactive_dir, f'{name}-{id}-fg-{k+1}.png')
                        Image.fromarray(object_interative_map[0]).save(fg_save_path)
                        bg_save_path = os.path.join(self.interactive_dir, f'{name}-{id}-bg-{k+1}.png')
                        Image.fromarray(object_interative_map[1]).save(bg_save_path)

            if have_object_flag:
                image_save_path = os.path.join(self.image_dir, f'{name}.jpg')
                image.save(image_save_path)
                label_save_path = os.path.join(self.label_dir, f'{name}.png')
                label.save(label_save_path)

# GenerateDataPairs(root_dir='/raid/home/guiyan/datasets', save_dir='./voc2012', image_set='val', n_pairs=1)
# GenerateDataPairs(root_dir='/raid/home/guiyan/datasets', save_dir='./voc2012', image_set='train', n_pairs=15)


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import glob, json
import torch
from ModelClass import *
from torchvision import transforms

# 删除训练集和验证集中包含超过四个数字的图片
def preprocess(json):
    png_idx = []
    index = 0
    for i in json:
        if len(json[i]['label']) > 4:
            png_idx.append(index)
        index += 1
    return png_idx

######################  训练集构造  #######################
train_path = glob.glob('F:/Tianchi_OCR_Freshman/Dataset/mchar_train/*.png')
train_path.sort()  # 按照文件名排序
train_json = json.load(open('F:/Tianchi_OCR_Freshman/Dataset/mchar_train.json'))  # 是排好序了的
train_length = [len(train_json[x]['label'])-1 for x in train_json]
del_idx = preprocess(train_json)
train_path = [train_path[i] for i in range(0,len(train_path)) if i not in del_idx]
train_length = [train_length[i] for i in range(0,len(train_length)) if i not in del_idx]
trainlength_loader = torch.utils.data.DataLoader(
    LengthDataset(train_path, train_length,
                   transforms.Compose([
                       # 缩放到固定尺寸
                       transforms.Resize((64, 128)),
                       # 随机颜色变换
                       transforms.ColorJitter(0.3, 0.3, 0.3),  # 改变图像的属性，亮度、对比度、饱和度和色调
                       # 加入随机旋转
                       transforms.RandomRotation(15),  # 随机旋转，在-5~5°之间旋转
                       # 将图片转换为pytorch的tensor
                       transforms.ToTensor(),
                       transforms.Normalize([0.4442,0.437,0.4326],[0.2035,0.2060,0.2076]),   # 均值、方差
                   ])),
    batch_size=256,  # 每批样本个数
    shuffle=False,   # 是否打乱顺序
    num_workers=0,   # 读取的线程个数
)

######################  验证集构造  #######################
valid_path = glob.glob('F:/Tianchi_OCR_Freshman/Dataset/mchar_val/*.png')
valid_path.sort()
valid_json = json.load(open('F:/Tianchi_OCR_Freshman/Dataset/mchar_val.json'))  # 是排好序了的
valid_length = [len(valid_json[x]['label'])-1 for x in valid_json]
del_idx = preprocess(valid_json)
valid_path = [valid_path[i] for i in range(0,len(valid_path)) if i not in del_idx]
valid_length = [valid_length[i] for i in range(0,len(valid_length)) if i not in del_idx]
validlength_loader = torch.utils.data.DataLoader(
    LengthDataset(valid_path,valid_length,transforms.Compose([
        # 缩放到固定尺寸
        transforms.Resize((64, 128)),
        # 随机颜色变换
        # transforms.ColorJitter(0.2, 0.2, 0.2),  # 改变图像的属性，亮度、对比度、饱和度和色调
        # 加入随机旋转
        # transforms.RandomRotation(5),  # 随机旋转，在-5~5°之间旋转
        transforms.ToTensor(),
        transforms.Normalize([0.4264,0.4101,0.3946],[0.2236,0.2293,0.2361]),   # 均值、方差
    ])),
    batch_size=1, # 每批样本个数  # 一个batch的样本数目通常设为2的n次幂，网络较小时选用256，较大时选用64
    shuffle=False,  # 是否打乱顺序
    num_workers=0,  # 10, # 读取的线程个数
)

################################  函数定义区  ######################################
def length_train(train_loader, model, criterion, optimizer, epoch):
    # 训练模式
    model.train()  # 启用batch normalization和dropout
    data_num = 0
    for x in train_loader:
        for i, (input, target) in enumerate(x):
            data_num += 1
            c = model(input)  # 调用的是模型的forward函数

            loss = criterion(c, target)
            # if not (data_num % 300):
            print('Epoch: {}  Loss: {}/{}'.format(epoch + 1, loss, data_num))
            optimizer.zero_grad()  # 梯度清零(每个batch都要清零)
            loss.backward()  # 误差反向传播
            optimizer.step()  # 模型参数更新

def length_validate(valid_loader, model, criterion):
    # 测试模式
    model.eval()   # 不启用BatchNormalization和Dropout
    val_loss = []
    sum = 0

    # 不记录模型梯度信息
    with torch.no_grad():
        for i, (input, target) in enumerate(valid_loader):
            c = model(input)  # 调用的是模型的forward函数
            idx = torch.argmax(c, dim=1)  # 如果最大为10，选用第二大的
            if idx.item() == target.item():
                sum += 1
            loss = criterion(c, target)
            val_loss.append(loss.item())

    return sum*1.0/10000, np.mean(val_loss)  # 返回验证集中的平均误差值

'''  字符长度识别部分  '''
model = Length_Recognition_model()  # 基于Resnet的预训练模型
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), 0.001)  # 学习率可能大了
#####################
train_epoch = 10
best_loss = 1000
for epoch in range(train_epoch):
    loader = [trainlength_loader, trainlength_loader, trainlength_loader]
    length_train(loader, model, criterion, optimizer, epoch)
    acc_loss, val_loss = length_validate(validlength_loader, model, criterion)
    print('Valid----Epoch: {}/{}  AccLoss: {}, LogLoss: {}'.format(epoch + 1, train_epoch, acc_loss, val_loss))
    # 记录下验证集精度,储存验证集误差最小时模型的参数
    if val_loss < best_loss:
        print('当前验证集最大准确率为: ', val_loss)
        best_loss = val_loss
        # state_dict()表示模型的参数字典,包含优化器对象、存储了优化器的状态、所使用到的超参数
        torch.save(model.state_dict(), './Length_model.pt')
print('长度识别模型: ', best_loss)


from annoying.decorators import JsonResponse
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.http import Http404
from django.shortcuts import get_object_or_404
from saveditems.models import SavedItem
from utils.decorators import login_required
from core.search import reindex
from utils.shortcuts import redirect_to_next_url

@login_required
def save(request, slug=None, model=None):
    """ Save item if it isn't saved.
    Unsave item if it's saved. """

    if not slug or not model:
        raise Http404()

    item = get_object_or_404(model, slug=slug)

    content_type = ContentType.objects.get_for_model(item)
    object_id = item.id
    SavedItem.objects.get_or_create(content_type=content_type,
                          object_id=object_id,
                          user=request.user)

    reindex(item)

    if request.is_ajax():
        return JsonResponse(dict(status="success",
                                 message=u"Item was saved in your collection."))

    messages.success(request, u"Item was saved in your collection.")
    return redirect_to_next_url(request, item.get_absolute_url())

@login_required
def unsave(request, slug=None, model=None):

    if not slug or not model:
        raise Http404()

    item = get_object_or_404(model, slug=slug)

    content_type = ContentType.objects.get_for_model(item)
    object_id = item.id
    try:
        SavedItem.objects.get(content_type=content_type,
                              object_id=object_id,
                              user=request.user).delete()

        reindex(item)

        if request.is_ajax():
            return JsonResponse(dict(status="success",
                                     message=u"Item was removed from your collection."))

        messages.success(request, u"Item was removed from your collection.")
    except SavedItem.DoesNotExist:
        pass

    return redirect_to_next_url(request, item.get_absolute_url())


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 06 21:45:09 2016

@author: Juan
"""

import numpy as np
import matplotlib.pyplot as plt
import scipy.io.wavfile as wav
from scipy import signal

if __name__=='__main__':

    melcoeff = 20
    melbands = 40

    artist = 'claire'
    audio_file = "../audio/" + artist + "_mono.wav"
    proba_csv = "../prediction/" + artist + "_mfcc_" + str(melcoeff) + str(melbands) + "_proba.csv"
    prediction_csv= "../prediction/" + artist + "_mfcc_" + str(melcoeff) + str(melbands) + "_prediction.csv"
#    audio_file='../audio/LP-mem-6-a.wav'

    fs, x = wav.read(audio_file)
    t = np.arange(len(x)) * (1/fs)

    proba = np.loadtxt(proba_csv)
    prediction = np.loadtxt(prediction_csv)

    from PIL import Image
    import numpy as np

    aux=prediction[np.argsort(prediction[:,2]),1]
    r_gt=np.zeros(aux.shape,dtype='uint8')
    g_gt=np.zeros(aux.shape,dtype='uint8')
    b_gt=np.zeros(aux.shape,dtype='uint8')
    r_gt[aux==1]=1
    g_gt[aux==2]=1
    b_gt[aux==3]=1

    for i in range(0,9):
        r_gt=np.c_[r_gt,r_gt]
        g_gt=np.c_[g_gt,g_gt]
        b_gt=np.c_[b_gt,b_gt]

    rgbArray_gt = np.zeros((r_gt.shape[1],r_gt.shape[0],3), 'uint8')
    rgbArray_gt[..., 0] = r_gt.T*255
    rgbArray_gt[..., 1] = g_gt.T*255
    rgbArray_gt[..., 2] = b_gt.T*255

    r=np.c_[proba[np.argsort(proba[:,3]),0],proba[np.argsort(proba[:,3]),0]]
    g=np.c_[proba[np.argsort(proba[:,3]),1],proba[np.argsort(proba[:,3]),1]]
    b=np.c_[proba[np.argsort(proba[:,3]),2],proba[np.argsort(proba[:,3]),2]]
    for i in range(0,8):
        r=np.c_[r,r]
        g=np.c_[g,g]
        b=np.c_[b,b]

    rgbArray = np.zeros((r.shape[1],r.shape[0],3), 'uint8')

    rgbArray[..., 0] = r.T*255
    rgbArray[..., 1] = g.T*255
    rgbArray[..., 2] = b.T*255

    rgbArray_mix=np.zeros((2*r.shape[1],r.shape[0],3), 'uint8')

    rgbArray_mix[0:512,:,:]=rgbArray
    rgbArray_mix[512:1024,:,:]=rgbArray_gt
    img_mix = Image.fromarray(rgbArray_mix)
    img_mix.save(artist+'_mix.jpeg')


common = 0
commonPairs=0

with open('4.txt', 'r') as f:
    lines = f.read().splitlines()

for s in lines:
    a, b = s.split(',')
    a = a.split('-')
    b = b.split('-')

    aRange = (list(range(int(a[0]), int(a[1])+1)))
    bRange = (list(range(int(b[0]), int(b[1])+1)))

    if set(aRange).issubset(set(bRange)):
        #p1
        common += 1

    elif set(bRange).issubset(set(aRange)):
        common += 1

    #p2
    commonPairs += any(set(aRange).intersection(set(bRange)))


# Othello Game Logic

DIRECTIONS=[[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]]

class Othello:

    def __init__(self,row,col,turn,corner,board):
        ''' default constructor'''
        self._row=row
        self._col=col
        self._turn=turn
        self._corner=corner
        self._board=board

    def game_board(self):
        '''
         create a game board as per the given row and col size , set the game state
        '''
        if(self._corner.upper()== 'W'):
            opponent= 'B'
        else:
            opponent='W'

        board = []
        for i in range(self._row):
            board.append([' '] * self._col)
        board[int(self._row/2)-1][int(self._col/2)-1]=self._corner
        board[int((self._row/2))][int((self._col/2))]=self._corner
        board[int(self._row/2)-1][int(self._col/2)]=opponent
        board[int((self._row/2))][int((self._col/2)-1)]=opponent
        self._board=board

    def display_board(self):
        '''
         display the game board
        '''

        for row in range(len(self._board)):
            for column in range(len(self._board[row])):
                print(self._board[row][column], end = ' ')
            print()

    def plug_piece(self,i:int, j:int):
        '''
        plug in the desired piece onto the board
        '''
        self.valid_row(i)
        self.valid_col(j)
        if(self.isValid(i,j)):
            moves=self.getMoves(i,j)
            if(len(moves)>0):
                return self.makeMove(moves)
            else:
                return False

    def isValid(self,i:int, j:int):
        '''
        Checks if the move passed in was valid. IF it  is valid, it will return True, other wise it will return false.
        '''
        if((self._board[i][j] !=' ') or (not self.onBound(i,j))):
            return False
        else:
            return True

    def onBound(self,i:int,j:int)->bool:
        '''
        check the boundary of the row and col  that are allowed
        '''
        return((i>=0 and i<=len(self._board)) and (j>=0 and j<=len(self._board[0])))

    def getMoves(self,i:int,j:int)->list:
        '''
        set the move and alternate the player's turn
        '''
        opposite=self.switch_turn()
        validboxes=[]
        for a ,b in DIRECTIONS:
            x,y= i ,j
            x += a
            y += b
            try:
                if(self.onBound(x,y)and self._board[x][y]==opposite):
                        x += a
                        y += b

                        while self._board[x][y]==opposite:
                            x += a
                            y += b

                        if self._board[x][y]==self._turn:
                            while True:
                                x -= a
                                y -= b
                                validboxes.append([x,y])
                                if x == i and y == j:
                                    break
            except:
                continue

        return validboxes

    def getValidMoves(self):

        AllowedMoves=[]
        for x in range(len(self._board)):
            for y in range(len(self._board[0])):
                if (self.getMoves(x,y)) != [] and self.isValid(x,y):
                    AllowedMoves.append([x+1,y+1])
        return AllowedMoves

    def makeMove(self,List:[]):

        for x,y in List:
            N_Board=self._board[:]
            N_Board[x][y]=self._turn
        self._board=N_Board
        self._turn=self.switch_turn()
        return Othello(self._row,self._col,self._turn,self._corner,self._board)

    def switch_turn(self)->str:
        '''
        Returns the opposite turn.
        '''
        if self._turn=='W':
            return 'B'
        else:
            return 'W'

    def get_count(self,color:str):
        '''
        Counts the Total number of disc for each plauer .
        '''
        total =0
        for x in range(len(self._board)):
            for y in range(len(self._board[0])):
                if self._board[x][y]==color:
                    total +=1
        return total

    def winner_more(self):
        '''
         determine winning condition for player with more discs
        '''
        white_piece=self.get_count("W")
        black_piece=self.get_count("B")
        if(white_piece>black_piece):
            return("Player White wins")
        elif(white_piece < black_piece):
            return("Black  Player Wins")
        elif(white_piece  == black_piece):
           return("It is a Tie, No one is winner")

    def winner_less(self):
        '''
         determine winning condition for player with less discs
        '''
        white_piece=self.get_count("W")
        black_piece=self.get_count("B")
        if(white_piece < black_piece):
            return("Player white wins")
        elif(white_piece  > black_piece):
            return("Player black wins")
        elif(white_piece  == black_piece):
            return("It is a Tie, No one is winner")

    def valid_row(self,row):
        ''' handle the exception when invalid row is given'''
        if (type(row)!= int) or (not self.validate_row(row)):
             raise ValueError('Invalid')

    def validate_row(self,row) -> bool:
        '''check if the given row is valid or not'''
        return 0 <= row < len(self._board)

    def valid_col(self,column_num):
        ''' handle the exception when invalid col is given'''
        if (type(column_num)!= int) or (not self.validate_col(column_num)):
             raise ValueError("Inavalid")

    def validate_col(self,col) -> bool:
        '''check if the given row is valid or not'''
        return 0 <= col < len(self._board[0])


import evokit.chromosome as chr
import evokit.crossover as cr
import evokit.mutation as mu
import evokit.ga as ga

def main():
    fitness = lambda ch : ((ch.values[0] - 1) ** 2) + (ch.values[1] ** 2) + ((ch.values[2] + 1) ** 2)
    chromosomeFactory = chr.NumericChromosomeFactory(3, -5000, 5000)
    crossover = cr.SimulatedBinaryCrossover()
    mutation = mu.NormalDistributionMutation(1)
    result = ga.geneticAlgorithm(fitness, chromosomeFactory, 100, crossover, mutation, 1000)

    print("Best fitness:", result["fitness"])
    print("Best solutions:", result["solution"].values)
    result["observer"].plot()

if __name__ == "__main__":
    main()


def fully_contains(a ,b):
    return (a[0] >= b[0] and a[-1] <= b[-1]) or (b[0] >= a[0] and b[-1] <= a[-1])

def overlaps(a, b):
    range_a = range(a[0], a[-1]+1)
    range_b = range(b[0], b[-1]+1)

    for a in range_a:
        if a in range_b:
            return 1

    return 0

def run():

    f = open('input.txt','r').read().rstrip().split()

    r1 = 0
    r2 = 0
    for line in f:
        s = line.split(',')
        a = s[0].split('-')
        b = s[-1].split('-')
        a = [int(x) for x in a]
        b = [int(x) for x in b]
        r1 += fully_contains(a, b)
        r2 += overlaps(a, b)

    print(r1)
    print(r2)
if __name__ == '__main__':
    run()


from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import tensorflow as tf
from transformers import (
    DistilBertTokenizerFast, TFDistilBertForSequenceClassification, TFTrainer,
    TFTrainingArguments
)

from prep_data import load_data

tokenizer_config = {
    'truncation': True,
    'padding': 'max_length',
    'max_length': 128
}
tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-cased')

def prepare_dataset(dataset, n_examples):
    text, prices = load_data(dataset, n_examples)
    encoded_text = tokenizer(text, **tokenizer_config)
    return tf.data.Dataset.from_tensor_slices((
        dict(encoded_text),
        prices
    ))

def train():
    train_dataset = prepare_dataset('train', 100000)
    val_dataset = prepare_dataset('validate', 30000)

    training_args = TFTrainingArguments(
        output_dir='./results',
        num_train_epochs=1,
        per_device_train_batch_size=16,
        per_device_eval_batch_size=64,
        warmup_steps=500,
        weight_decay=0.01,
        logging_dir='./logs',
        logging_steps=10,
    )

    with training_args.strategy.scope():
        model = TFDistilBertForSequenceClassification.from_pretrained(
            "distilbert-base-cased", num_labels=1
        )

    trainer = TFTrainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset,
        eval_dataset=val_dataset
    )

    trainer.train()
    trainer.save_model()

    return trainer

def evaluate(trainer):
    test_dataset = prepare_dataset('test', 30000)
    preds = trainer.predict(test_dataset)
    labels = [1, 2, 3, 4]

    conf_matrix = confusion_matrix(
        preds.label_ids, preds.predictions.round(), labels=labels
    )
    (
        ConfusionMatrixDisplay(conf_matrix, display_labels=labels)
        .plot().figure_.savefig('conf-matrix.png')
    )

if __name__ == '__main__':
    trainer = train()
    evaluate(trainer)


from typing import List

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        import operator
        d = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}
        stack = []
        for i in tokens:
            if i in d:
                a = int(stack.pop())
                b = int(stack.pop())
                stack.append(int(d[i](b, a)))
            else:
                stack.append(i)
        if len(stack) == 1:
            return stack.pop()
        else:
            return False


import cv2
import imutils
import numpy as np

class EyeTracker:
    def __init__(self, faceCascadePath, eyeCascadePath):
        # Initializerar 2 objekt, av Cascade Classifiers,
        self.faceCascade = cv2.CascadeClassifier(faceCascadePath)
        self.eyeCascade = cv2.CascadeClassifier(eyeCascadePath)

    def track(self, img):
        face_rectangles = self.faceCascade.detectMultiScale(img, scaleFactor=1.1,
                                                  minNeighbors=5, minSize=(30,30),
                                                  flags=cv2.CASCADE_SCALE_IMAGE)
        rects = []

        #Börjar leta efter ögonen
        for (fX, fY, fW, fH) in face_rectangles:
            #vi skapar ett område för ansiktsregionen via rektangeln
            faceROI = img[fY:fY + fH, fX:fX+fW]
            #Appendar rektangel till rects, för senare användning
            # rects.append((fX, fY, fX + fW, fY + fH))

            #Därefter letar vi nu efter ögonen inuti ansiktsregionen, fast med andra parametervärden, för att reducera false positives.
            eye_rectangles = self.eyeCascade.detectMultiScale(faceROI, scaleFactor=1.1, minNeighbors= 10, minSize=(20,20), flags=cv2.CASCADE_SCALE_IMAGE)

            #Vi appendar rektanglarna ifrån eye rektangels, till listan över rektangles.
            for (eX, eY, eW, eH) in eye_rectangles:
                rects.append((fX + eX, fY + eY, fX + eX + eW, fY + eY + eH))

        return rects

ec = EyeTracker("haarcascade_frontalface_default.xml", "haarcascade_eye.xml")
cam = cv2.VideoCapture(0)

while True:
    (grabbed, frame) = cam.read()

    # standard korrigeringar
    frame = imutils.resize(frame, 400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #Svart canavas
    canavas = np.zeros(frame.shape[:2], dtype="uint8")

    #Hämtar rektanglarna som returneras utav Cascade Classifiersen i track()
    rectangles = ec.track(gray)

    #Vi börjar loopa över rektanglarna och målar upp dem,
    # for rect in rectangles:
    #     cv2.rectangle(canavas, (rect[0],rect[1]),(rect[2],rect[3]), (np.random.randint(0,256),np.random.randint(0,256),np.random.randint(0,256)), 2)

    #Alternativ
    #Måla upp cirklar som varierar i färg
    for rect in rectangles:
        centerX = (rect[0]+ rect[2]) // (2)
        centerY = (rect[1] + rect[3]) // (2)

        radius = rect[2] - rect[0]
        radius = int(radius / 2)
        print(radius)

        cv2.circle(canavas, (centerX, centerY), radius , (np.random.randint(0,256),np.random.randint(0,256), np.random.randint(0,256)),-1)

    #Visar
    cv2.imshow("Tracking",cv2.bitwise_and(frame,frame, mask=canavas))

    #bryter
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cam.release()
cv2.destroyAllWindows()


import pandas as pd

# read the csv file and create a dict from it of format {"letter": "code"}
PATH = "nato_phonetic_alphabet.csv"
nato_df = pd.read_csv(PATH)
nato_phonetic_alphabet_dict = {row["letter"]: row["code"] for (index, row) in nato_df.iterrows()}

# compare each letter from users input to the dict and print the phonetic code for the letter
user_input = input("What is the word? :").upper()
phonetic_code = [nato_phonetic_alphabet_dict[letter] for letter in user_input]
print(phonetic_code)

Day 26/Program Day 26/NATO-alphabet project/NATO-alphabet-start/main.py


from ogspy.base import OGS_File

class OUT(OGS_File):

    """
    Class for the ogs output file.

    History
    -------
    Written,  JM, Jul 2015
    Modified, FH, Jul 2015 - rewritten for geneneral purpose ogs projects

    """

    def __init__(self, **OGS_Config):
        '''
        Input
        ----------

        OGS_Config dictonary

        '''

        OGS_File.__init__(self, **OGS_Config)

        self.f_type = '.out'

        self.nod_values = []
        self.geo_type = []
        self.geo_name = []
        self.dat_type = []
        self.tim_type = []
        self.block_no = 0

    def add_block(self, nod_values = 'HEAD', geo_type = 'DOMAIN',
                  geo_name = None, dat_type = 'VTK', tim_type = 'STEPS 1'):

        self.nod_values.append(nod_values)
        self.geo_type.append(geo_type)
        self.geo_name.append(geo_name)
        self.dat_type.append(dat_type)
        self.tim_type.append(tim_type)

        self.block_no += 1

    def gen_f_str(self):

        f_out = ''
        for block_i in range (0, self.block_no):

            f_out += '#OUTPUT' + self.eol
            f_out += self.sid + '$NOD_VALUES' + self.eol
            f_out += self.did + str(self.nod_values[block_i]) + self.eol
            f_out += self.sid + '$GEO_TYPE' + self.eol
            f_out += self.did + str(self.geo_type[block_i])
            if self.geo_name[block_i]:
                f_out += ' ' + str(self.geo_name[block_i])
            f_out += self.eol
            f_out += self.sid + '$DAT_TYPE' + self.eol
            f_out += self.did + str(self.dat_type[block_i]) + self.eol
            f_out += self.sid + '$TIM_TYPE' + self.eol
            f_out += self.did + str(self.tim_type[block_i]) + self.eol

        f_out += '#STOP'
        self.f_str = f_out