Guest User

Untitled

a guest
Apr 23rd, 2019
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.19 KB | None | 0 0
  1. #!/usr/bin/python3
  2. from pynput.keyboard import Key
  3. import pynput.keyboard as keyboardO
  4. from pynput.mouse import Button
  5. import pynput
  6.  
  7. mouse = pynput.mouse.Controller()
  8.  
  9. import keyboard
  10. import cv2
  11. import numpy
  12. import sys
  13. import PyQt5
  14. import os
  15. import atexit
  16. import socket
  17.  
  18. dirname = os.path.dirname(PyQt5.__file__)
  19. plugin_path = os.path.join(dirname, 'plugins', 'platforms')
  20. os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
  21.  
  22. from PyQt5 import QtWidgets
  23. import configparser
  24. from PyQt5.QtCore import *
  25. from PyQt5 import QtGui
  26. from PyQt5 import QtCore
  27. from PyQt5.QtWidgets import *
  28. from PyQt5 import uic
  29. from threading import Thread
  30. import datetime
  31. from time import sleep
  32. import pickle
  33. from copy import deepcopy
  34. import sys
  35.  
  36. keyboardB = keyboardO.Controller()
  37.  
  38. canvasWidth = 1200
  39. canvasHeight = 800
  40.  
  41. startPositionX = 300
  42. startPositionY = 300
  43.  
  44. countdown = 3
  45. timeBetweenCommand = 2
  46.  
  47. ping_before_command = True
  48. ping_address = "www.google.com"
  49. ping_port = 80
  50. internet_reconnect_auto_unpause = True
  51.  
  52.  
  53. def get_platform():
  54.     platforms = {
  55.         'linux1': 'Linux',
  56.         'linux2': 'Linux',
  57.         'darwin': 'OS X',
  58.         'win32': 'Windows'
  59.     }
  60.     if sys.platform not in platforms:
  61.         return sys.platform
  62.  
  63.     return platforms[sys.platform]
  64.  
  65. platform = get_platform()
  66.  
  67. currentPath = os.path.dirname(os.path.realpath(__file__))
  68.  
  69. if platform == 'linux':
  70.     imageFolder = currentPath + "/Image"
  71.     progressFolder = currentPath + "/Progress"
  72.     configPath = currentPath + "/config.ini"
  73. else:
  74.     imageFolder = currentPath + "\Image"
  75.     progressFolder = currentPath + "\Progress"
  76.     configPath = currentPath + "\config.ini"
  77. config = configparser.ConfigParser()
  78. config.read(configPath)
  79. mainWindow = None
  80. startPlacing = False
  81. pause = False
  82. commands = None
  83. errorMsg = ""
  84. progress = 0
  85. recentImagePath = None
  86. internetPause = False
  87. mouse_move = False
  88. mouseStartPosition = None
  89. startTime = None
  90. canSaveAgain = True
  91.  
  92. """
  93. Gets image from image folder and converts it in to a numpy array
  94. """
  95. def imageToArray(path):
  96.     global recentImagePath
  97.     recentImagePath = path
  98.     print(path)
  99.     im = cv2.imread(path, cv2.IMREAD_UNCHANGED)
  100.     return im
  101.  
  102.  
  103. """
  104. Main Window, mainly handles data input
  105.  
  106. """
  107.  
  108. class PrimaryWindow(QMainWindow):
  109.  
  110.     """
  111.    PyQt signals for updating the GUI from the worker threads
  112.    """
  113.     createError = pyqtSignal()
  114.     updateTimeLeft = pyqtSignal()
  115.  
  116.     def __init__(self):
  117.         QWidget.__init__(self)
  118.         uic.loadUi("window.ui", self)
  119.         self.addItemSelection()
  120.         self.addProgressSelection()
  121.         #self.loadUIC()
  122.         self.move(200, 200)
  123.         self.convertCommands.clicked.connect(self.convertIntoCommands)
  124.         self.loadProgress.clicked.connect(self.loadProgressFromFile)
  125.         self.reload.clicked.connect(self.reloadImage)
  126.         self.begin.clicked.connect(beginProcess)
  127.         self.pause.clicked.connect(lambda: self.toggleProcess(True))
  128.         self.terminate.clicked.connect(lambda: self.toggleProcess(False))
  129.         self.saveProgress.clicked.connect(lambda: saveProgress())
  130.         self.loadConfigValues()
  131.         self.createError.connect(self.showErrorBox)
  132.         self.updateTimeLeft.connect(self.updateRunning)
  133.         self.progressBar.setValue(0)
  134.         self.folderpath.setText(str(imageFolder))
  135.         print(imageFolder)
  136.         if not os.path.isfile(imageFolder):
  137.             try:
  138.                 os.makedirs(imageFolder)
  139.                 print("couldn't find image folder creating one")
  140.             except:
  141.                 print("skippin exception")
  142.         else:
  143.             print("found image folder")
  144.  
  145.     def toggleProcess(self, flag):
  146.         global pause
  147.         pause = flag
  148.  
  149.     def loadProgressFromFile(self):
  150.         global commands, progress, pause, recentImagePath
  151.         if os.path.exists(progressFolder):
  152.             savedDetails = os.listdir(progressFolder)
  153.             loadTemp = []
  154.             for detail in savedDetails:
  155.                 if platform == 'linux':
  156.                     with open(progressFolder + "/" + detail, "rb") as input:
  157.                         loadTemp.append(pickle.load(input))
  158.                 else:
  159.                     with open(progressFolder + "\\" + detail, "rb") as input:
  160.                         loadTemp.append(pickle.load(input))
  161.  
  162.             for temp in loadTemp:
  163.                 if temp.imageName == str(self.toBeLoaded.currentText()).split(".")[0]:
  164.                     self.commands = deepcopy(temp.commands)
  165.                     commands = deepcopy(temp.commands)
  166.                     progress = temp.progress
  167.                     print(progress)
  168.                     self.allCommands.clear()
  169.                     if platform == 'linux':
  170.                         recentImagePath = imageFolder + "/" + temp.imageName + ".png"
  171.                     else:
  172.                         recentImagePath = imageFolder + "\\" + temp.imageName + ".png"
  173.                     pause = True
  174.                     for i in range(len(commands)):
  175.                         self.allCommands.append(
  176.                             "(" + str(i + 1) + "/" + str(len(commands)) + ") " + str(commands[i]))
  177.         else:
  178.             print("No progress folder found")
  179.  
  180.     def addProgressSelection(self):
  181.         self.toBeLoaded.clear()
  182.         if os.path.exists(progressFolder):
  183.             savedDetails = os.listdir(progressFolder)
  184.             self.toBeLoaded.addItems(savedDetails)
  185.             for detail in savedDetails:
  186.                 if platform == 'linux':
  187.                     with open(progressFolder + "/" + detail, "rb") as input:
  188.                         load = pickle.load(input)
  189.                         self.progressArea.append(str((str(load.imageName), str(load.progress) + "/" + str(load.maxProgress), str(round((load.progress / load.maxProgress), 2) * 100) + "%")))
  190.                 else:
  191.                     with open(progressFolder + "\\" + detail, "rb") as input:
  192.                         load = pickle.load(input)
  193.                         self.progressArea.append(str((str(load.imageName), str(load.progress) + "/" + str(load.maxProgress), str(round((load.progress / load.maxProgress), 2) * 100) + "%")))
  194.  
  195.         else:
  196.             print("No progress folder found")
  197.  
  198.     def addItemSelection(self):
  199.         self.imageName.clear()
  200.         if os.path.exists(imageFolder):
  201.             savedDetails = os.listdir(imageFolder)
  202.             self.imageName.addItems(savedDetails)
  203.  
  204.     def reloadImage(self):
  205.         global errorMsg
  206.         savedContracts = os.listdir(imageFolder)
  207.         if savedContracts:
  208.             try:
  209.                 if platform == 'linux':
  210.                     self.loadImage(imageFolder + '/' + self.imageName.currentText())
  211.                 else:
  212.                     self.loadImage(imageFolder + '\\' + self.imageName.currentText())
  213.             except:
  214.                 errorMsg = "Couldn't find specified image: " + self.imageName.text()
  215.                 self.showErrorBox()
  216.         else:
  217.             print(imageFolder + "\\lol")
  218.             print("no images")
  219.  
  220.     def updateRunning(self):
  221.         self.progressBar.setValue((progress / len(self.commands) * 100))
  222.         estimated_seconds = (len(self.commands) - progress) * float(self.betweenCommand.text())
  223.         self.timeLeft.setText("Time Left: " + str(datetime.timedelta(seconds=estimated_seconds, milliseconds=0, microseconds=0)))
  224.         newTime = startTime + datetime.timedelta(seconds=(len(self.commands)) * float(self.betweenCommand.text()), milliseconds=0, microseconds=0)
  225.         self.estComplete.setText("Est. Complete: " + str(newTime))
  226.  
  227.     def showErrorBox(self):
  228.         global errorMsg
  229.         if not hasattr(self, "errorBox"):
  230.             self.errorBox = self.createCriticalMessage(errorMsg)
  231.  
  232.         if not self.errorBox.isVisible():
  233.             self.errorBox.show()
  234.  
  235.     def loadConfigValues(self):
  236.         self.canvasWidth.setText(str(canvasWidth))
  237.         self.canvasHeight.setText(str(canvasHeight))
  238.         self.startX.setText(str(startPositionX))
  239.         self.startY.setText(str(startPositionY))
  240.         self.betweenCommand.setText(str(timeBetweenCommand))
  241.         self.startTime.setText(str(countdown))
  242.  
  243.     def loadImage(self, imag):
  244.         self.image = imageToArray(imag)
  245.         image_shape = self.image.shape
  246.         self.image_width = image_shape[1]
  247.         self.image_height = image_shape[0]
  248.         self.total_pixels = self.image_width * self.image_height
  249.         self.coloredIndexs = numpy.where(self.image[:, :, 3:] != [0])
  250.         self.totalPixels.setText("Total Pixels: " + str(self.total_pixels))
  251.         self.coloredPixels.setText("Colored Pixels: " + str(len(self.coloredIndexs[0])) + " (" + str(int((len(self.coloredIndexs[0]) / self.total_pixels) * 100)) + "%)")
  252.         self.imageDimensions.setText("Image Dimensions: " + str((self.image_width, self.image_height)))
  253.  
  254.     def convertIntoCommands(self):
  255.         global commands
  256.  
  257.         try:
  258.             self.reloadImage()
  259.         except Exception:
  260.             self.noImages = self.createCriticalMessage("No Images in Image folder!")
  261.             self.noImages.show()
  262.             return
  263.  
  264.         if self.image_width + int(self.startX.text()) >= canvasWidth or self.image_height + int(self.startY.text()) >= canvasHeight:
  265.             self.totalCommands.setText("Change start positions! Current one with image dimensions goes out of canvas boundaries!")
  266.             return
  267.         self.commandsRaw = []
  268.         usedColors = []
  269.         for i in range(len(self.coloredIndexs[0])):
  270.             x = self.coloredIndexs[0][i]
  271.             y = self.coloredIndexs[1][i]
  272.             color = self.image[x, y, :3]
  273.  
  274.             if (y, x, color[2], color[1], color[0]) in self.commandsRaw:
  275.                 continue
  276.             currentColorCheck = (color[2], color[1], color[0])
  277.             for n in range(len(self.coloredIndexs[0])):
  278.                 x = self.coloredIndexs[0][n]
  279.                 y = self.coloredIndexs[1][n]
  280.                 color = self.image[x, y, :3]
  281.                 if color[2] == currentColorCheck[0] and color[1] == currentColorCheck[1] and color[0] == currentColorCheck[2]:
  282.                     if not (y, x, color[2], color[1], color[0]) in self.commandsRaw:
  283.                         self.commandsRaw.append((y, x, color[2], color[1], color[0]))
  284.  
  285.         self.commands = []
  286.  
  287.         last = (0, 0, 0)
  288.         for i in range(len(self.commandsRaw)):
  289.             if not self.commandsRaw[i][2] == last[0] or not self.commandsRaw[i][3] == last[1] or not self.commandsRaw[i][4] == last[2]:
  290.                 last = (self.commandsRaw[i][2], self.commandsRaw[i][3], self.commandsRaw[i][4])
  291.                 self.commands.append("setrgb(%s,%s,%s)" % (self.commandsRaw[i][2], self.commandsRaw[i][3], self.commandsRaw[i][4]))
  292.             self.commands.append("pp(%s,%s)" % (str(self.commandsRaw[i][0] + int(self.startX.text())), str(self.commandsRaw[i][1] + int(self.startY.text()))))
  293.  
  294.         for i in range(len(self.commands)):
  295.             self.allCommands.append("(" + str(i + 1) +"/" + str(len(self.commands)) + ") " + str(self.commands[i]))
  296.  
  297.         self.totalCommands.setText("Total Commands: " + str(len(self.commands)))
  298.         estimated_seconds = len(self.commands) * float(self.betweenCommand.text())
  299.         self.estimatedTime.setText("Estimated Time: " + str(datetime.timedelta(seconds=estimated_seconds, milliseconds=0, microseconds=0)))
  300.         self.convertCommands.setEnabled(False)
  301.         commands = self.commands
  302.         if not os.path.isfile(progressFolder):
  303.             try:
  304.                 os.makedirs(progressFolder)
  305.                 print("couldn't find progress folder creating one")
  306.             except:
  307.                 print("skippin exception")
  308.  
  309.  
  310.     def createCriticalMessage(self, error):
  311.         msg = QMessageBox()
  312.         msg.setIcon(QMessageBox.Critical)
  313.         msg.setWindowTitle("Error")
  314.         msg.setText(error)
  315.         msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
  316.         return msg
  317.  
  318.     def closeEvent(self, event):
  319.         exit_handler()
  320.     #def loadImage(self):
  321.  
  322. def create_connection(address, port):
  323.     if not ping_before_command:
  324.         return True
  325.     try:
  326.         socket.create_connection((address, port))
  327.         return True
  328.     except OSError:
  329.         pass
  330.     return False
  331.  
  332.  
  333. """
  334. Creates config file in the same directory
  335. These are the default values it puts in
  336. """
  337.  
  338. def generateConfigFile():
  339.  
  340.     """
  341.    Skip file creation if file exists goes to read function
  342.    """
  343.     if not os.path.isfile(configPath):
  344.         print("Created new config file in path: " + configPath)
  345.         config.add_section("settings")
  346.         config.set("settings", "canvas_width", "1360")
  347.         config.set("settings", "canvas_height", "768")
  348.         config.set("settings", "start_posX", "300")
  349.         config.set("settings", "start_posY", "300")
  350.         config.set("settings", "countdown", "3")
  351.         config.set("settings", "time_between_command", "2")
  352.         config.set("settings", "ping_before_command", "True")
  353.         config.set("settings", "ping_address", "www.google.com")
  354.         config.set("settings", "ping_port", "80")
  355.         config.set("settings", "internet_reconnect_auto_unpause", "True")
  356.         config.set("settings", "move_mouse", "True")
  357.         with open(configPath, 'w') as configfile:
  358.             config.write(configfile)
  359.     else:
  360.         print("Found config file")
  361.         loadValues()
  362.  
  363. """
  364. Populates global values
  365. """
  366. def loadValues():
  367.     global canvasWidth, canvasHeight, startPositionX, startPositionY, timeBetweenCommand, countdown, ping_before_command, ping_address, ping_port, internet_reconnect_auto_unpause
  368.     global mouse_move
  369.     config = configparser.ConfigParser()
  370.     config.read(configPath)
  371.     canvasWidth = config.getint("settings", "canvas_width")
  372.     canvasHeight = config.getint("settings", "canvas_height")
  373.     startPositionX = config.getint("settings", "start_posX")
  374.     startPositionY = config.getint("settings", "start_posY")
  375.     timeBetweenCommand = config.getint("settings", "time_between_command")
  376.     countdown = config.getint("settings", "countdown")
  377.     ping_before_command = config.getboolean("settings", "ping_before_command")
  378.     ping_address = config.get("settings", "ping_address")
  379.     ping_port = config.getint("settings", "ping_port")
  380.     internet_reconnect_auto_unpause = config.getboolean("settings", "internet_reconnect_auto_unpause")
  381.     mouse_move = config.getboolean("settings", "move_mouse")
  382.  
  383.  
  384.  
  385. class SaveImage():
  386.     def __init__(self, imageName, progress, maxProgress, commandsN):
  387.         self.imageName = imageName
  388.         self.progress = progress
  389.         self.maxProgress = maxProgress
  390.         self.commands = commandsN
  391.  
  392. def saveProgress():
  393.     if platform == 'linux':
  394.         imageName = recentImagePath.split("/Image/")[1]
  395.         imageName = imageName.split(".")[0]
  396.         newSave = SaveImage(imageName, progress, len(commands), commands)
  397.         newPath = progressFolder + "/" +  imageName + ".cmds"
  398.     else:
  399.         imageName = recentImagePath.split("\Image\\")[1]
  400.         imageName = imageName.split(".")[0]
  401.         newSave = SaveImage(imageName, progress, len(commands), commands)
  402.         newPath = progressFolder + "\\" +  imageName + ".cmds"
  403.     with open(newPath, "wb") as output:
  404.         pickle.dump(newSave, output, pickle.HIGHEST_PROTOCOL)
  405.     print("Saved progress to " + newPath)
  406.  
  407. class App():
  408.     def __init__(self):
  409.         application = QtWidgets.QApplication(sys.argv)
  410.         application.processEvents()
  411.         generateConfigFile()
  412.         global mainWindow
  413.         mainWindow = PrimaryWindow()
  414.         mainWindow.show()
  415.         sys.exit(application.exec_())
  416.  
  417.  
  418. def type(message):
  419.     keyboardB.type(message)
  420.     keyboardB.press(Key.enter)
  421.     keyboardB.release(Key.enter)
  422.  
  423. def placeCommands():
  424.     global commands, startPlacing, mainWindow, pause, progress, internetPause, mouse_move, mouseStartPosition
  425.     while True:
  426.         sleep(0.01)
  427.         if (startPlacing) and not pause:
  428.             time_between = float(mainWindow.betweenCommand.text())
  429.             for i in range(progress, len(commands), 1):
  430.                 if not pause:
  431.                     time1 = datetime.datetime.now()
  432.                     if create_connection(ping_address, ping_port):
  433.                         sleep(time_between)
  434.                         if mouse_move:
  435.                             mouse.position = (mouseStartPosition[0], mouseStartPosition[1])
  436.                             mouse.press(Button.left)
  437.                             mouse.release(Button.left)
  438.                         time2 = datetime.datetime.now()
  439.                         workerThreadUpdateTime = (time2 - time1)
  440.                         print("Placing " + str(i + 1) + "/" + str(len(commands)) + ' took ' + str(workerThreadUpdateTime))
  441.                         type(commands[i])
  442.                         progress = i
  443.  
  444.                         mainWindow.updateTimeLeft.emit()
  445.                         if i == len(commands) - 1:
  446.                             print('Finished!')
  447.                             startPlacing = False
  448.                     else:
  449.                         print("lost internet connection")
  450.                         if internet_reconnect_auto_unpause:
  451.                             internetPause = True
  452.                         else:
  453.                             pause = True
  454.                             print("Auto unpause after internet reconnect is not turned on. Go into the config to unpause automatically after internet reconnect.")
  455.                 else:
  456.                     onPause()
  457.                 if internetPause:
  458.                     onPause()
  459.                     while not create_connection(ping_address, ping_port):
  460.                         sleep(2)
  461.                         print("Waiting for internet to reconnect...")
  462.                     internetPause = False
  463.  
  464. def onPause():
  465.     global canSaveAgain
  466.     if canSaveAgain:
  467.         sleep(1)
  468.         print("Paused " + str(progress + 1) + "/" + str(len(commands)))
  469.         saveProgress()
  470.     canSaveAgain = False
  471.  
  472.  
  473. def beginProcess():
  474.     global errorMsg, startTime, mouseStartPosition, pause, startPlacing
  475.     if commands is None:
  476.         errorMsg = "Commands not converted yet!"
  477.         mainWindow.createError.emit()
  478.     else:
  479.         startTime = datetime.datetime.now()
  480.         mouseStartPosition = mouse.position
  481.         pause = False
  482.         startPlacing = True
  483.  
  484. def read_key_board():
  485.     global commands, errorMsg, mainWindow, startPlacing, pause, mouseStartPosition, startTime, canSaveAgain
  486.     while True:
  487.         sleep(0.01)
  488.         if keyboard.is_pressed('f6'):
  489.             beginProcess()
  490.         if keyboard.is_pressed('f7'):
  491.             pause = True
  492.         if keyboard.is_pressed('f8'):
  493.             canSaveAgain = True
  494.             pause = False
  495.  
  496.  
  497. def exit_handler():
  498.     print("Exit")
  499.  
  500.  
  501. """
  502. Uses two additional threads
  503.  
  504.  
  505. """
  506. if __name__ == "__main__":
  507.     #main
  508.     if hasattr(os, 'geteuid'):
  509.         if os.geteuid() != 0:
  510.             print('You must be root to use this bot on linux.')
  511.     atexit.register(exit_handler)
  512.     os.chdir(currentPath)
  513.     commandThread = Thread(target=placeCommands)
  514.     commandThread.start()
  515.     keyboardListener = Thread(target=read_key_board)
  516.     keyboardListener.start()
  517.     app = App()
Advertisement
Add Comment
Please, Sign In to add comment