from tkinter import *
from PIL import ImageGrab
import numpy as np
import cv2
import time
import pyautogui as pg
import DirectInputRoutines as DIR
from LogKey import key_check
last_time = time.time()
one_hot = [0, 0, 0, 0, 0, 0]
hash_dict = {'w':0, 's':1, 'a':2, 'd':3, 'c':4, 'v':5}
X = []
y = []


def auto_canny(image, sigma=0.33):
	# compute the median of the single channel pixel intensities
	v = np.median(image)
	# apply automatic Canny edge detection using the computed median
	lower = int(max(0, (1.0 - sigma) * v))
	upper = int(min(255, (1.0 + sigma) * v))
	edged = cv2.Canny(image, lower, upper)
	# return the edged image
	return edged
def process_img(original_image):
    processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
    processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300)
    processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300)
    #processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300)
    
    vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500],
                         ], np.int32)

    processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
    processed_img = roi(processed_img, [vertices])

    # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
    #                          edges       rho   theta   thresh         # min length, max gap:        
    #lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180,      20,         15)
    #draw_lines(processed_img,lines)
    return processed_img


def roi(img, vertices):
    #blank mask:
    mask = np.zeros_like(img)
    # fill the mask
    cv2.fillPoly(mask, vertices, 255)
    # now only show the area that is the mask
    masked = cv2.bitwise_and(img, mask)
    return masked


def draw_lines(img,lines):
    for line in lines:
        coords = line[0]
        cv2.line(img, (coords[0], coords[1]), (coords[2], coords[3]), [255,255,255], 3)

def change_tab():
    pg.hotkey("alt","tab")
def send_key(e):
    hash = {"w":DIR.W, "a":DIR.A, "s":DIR.S, "d":DIR.D}
    return hash[e.keysym]
def keyup(e):
    
    if(e.keysym == "Alt_L" or e.keysym == "Tab"):
        return
    #print('down', e.keysym)
    change_tab()
    DIR.ReleaseKey(send_key(e))
    change_tab()
    global last_time
    one_hot[hash_dict[e.keysym]] = 0
    temp = list(one_hot)
    printscreen =  np.array(ImageGrab.grab(bbox=(0,40,800,640)))
    printscreen = process_img(printscreen)
    print('loop took {} seconds'.format(time.time()-last_time))
    print([printscreen, temp])
    last_time = time.time()
    X.append(printscreen)
    y.append(temp)
    #cv2.imshow("image", printscreen)

def keydown(e):
    #print('up', e.keysym)
    if(e.keysym == "Alt_L" or e.keysym == "Tab"):
        return
    change_tab()
    DIR.ReleaseKey(send_key(e))
    change_tab()
    global last_time
    one_hot[hash_dict[e.keysym]] = 1
    temp = list(one_hot)
    printscreen =  np.array(ImageGrab.grab(bbox=(0,40,800,680)))
    printscreen = process_img(printscreen)
    print('loop took {} seconds'.format(time.time()-last_time))
    print([printscreen,temp])
    last_time = time.time()
    X.append(printscreen)
    y.append(temp)

root = Tk()
frame = Frame(root, width=100, height=100)
frame.bind("<KeyPress>", keydown)
frame.bind("<KeyRelease>", keyup)
frame.pack()
frame.focus_set()
root.mainloop()
np.save("X.npy", X)
np.save("y.npy", y)
[((9, 12, 9, 23), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((109, 0, 109, 19), 'numpy.save', 'np.save', ({(109, 8, 109, 15): '"""X.npy"""', (109, 17, 109, 18): 'X'}, {}), "('X.npy', X)", True, 'import numpy as np\n'), ((110, 0, 110, 19), 'numpy.save', 'np.save', ({(110, 8, 110, 15): '"""y.npy"""', (110, 17, 110, 18): 'y'}, {}), "('y.npy', y)", True, 'import numpy as np\n'), ((18, 5, 18, 21), 'numpy.median', 'np.median', ({(18, 15, 18, 20): 'image'}, {}), '(image)', True, 'import numpy as np\n'), ((22, 9, 22, 39), 'cv2.Canny', 'cv2.Canny', ({(22, 19, 22, 24): 'image', (22, 26, 22, 31): 'lower', (22, 33, 22, 38): 'upper'}, {}), '(image, lower, upper)', False, 'import cv2\n'), ((26, 20, 26, 68), 'cv2.cvtColor', 'cv2.cvtColor', ({(26, 33, 26, 47): 'original_image', (26, 49, 26, 67): 'cv2.COLOR_BGR2GRAY'}, {}), '(original_image, cv2.COLOR_BGR2GRAY)', False, 'import cv2\n'), ((27, 20, 27, 76), 'cv2.Canny', 'cv2.Canny', (), '', False, 'import cv2\n'), ((28, 20, 28, 76), 'cv2.Canny', 'cv2.Canny', (), '', False, 'import cv2\n'), ((31, 15, 32, 37), 'numpy.array', 'np.array', ({(31, 24, 32, 26): '[[10, 500], [10, 300], [300, 200], [500, 200], [800, 300], [800, 500]]', (32, 28, 32, 36): 'np.int32'}, {}), '([[10, 500], [10, 300], [300, 200], [500, 200], [800, 300], [800, \n    500]], np.int32)', True, 'import numpy as np\n'), ((34, 20, 34, 59), 'cv2.GaussianBlur', 'cv2.GaussianBlur', ({(34, 37, 34, 50): 'processed_img', (34, 51, 34, 56): '(5, 5)', (34, 57, 34, 58): '0'}, {}), '(processed_img, (5, 5), 0)', False, 'import cv2\n'), ((46, 11, 46, 29), 'numpy.zeros_like', 'np.zeros_like', ({(46, 25, 46, 28): 'img'}, {}), '(img)', True, 'import numpy as np\n'), ((48, 4, 48, 37), 'cv2.fillPoly', 'cv2.fillPoly', ({(48, 17, 48, 21): 'mask', (48, 23, 48, 31): 'vertices', (48, 33, 48, 36): '(255)'}, {}), '(mask, vertices, 255)', False, 'import cv2\n'), ((50, 13, 50, 39), 'cv2.bitwise_and', 'cv2.bitwise_and', ({(50, 29, 50, 32): 'img', (50, 34, 50, 38): 'mask'}, {}), '(img, mask)', False, 'import cv2\n'), ((60, 4, 60, 26), 'pyautogui.hotkey', 'pg.hotkey', ({(60, 14, 60, 19): '"""alt"""', (60, 20, 60, 25): '"""tab"""'}, {}), "('alt', 'tab')", True, 'import pyautogui as pg\n'), ((79, 16, 79, 27), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((98, 16, 98, 27), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((57, 8, 57, 87), 'cv2.line', 'cv2.line', ({(57, 17, 57, 20): 'img', (57, 22, 57, 44): '(coords[0], coords[1])', (57, 46, 57, 68): '(coords[2], coords[3])', (57, 70, 57, 83): '[255, 255, 255]', (57, 85, 57, 86): '(3)'}, {}), '(img, (coords[0], coords[1]), (coords[2], coords[3]), [255, 255, \n    255], 3)', False, 'import cv2\n'), ((75, 28, 75, 63), 'PIL.ImageGrab.grab', 'ImageGrab.grab', (), '', False, 'from PIL import ImageGrab\n'), ((94, 28, 94, 63), 'PIL.ImageGrab.grab', 'ImageGrab.grab', (), '', False, 'from PIL import ImageGrab\n'), ((77, 40, 77, 51), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((96, 40, 96, 51), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n')]