index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
50,830
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/activityStateDetector.py
import re import sys import time import os import subprocess from com.dtmilano.android.viewclient import ViewClient, View, ViewClientOptions from com.dtmilano.android.adb import adbclient from com.dtmilano.android.common import debugArgsToDict from stateNode import stateNode import graphPlotter as gp from matplotlib.image import imread import enum from activityDataClass import activityDataClass import cv2 import time import pickle import numpy as np from sklearn.linear_model import LogisticRegression class activityStateDetector: ########## IMPORTANT VARIABLES ################ topScreenLimitPercentage = 0.2 # 20% from top (considering 1920 pixels in height) middleScreenLimitPercentage = 0.6 # 60% center of screen activityTypeDictionary = { # Dictionary to convert from number to string label 1: "Todo", 2: "Ad", 3: "Login", 4: "List", 5: "Portal", 6: "Browser", 7: "Map", 8: "Messages" } ############################################### @staticmethod def trainModel(): # Reading X and Y vectors filehandler = open('./../savedKerasModels/X.dat', 'rb') X = pickle.load(filehandler) filehandler.close() filehandler = open('./../savedKerasModels/Y.dat', 'rb') Y = pickle.load(filehandler) filehandler.close() # Training the model # Instantiating the logistic Regression model logisticRegr = LogisticRegression(solver='newton-cg', multi_class='ovr') # Fitting the model logisticRegr.fit(X, Y) return logisticRegr @classmethod def detectActivity(cls, logisticRegr): # Setting the ViewClient's options kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': True} kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': False} # Connecting to the Device device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) # Instatiation of the ViewClient for the selected Device: this is an interface for the device's views vc = ViewClient(device, serialno, **kwargs2) if vc.useUiAutomator: print "ViewClient: using UiAutomator backend" # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Calculating the percentage of screen sections topScreenSection = int(cls.topScreenLimitPercentage * screenHeight) middleScreenSection = int(topScreenSection + (cls.middleScreenLimitPercentage * screenHeight)) # Instantiation of the activityDataClass object and getting the activity name activityObject = activityDataClass(device.getTopActivityName()) ##############-------------------####################### # Dumping the current view elements of the application print "\nDumping current application screen..." vc.dump(window='-1') elementToAttributesDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Bounds of this specific UI elements are (startWidth, startHeight), (endWidth, endHeight) topHeight = elementAttributes['bounds'][0][1] bottomHeight = elementAttributes['bounds'][1][1] # Understanding in which section of the screen the element is located screenSection = 0 activityObject.initializeFocusable() activityObject.initializeEnabled() activityObject.initializeImageViews() if bottomHeight <= topScreenSection: # Case of TOP SECTION of screen if elementAttributes['clickable'] == 'true': activityObject.incrementnumClickableTop() if elementAttributes['scrollable'] == 'true': activityObject.incrementnumSwipeableTop() if elementAttributes['class'] == 'android.widget.EditText': activityObject.incrementnumEdittextTop() if elementAttributes['long-clickable'] == 'true': activityObject.incrementnumLongclickTop() if elementAttributes['focusable'] == 'true': activityObject.incrementnumFocusableTop() if elementAttributes['enabled'] == 'true': activityObject.incrementnumEnabledTop() if elementAttributes['class'] == 'android.widget.ImageView': activityObject.incrementnumImageViewsTop() elif bottomHeight <= middleScreenSection: # Case of MIDDLE SECTION of screen if elementAttributes['clickable'] == 'true': activityObject.incrementnumClickableMid() if elementAttributes['scrollable'] == 'true': activityObject.incrementnumSwipeableMid() if elementAttributes['class'] == 'android.widget.EditText': activityObject.incrementnumEdittextMid() if elementAttributes['long-clickable'] == 'true': activityObject.incrementnumLongclickMid() if elementAttributes['focusable'] == 'true': activityObject.incrementnumFocusableMid() if elementAttributes['enabled'] == 'true': activityObject.incrementnumEnabledMid() if elementAttributes['class'] == 'android.widget.ImageView': activityObject.incrementnumImageViewsMid() else: # Case of BOTTOM SECTION of screen if elementAttributes['clickable'] == 'true': activityObject.incrementnumClickableBot() if elementAttributes['scrollable'] == 'true': activityObject.incrementnumSwipeableBot() if elementAttributes['class'] == 'android.widget.EditText': activityObject.incrementnumEdittextBot() if elementAttributes['long-clickable'] == 'true': activityObject.incrementnumLongclickBot() if elementAttributes['focusable'] == 'true': activityObject.incrementnumFocusableBot() if elementAttributes['enabled'] == 'true': activityObject.incrementnumEnabledBot() if elementAttributes['class'] == 'android.widget.ImageView': activityObject.incrementnumImageViewsBot() # Doing last checks if elementAttributes['password'] == 'true': activityObject.incrementnumPassword() if elementAttributes['checkable'] == 'true': activityObject.incrementnumCheckable() # Incrementing the total number of UI elements for this activity activityObject.incrementnumTot() # Setting all the UI elements in the object for backup purposes activityObject.setAllUIElements(elementToAttributesDictionary) ##############-------------------####################### print "Preparing data for input array format" # Concatenating all metadata for the activity metaInputList = [] tmpArray = [] tmpArray.append(activityObject.numClickableTop) tmpArray.append(activityObject.numClickableMid) tmpArray.append(activityObject.numClickableBot) tmpArray.append(int( activityObject.numSwipeableTop + activityObject.numSwipeableMid + activityObject.numSwipeableBot)) # Adding the sum too tmpArray.append(activityObject.numEdittextTop) tmpArray.append(activityObject.numEdittextMid) tmpArray.append(activityObject.numEdittextBot) tmpArray.append(int( activityObject.numLongclickTop + activityObject.numLongclickMid + activityObject.numLongclickBot)) # Adding the sum too tmpArray.append(activityObject.numFocusableTop) tmpArray.append(activityObject.numFocusableMid) tmpArray.append(activityObject.numFocusableBot) tmpArray.append(int( activityObject.numImageViewsTop + activityObject.numImageViewsMid + activityObject.numImageViewsBot)) # Adding the sum too tmpArray.append(activityObject.numPassword) tmpArray.append(activityObject.numCheckable) tmpArray.append(activityObject.presentDrawer) tmpArray.append(activityObject.numTotElements) ##############-------------------####################### # Getting desired format metaInputList.append(tmpArray) # Converting to numpy arrays metaInputList = np.array(metaInputList) print "Predicting..." # Trying to predict predictedNumber = logisticRegr.predict(metaInputList) # Adding one to adjust numeric format predictedNumber = predictedNumber # Converting from number to string predictedCategory = cls.activityTypeDictionary[predictedNumber[0]] print "((( I predicted " + str(predictedCategory) + " )))" return predictedCategory
{"/graphPlotter.py": ["/stateNode.py"]}
50,831
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/customLanguageInterpreter/testClass.py
from com.dtmilano.android.viewclient import ViewClient, View, ViewClientOptions from com.dtmilano.android.adb import adbclient from com.dtmilano.android.common import debugArgsToDict from activityStateDetector import activityStateDetector import subprocess import re import time class testClass: # This class coincides with a test to execute (list of commands) def __init__(self, startingActivityType, sameDestination, endActivityType=None): # Saving the type of activity in which we have to execute the list of commands self.startingActivityType = startingActivityType # Saving whether the ending state after the commands are executed should be the same or not self.sameDestination = sameDestination # Initializing the list of commands to be executed for this test self.commandsList = [] # Understanding whether we need to save a different destination activity type if sameDestination==False: self.endActivityType = endActivityType # Initializing dictionary self.startingElementToAttributesDictionary = None # Those must be function calls in string format! def appendCommandFunction(self, command): self.commandsList.append(command) ###################################################### ######### LIST OF POSSIBLE COMMANDS ################## ### INIT FUNCTION TO SAVE THE DUMP ### def initDump(self): # Setting the ViewClient's options kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': True} kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': False} # Connecting to the Device device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) # Instatiation of the ViewClient for the selected Device: this is an interface for the device's views vc = ViewClient(device, serialno, **kwargs2) if vc.useUiAutomator: print "ViewClient: using UiAutomator backend" # Dumping vc.dump(window='-1') vc.sleep(1) elementToAttributesDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Setting the class variable self.vc = vc self.startingElementToAttributesDictionary = dict(elementToAttributesDictionary) self.device = device ### FINAL FUNCTION TO CHECK THE STATE WHERE WE ARE ARRIVED def finalStateCheck(self, logisticRegr): # Setting the ViewClient's options kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': True} kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': False} # Connecting to the Device device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) # Instatiation of the ViewClient for the selected Device: this is an interface for the device's views vc = ViewClient(device, serialno, **kwargs2) if vc.useUiAutomator: print "ViewClient: using UiAutomator backend" # Dumping vc.dump(window='-1',sleep=2) vc.sleep(1) elementToAttributesDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Finally comparing the current dump with the one of the initial state if elementToAttributesDictionary == self.startingElementToAttributesDictionary: return "SAME" else: # If the state is different, return its detected type stateType = activityStateDetector.detectActivity(logisticRegr) return stateType ### CUSTOM FUNCTIONS ### def customClick(self, xCord, yCord): success = False # Converting to float xCord = float(xCord) yCord = float(yCord) # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Checking if the given coordinates are in the correct range if screenWidth >= xCord >= 0 and screenHeight >= yCord >= 0: success = True # Determining if we had success if success == True: # Pressing the screen self.device.touch(xCord, yCord) print "Command OK!" return True else: print "Command NOT EXECUTED - Out of screen bounds" return False def customLongClick(self, xCord, yCord): success = False # Converting to float xCord = float(xCord) yCord = float(yCord) # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Checking if the given coordinates are in the correct range if screenWidth >= xCord >= 0 and screenHeight >= yCord >= 0: success = True # Determining if we had success if success == True: # Long-pressing the screen self.device.drag((xCord,yCord), (xCord,yCord), 2000) print "Command OK!" return True else: print "Command NOT EXECUTED - Out of screen bounds" return False def customDrag(self, xCordStart, yCordStart, xCordEnd, yCordEnd, duration): success = False # Converting to float xCordStart = float(xCordStart) yCordStart = float(yCordStart) xCordEnd = float(xCordEnd) yCordEnd = float(yCordEnd) duration = int(duration) # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Checking if the given coordinates are in the correct range if screenWidth >= xCordStart >= 0 and screenHeight >= yCordStart >= 0 and screenWidth >= xCordEnd >= 0 and screenHeight >= yCordEnd >= 0: success = True # Determining if we had success if success == True: # Long-pressing the screen self.device.drag((xCordStart, yCordStart), (xCordEnd, yCordEnd), duration) print "Command OK!" return True else: print "Command NOT EXECUTED - Out of screen bounds" return False def customType(self, inputString): success = False if self.device.isKeyboardShown(): # This command requires the keyboard to be opened self.device.type(inputString) self.device.press('KEYCODE_BACK') self.vc.sleep(1) success = True # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED - Could not input text" return False def customPressBack(self): # Pressing the back device button self.device.press('KEYCODE_BACK') print "Command OK!" def customSleep(self, stringMilliSecs): # Getting the number of milliseconds to wait milliSecs = int(stringMilliSecs) secs = milliSecs/1000 self.vc.sleep(secs) print "Command OK!" return True def customAssertText(self, inputText): success = False # Dumping self.vc.dump(window='-1', sleep=1) self.vc.sleep(1) elementToAttributesDictionary = {} for element in self.vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = self.vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Find an the desired text for element in elementToAttributesDictionary: if inputText in str(elementToAttributesDictionary[element]["text"].encode('utf-8')): success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED - Could not find text " + str(inputText) return False def customClickText(self, inputText): success = False # Dumping self.vc.dump(window='-1', sleep=1) self.vc.sleep(1) elementToAttributesDictionary = {} for element in self.vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = self.vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Find an the desired text for element in elementToAttributesDictionary: if (inputText == (elementToAttributesDictionary[element]["text"]).encode('utf-8')) or (inputText in (elementToAttributesDictionary[element]["content-desc"]).encode('utf-8').lower()): address = self.vc.findViewByIdOrRaise(element) address.touch() self.vc.sleep(2) success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED - Could not find text " + str(inputText) return False ### TODO - TYPE 1 ### def todoAddNewNote(self, inputNoteTitle): success = False # Trying to find an Image button (generally the "add note button" is a fab in the bottom of the screen) for element in self.startingElementToAttributesDictionary: if ("imagebutton" in str(self.startingElementToAttributesDictionary[element]["class"]).lower()) or (self.startingElementToAttributesDictionary[element]["clickable"] == "true"): # Now we need to find some keywords that are generally hidden in the resource id of the element hints = ['fab', 'add', 'new', 'create', 'write'] text = str(self.startingElementToAttributesDictionary[element]["resource-id"]).lower() for hint in hints: if hint in text: # We have found the right "add note button", therefore click it address = self.vc.findViewByIdOrRaise(element) address.touch() if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') self.vc.sleep(2) success = True break if success == True: break # If everything went ok up to now, find an EditText where to write the note title if success == True: success = False # Dumping self.vc.dump(window='-1',sleep=1) self.vc.sleep(2) elementToAttributesDictionary = {} for element in self.vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = self.vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Find an edittext for element in elementToAttributesDictionary: if "edittext" in str(elementToAttributesDictionary[element]["class"]).lower(): # Finding some hints hints = ['title', 'name', 'task'] text = (elementToAttributesDictionary[element]["text"]).encode('utf-8').lower() for hint in hints: if hint in text: # Finding the element and typing address = self.vc.findViewByIdOrRaise(element) address.type(inputNoteTitle) if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') success = True self.vc.sleep(2) break if success == True: break # Now that we have added the note, we need to press "next" button if success == True: success = False # Dumping self.vc.dump(window='-1',sleep=1) self.vc.sleep(1) elementToAttributesDictionary = {} for element in self.vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = self.vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Find a Next button for element in elementToAttributesDictionary: if elementToAttributesDictionary[element]["clickable"] == "true": # Finding some hints hints = ['add', 'next', 'save', 'create'] text = (elementToAttributesDictionary[element]["text"]).encode('utf-8').lower() # desc = (elementToAttributesDictionary[element]["content-desc"]).encode('utf-8').lower() desc = "" for hint in hints: if (hint in text) or (hint in desc): # We have found the right "add note button", therefore click it address = self.vc.findViewByIdOrRaise(element) address.touch() self.vc.sleep(1) success = True break if success == True: break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def tickLine(self, lineNum): success = False # Dumping self.vc.dump(window='-1', sleep=1) self.vc.sleep(1) elementToAttributesDictionary = {} for element in self.vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = self.vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Find a checkable box currentCounter = 0 for element in elementToAttributesDictionary: if str(elementToAttributesDictionary[element]["checkable"]).lower() == "true": # Checking if the current checkbox is the onw that we need to click if "priority" in str(elementToAttributesDictionary[element]["resource-id"]).lower(): pass else: currentCounter = currentCounter + 1 if currentCounter == int(lineNum): address = self.vc.findViewByIdOrRaise(element) address.touch() self.vc.sleep(1) success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def assertNumNotes(self, assertingNum): success = False # Dumping self.vc.dump(window='-1', sleep=1) self.vc.sleep(1) elementToAttributesDictionary = {} for element in self.vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = self.vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Find a checkable box currentCounter = 0 for element in elementToAttributesDictionary: if str(elementToAttributesDictionary[element]["checkable"]).lower() == "true": # Checking if the current checkbox is the onw that we need to click if "priority" in str(elementToAttributesDictionary[element]["resource-id"]).lower(): pass else: currentCounter = currentCounter + 1 # Determining if we had success if currentCounter == int(assertingNum): print "Command OK!" return True else: print "ASSERTION FAILED: requested " + str(assertingNum) + " but obtained " + str(currentCounter) return False ### AD - TYPE 2 ### def closeAd(self): success = False # Trying to find the 'name' field for element in self.startingElementToAttributesDictionary: # Finding out if this is an Edittext first if ("imagebutton" in self.startingElementToAttributesDictionary[element]["class"].lower() and "close" in self.startingElementToAttributesDictionary[element]["content-desc"].lower()) or ("view.view" in str(self.startingElementToAttributesDictionary[element]["class"]).lower() and str(self.startingElementToAttributesDictionary[element]["clickable"]).lower() == "true" and str(self.startingElementToAttributesDictionary[element]["text"]).lower() == "") : # Finding the element and typing address = self.vc.findViewByIdOrRaise(element) address.touch() self.vc.sleep(1) success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def openAd(self): success = False # Trying to find the 'name' field for element in self.startingElementToAttributesDictionary: # Finding out if this is an Edittext first if ("view.view" in str(self.startingElementToAttributesDictionary[element]["class"]).lower() and str(self.startingElementToAttributesDictionary[element]["clickable"]).lower() == "true" and str(self.startingElementToAttributesDictionary[element]["text"]).lower() != "") or (str(self.startingElementToAttributesDictionary[element]["clickable"]).lower() == "true" and "container" not in str(self.startingElementToAttributesDictionary[element]["resource-id"]).lower()): # Finding the element and typing address = self.vc.findViewByIdOrRaise(element) address.touch() self.vc.sleep(1) success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def backAd(self): self.customPressBack() ### LOGIN - TYPE 3 ### def loginInputName(self, inputName): success = False # Trying to find the 'name' field for element in self.startingElementToAttributesDictionary: # Finding out if this is an Edittext first if "edittext" in str(self.startingElementToAttributesDictionary[element]["class"]).lower(): # Avoiding the password field if self.startingElementToAttributesDictionary[element]["password"]== "false": # Finding the element and typing address = self.vc.findViewByIdOrRaise(element) address.type(inputName) if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def loginInputPassword(self, inputPassword): success = False # Trying to find the 'password' field for element in self.startingElementToAttributesDictionary: # Finding out if this is an Edittext first if "edittext" in str(self.startingElementToAttributesDictionary[element]["class"]).lower(): # Finding the password field if self.startingElementToAttributesDictionary[element]["password"] == "true": # Finding the element and typing address = self.vc.findViewByIdOrRaise(element) address.type(inputPassword) if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def clickNext(self): success = False # Trying to find the 'password' field for element in self.startingElementToAttributesDictionary: # Finding the button elements if "button" in str(self.startingElementToAttributesDictionary[element]["class"]).lower() or str(self.startingElementToAttributesDictionary[element]["clickable"]) == "true": # Checking that this is a 'next' button thanks to some hint words hints = ['login', 'log', 'signup', 'sign', 'create', 'next'] text = (self.startingElementToAttributesDictionary[element]["text"]).encode('utf-8').lower() desc = (self.startingElementToAttributesDictionary[element]["content-desc"]).encode('utf-8').lower() for hint in hints: if (hint in text) or (hint in desc): # Now we just have to find the element and click it address = self.vc.findViewByIdOrRaise(element) address.touch() self.vc.sleep(1) success = True if success == True: break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def clearFields(self): success = False # Trying to find the 'name' field for element in self.startingElementToAttributesDictionary: # Finding out if this is an Edittext first if "edittext" in str(self.startingElementToAttributesDictionary[element]["class"]).lower(): # Finding the element and typing address = self.vc.findViewByIdOrRaise(element) (x, y) = address.getXY() self.device.drag((x, y), (x, y), 2000, 1) self.device.press('KEYCODE_DEL') if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') success = True # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False ### LIST - TYPE 4 ### def clickListLine(self, lineNumber): success = False # Trying to find the Nth line for element in self.startingElementToAttributesDictionary: # Finding the Linear Layout elements if "linearlayout" in str(self.startingElementToAttributesDictionary[element]["class"]).lower(): # Checking that this is the right line number if str(self.startingElementToAttributesDictionary[element]["index"]) == str(lineNumber): # Now we just have to find the element and click it address = self.vc.findViewByIdOrRaise(element) address.touch() self.vc.sleep(1) success = True if success == True: break # Determining if we had success if success == True: print "Command OK!" self.vc.sleep(1) return True else: print "Command NOT EXECUTED - Could not find line index " + str(lineNumber) return False ### PORTAL - TYPE 5 ### def swipeLeftPortal(self): # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Finding central point yCenter = int(screenHeight / 2) # Swiping self.device.drag((0, yCenter), (screenWidth, yCenter), 250) print "Command OK!" def swipeRightPortal(self): # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Finding central point yCenter = int(screenHeight / 2) # Swiping self.device.drag((screenWidth-10, yCenter), (0, yCenter), 250) print "Command OK!" ### BROWSER - TYPE 8 ### def inputUrl(self, inputString): success = False # Trying to find the Nth line for element in self.startingElementToAttributesDictionary: # Finding the Linear Layout elements if "edittext" in str(self.startingElementToAttributesDictionary[element]["class"]).lower(): # Now we just have to find the element and click it address = self.vc.findViewByIdOrRaise(element) address.type(inputString) if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') self.vc.sleep(1) success = True break # Determining if we had success if success == True: print "Command OK!" self.vc.sleep(1) return True else: print "Command NOT EXECUTED" return False def pressEnterUrl(self): success = False # Trying to find the Nth line for element in self.startingElementToAttributesDictionary: # Finding the Linear Layout elements if "edittext" in str(self.startingElementToAttributesDictionary[element]["class"]).lower(): # Now we just have to find the element and click it address = self.vc.findViewByIdOrRaise(element) address.touch() self.device.press('KEYCODE_ENTER') if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') self.vc.sleep(1) success = True break # Determining if we had success if success == True: print "Command OK!" self.vc.sleep(1) return True else: print "Command NOT EXECUTED" return False ### MAP - TYPE 7 ### def searchOnMap(self, inputString): # CUSTOM CLICK TEXT "Search here"; if not self.customClickText("Search here"): print "Command NOT EXECUTED" return False # CUSTOM SLEEP 1000 ; if not self.customSleep(1000): print "Command NOT EXECUTED" return False # CUSTOM TYPE "San Francisco"; if not self.customType(inputString): print "Command NOT EXECUTED" return False # CUSTOM SLEEP 1000 ; if not self.customSleep(1000): print "Command NOT EXECUTED" return False # CUSTOM CLICK TEXT "San Francisco" if not self.customClickText(inputString): print "Command NOT EXECUTED" return False print "Command OK!" return True def swipeUp(self): success = False # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Finding central point xCenter = int(screenWidth/2) yCenter = int(screenHeight/2) # Swiping self.device.drag((xCenter, yCenter), (xCenter, yCenter+500), 250) print "Command OK!" return True def swipeDown(self): success = False # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Finding central point xCenter = int(screenWidth/2) yCenter = int(screenHeight/2) # Swiping self.device.drag((xCenter, yCenter), (xCenter, yCenter-500), 250) print "Command OK!" return True def swipeLeft(self): success = False # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Finding central point xCenter = int(screenWidth/2) yCenter = int(screenHeight/2) # Swiping self.device.drag((xCenter, yCenter), (xCenter-500, yCenter), 250) print "Command OK!" return True def swipeRight(self): success = False # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start() + 6: matchResult.end() - 1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start() + 7: matchResult.end() - 1] screenHeight = int(screenHeight) # Finding central point xCenter = int(screenWidth/2) yCenter = int(screenHeight/2) # Swiping self.device.drag((xCenter, yCenter), (xCenter+500, yCenter), 250) print "Command OK!" return True ### MESSAGES - TYPE 8 ### def inputMessage(self, inputString): success = False # Trying to find the 'password' field for element in self.startingElementToAttributesDictionary: # Finding the button elements if "edittext" in str(self.startingElementToAttributesDictionary[element]["class"]).lower(): # Checking that this is an edittext where to write our command # Now we just have to find the element and input the text address = self.vc.findViewByIdOrRaise(element) address.type(inputString) if self.device.isKeyboardShown(): self.device.press('KEYCODE_BACK') self.vc.sleep(1) success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False def sendMessage(self): success = False # Trying to find the 'password' field for element in self.startingElementToAttributesDictionary: # Finding the button elements if "send" in str(self.startingElementToAttributesDictionary[element]["content-desc"]).lower(): # Now we just have to find the element and input the text address = self.vc.findViewByIdOrRaise(element) address.touch() success = True break # Determining if we had success if success == True: print "Command OK!" return True else: print "Command NOT EXECUTED" return False
{"/graphPlotter.py": ["/stateNode.py"]}
50,832
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/stateNode.py
import re import sys import time import os import subprocess from com.dtmilano.android.viewclient import ViewClient, View, ViewClientOptions import copy class stateNode: # Static variable keeping count of the number of states generated until now currentNumStates = 0 def __init__(self, roadMap = [], attributesDictionary = {}, father = None): # Setting unique name self.name = 'state' + str(stateNode.currentNumStates) stateNode.incrementNumStates() # Setting the roadmap (list of UI elements) to get here self.roadMap = roadMap[:] # Setting the 'UI element -> attributes dictionary' dictionary (nested dictionary) self.attributesDictionary = copy.deepcopy(attributesDictionary) # Setting the 'UI element -> arriving state' dictionary self.outgoingStateDictionary = {} # Setting the father state self.father = father # Building the queue of UI elements to visit (key is UI element) self.visitQueue = [] for key in self.attributesDictionary: self.visitQueue.append(key) # This method sets all over again the attributes dictionary and also their queue def updateAttributes(self, attributesDictionary = {}): # Setting the 'UI element -> attributes dictionary' dictionary (nested dictionary) self.attributesDictionary = copy.deepcopy(attributesDictionary) # Building the queue of UI elements to visit (key is UI element) del self.visitQueue[:] self.visitQueue = [] for key in self.attributesDictionary: self.visitQueue.append(key) # This method returns and pops from the list the UI element that we have to analyze def popUIelementToAnalyze(self): if len(self.visitQueue) == 0: return None else: return self.visitQueue.pop(0) # This method adds a state that can be reached through a specific UI element (UiElement is actually an uniqueID) def addOutgoingState(self, UiElement, state): self.outgoingStateDictionary[UiElement] = state # This method increments the static num of states @classmethod def incrementNumStates(cls): cls.currentNumStates = cls.currentNumStates + 1 def updateOutgoingStateDictionary(self, dictionary): self.outgoingStateDictionary = copy.deepcopy(dictionary) def getOutgoingStateDictionary(self): return self.outgoingStateDictionary def getStateName(self): return self.name def getCurrentQueueLength(self): return len(self.visitQueue) def getAttributesDictionary(self): return self.attributesDictionary def getRoadMap(self): return list(self.roadMap) def getFather(self): return self.father
{"/graphPlotter.py": ["/stateNode.py"]}
50,833
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/activityDumper.py
import re import sys import time import os import subprocess from com.dtmilano.android.viewclient import ViewClient, View, ViewClientOptions from com.dtmilano.android.adb import adbclient from com.dtmilano.android.common import debugArgsToDict from stateNode import stateNode import graphPlotter as gp from matplotlib.image import imread import enum from activityDataClass import activityDataClass import cv2 import time import pickle ########## IMPORTANT VARIABLES ################ topScreenLimitPercentage = 0.2 # 20% from top (considering 1920 pixels in height) middleScreenLimitPercentage = 0.6 # 60% center of screen topScreenCropping = 65 # Pixels to crop on top of the screenshot bottomScreenCropping = 127 # Pixels to crop on bottom of the screenshot storePath = "./storedData/labeledActivities.dat" class ActivityTypes(enum.Enum): # Enumeration for screen section ToDo = 1 Ad = 2 Login = 3 ListScreen = 4 Portal = 5 Browser = 6 Map = 7 Messages = 8 numCategories = 8 activityTypeDictionary = { 1 : "Todo", 2 : "Ad", 3 : "Login", 4 : "ListScreen", 5 : "Portal", 6 : "Browser", 7 : "Map", 8 : "Messages" } ############################################### # Setting the ViewClient's options kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': True} kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': False} # Connecting to the Device device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) # Instatiation of the ViewClient for the selected Device: this is an interface for the device's views vc = ViewClient(device, serialno, **kwargs2) if vc.useUiAutomator: print "ViewClient: using UiAutomator backend" #device.dumpsys() # First of all, check if the stored file already exists labeledList = [] exists = os.path.isfile(storePath) if exists: # If the file already exists, then load it with open(storePath, "rb") as fp: # Unpickling labeledList = pickle.load(fp) print "[[ Loaded list with " + str(len(labeledList)) + " elements ]]" else: # If the file does not exist yet, create the empty list labeledList = [] print "[[ New list created ]]" # Getting the screen size via adb shell command output = subprocess.check_output("adb shell dumpsys window | find \"width\"", shell=True) # Parsing the result in order to find the width matchResult = re.search("width=[0-9]+,", output) screenWidth = output[matchResult.start()+6 : matchResult.end()-1] screenWidth = int(screenWidth) # Parsing the result in order to find the height matchResult = re.search("height=[0-9]+,", output) screenHeight = output[matchResult.start()+7 : matchResult.end()-1] screenHeight = int(screenHeight) # Calculating the percentage of screen sections topScreenSection = int(topScreenLimitPercentage * screenHeight) middleScreenSection = int(topScreenSection + (middleScreenLimitPercentage * screenHeight)) # Instantiation of the activityDataClass object and getting the activity name activityObject = activityDataClass( device.getTopActivityName() ) # Dumping the current view elements of the application print "Dumping current application screen..." vc.dump(window='-1') elementToAttributesDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Bounds of this specific UI elements are (startWidth, startHeight), (endWidth, endHeight) topHeight = elementAttributes['bounds'][0][1] bottomHeight = elementAttributes['bounds'][1][1] # Understanding in which section of the screen the element is located screenSection = 0 if bottomHeight <= topScreenSection: # Case of TOP SECTION of screen if elementAttributes['clickable'] == 'true': activityObject.incrementnumClickableTop() if elementAttributes['scrollable'] == 'true': activityObject.incrementnumSwipeableTop() if elementAttributes['class'] == 'android.widget.EditText': activityObject.incrementnumEdittextTop() if elementAttributes['long-clickable'] == 'true': activityObject.incrementnumLongclickTop() elif bottomHeight <= middleScreenSection: # Case of MIDDLE SECTION of screen if elementAttributes['clickable'] == 'true': activityObject.incrementnumClickableMid() if elementAttributes['scrollable'] == 'true': activityObject.incrementnumSwipeableMid() if elementAttributes['class'] == 'android.widget.EditText': activityObject.incrementnumEdittextMid() if elementAttributes['long-clickable'] == 'true': activityObject.incrementnumLongclickMid() else: # Case of BOTTOM SECTION of screen if elementAttributes['clickable'] == 'true': activityObject.incrementnumClickableBot() if elementAttributes['scrollable'] == 'true': activityObject.incrementnumSwipeableBot() if elementAttributes['class'] == 'android.widget.EditText': activityObject.incrementnumEdittextBot() if elementAttributes['long-clickable'] == 'true': activityObject.incrementnumLongclickBot() # Doing last checks if elementAttributes['password'] == 'true': activityObject.incrementnumPassword() if elementAttributes['checkable'] == 'true': activityObject.incrementnumCheckable() # Incrementing the total number of UI elements for this activity activityObject.incrementnumTot() # Setting all the UI elements in the object for backup purposes activityObject.setAllUIElements(elementToAttributesDictionary) # Taking a screenshot print "Done.\nCapturing Screenshot..." device.takeSnapshot().save("./screenshots/screenshot.PNG", 'PNG') loadedScreenshot = cv2.imread("./screenshots/screenshot.PNG") # Converting the screenshot to grayscale grayScreenshot = cv2.cvtColor(loadedScreenshot, cv2.COLOR_BGR2GRAY) # Cropping the image to remove top and bottom system bars croppedScreenshot = grayScreenshot[topScreenCropping:(screenHeight-bottomScreenCropping), 0:screenWidth] # Rescaling the image to make it smaller (45% of original size) smallerScreenshot = cv2.resize(croppedScreenshot, (0,0), fx=0.45, fy=0.45) print "Screenshot resized to " + str(smallerScreenshot.shape) # Setting that screenshot to the object activityObject.setScreenshot(smallerScreenshot) # cv2.imshow('image', activityObject.screenshot) # cv2.waitKey() # Requesting to the user to input the type of the recorded activity print "Insert type of activity:\n\tToDo = 1\n\tAd = 2\n\tLogin = 3\n\tListScreen = 4\n\tPortal = 5\n\tBrowser = 6\n\tMap = 7\n\tMessages = 8\n" userInput = 0 while True: try: userInput = int(input("Enter category number: ")) except Exception: # Case of string print("Not an integer!") continue else: # Case of integer if userInput >=1 and userInput<=numCategories: print "You selected \'" + activityTypeDictionary[userInput] + "\'" activityObject.setLabel(activityTypeDictionary[userInput], userInput) break else: print "Number out of range" continue # Adding the new object to the list labeledList.append(activityObject) # Saving the list to file print "Saving list to file..." with open(storePath, "wb") as fp: #Pickling pickle.dump(labeledList, fp) print "Done."
{"/graphPlotter.py": ["/stateNode.py"]}
50,834
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/customLanguageInterpreter/scriptingLanguageLexer.py
# Generated from scriptingLanguage.g4 by ANTLR 4.7.1 # encoding: utf-8 from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"M\u02e1\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4") buf.write(u"\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r") buf.write(u"\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22") buf.write(u"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4") buf.write(u"\30\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35") buf.write(u"\t\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4") buf.write(u"$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t") buf.write(u",\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63") buf.write(u"\t\63\4\64\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\4") buf.write(u"9\t9\4:\t:\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA") buf.write(u"\4B\tB\4C\tC\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\t") buf.write(u"J\4K\tK\4L\tL\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S") buf.write(u"\tS\4T\tT\4U\tU\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4") buf.write(u"\\\t\\\4]\t]\4^\t^\4_\t_\4`\t`\4a\ta\4b\tb\4c\tc\4d\t") buf.write(u"d\4e\te\4f\tf\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6") buf.write(u"\3\7\3\7\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3") buf.write(u"\r\3\r\3\16\3\16\3\17\3\17\3\20\3\20\3\21\3\21\3\22\3") buf.write(u"\22\3\23\3\23\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27") buf.write(u"\3\30\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\34\3\34\3") buf.write(u"\34\3\34\3\34\3\35\3\35\3\35\3\35\3\36\3\36\3\37\3\37") buf.write(u"\3 \3 \3 \3!\3!\3!\3!\3!\3!\3\"\3\"\3\"\3\"\3#\3#\3#") buf.write(u"\3#\3#\3$\3$\3$\3$\3$\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3") buf.write(u"%\3&\3&\3&\3&\3&\3&\3\'\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3") buf.write(u"(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3)\3*\3*\3*\3*\3*\3+\3+") buf.write(u"\3+\3+\3+\3+\3,\3,\3,\3,\3,\3,\3-\3-\3-\3-\3-\3.\3.\3") buf.write(u".\3.\3.\3/\3/\3/\3/\3/\3\60\3\60\3\60\3\60\3\61\3\61") buf.write(u"\3\61\3\61\3\62\3\62\3\62\3\62\3\62\3\62\3\63\3\63\3") buf.write(u"\63\3\63\3\63\3\63\3\63\3\63\3\64\3\64\3\64\3\64\3\64") buf.write(u"\3\64\3\64\3\65\3\65\3\65\3\65\3\65\3\65\3\66\3\66\3") buf.write(u"\66\3\67\3\67\3\67\3\67\3\67\38\38\38\38\38\39\39\39") buf.write(u"\39\39\39\3:\3:\3:\3:\3:\3:\3:\3;\3;\3;\3;\3;\3;\3;\3") buf.write(u"<\3<\3<\3<\3<\3=\3=\3=\3=\3>\3>\3>\3>\3>\3?\3?\3?\3?") buf.write(u"\3?\3?\3?\3@\3@\3@\3@\3@\3A\3A\3A\3A\3A\3B\3B\3B\3C\3") buf.write(u"C\3C\3C\3C\3C\3C\3C\3C\3D\3D\3D\3D\3D\3E\3E\3E\3E\3E") buf.write(u"\3E\3E\3F\3F\3F\3F\3F\3F\3F\3F\3G\3G\3G\3G\3G\3G\3H\3") buf.write(u"H\3H\3H\3H\3H\3H\3H\3H\3H\3I\3I\3I\3I\3I\3I\3I\3I\3I") buf.write(u"\3I\3J\3J\3J\3J\3J\3J\3J\3J\3J\3J\3K\3K\3K\3K\3K\3K\3") buf.write(u"K\3L\3L\3L\3L\3L\3L\3L\3L\3L\3L\3M\3M\3M\3M\3M\3M\3M") buf.write(u"\3N\3N\3N\3N\3N\3O\3O\3O\3O\3O\3O\3P\3P\3P\3P\3P\3P\3") buf.write(u"P\3Q\3Q\3Q\3Q\3Q\3R\3R\3R\3R\3R\3R\3R\3R\3R\3S\3S\3S") buf.write(u"\3S\3S\3S\3S\3T\3T\3T\3T\3T\3T\3U\3U\3U\3U\3U\3U\3U\3") buf.write(u"U\3V\3V\3V\3V\3V\3V\3V\3V\3V\3V\3V\3V\3V\3V\3W\3W\3W") buf.write(u"\3W\3W\3W\3W\3W\3W\3W\3X\3X\3X\3X\3X\3Y\3Y\3Y\3Y\3Y\3") buf.write(u"Y\3Y\3Y\3Z\3Z\3Z\3Z\3Z\3Z\3[\3[\3[\3[\3[\3\\\3\\\3\\") buf.write(u"\3]\3]\3]\3]\3]\3]\3^\3^\3^\3^\3^\3_\3_\3_\3_\3_\3_\3") buf.write(u"_\3`\3`\3`\3`\3`\3`\3`\3`\3a\3a\3a\3a\3b\3b\3b\3b\3b") buf.write(u"\3b\3b\3b\3b\3c\3c\7c\u02bb\nc\fc\16c\u02be\13c\3c\3") buf.write(u"c\3d\6d\u02c3\nd\rd\16d\u02c4\3d\3d\3e\5e\u02ca\ne\3") buf.write(u"e\3e\6e\u02ce\ne\re\16e\u02cf\3e\3e\3f\6f\u02d5\nf\r") buf.write(u"f\16f\u02d6\3f\5f\u02da\nf\3f\7f\u02dd\nf\ff\16f\u02e0") buf.write(u"\13f\2\2g\3\2\5\2\7\2\t\2\13\2\r\2\17\2\21\2\23\2\25") buf.write(u"\2\27\2\31\2\33\2\35\2\37\2!\2#\2%\2\'\2)\2+\2-\2/\2") buf.write(u"\61\2\63\2\65\2\67\39\4;\5=\6?\7A\bC\tE\nG\13I\fK\rM") buf.write(u"\16O\17Q\20S\21U\22W\23Y\24[\25]\26_\27a\30c\31e\32g") buf.write(u"\33i\34k\35m\36o\37q s!u\"w#y${%}&\177\'\u0081(\u0083") buf.write(u")\u0085*\u0087+\u0089,\u008b-\u008d.\u008f/\u0091\60") buf.write(u"\u0093\61\u0095\62\u0097\63\u0099\64\u009b\65\u009d\66") buf.write(u"\u009f\67\u00a18\u00a39\u00a5:\u00a7;\u00a9<\u00ab=\u00ad") buf.write(u">\u00af?\u00b1@\u00b3A\u00b5B\u00b7C\u00b9D\u00bbE\u00bd") buf.write(u"F\u00bfG\u00c1H\u00c3I\u00c5J\u00c7K\u00c9L\u00cbM\3") buf.write(u"\2#\4\2CCcc\4\2DDdd\4\2EEee\4\2FFff\4\2GGgg\4\2HHhh\4") buf.write(u"\2IIii\4\2JJjj\4\2KKkk\4\2LLll\4\2MMmm\4\2NNnn\4\2OO") buf.write(u"oo\4\2PPpp\4\2QQqq\4\2RRrr\4\2SSss\4\2TTtt\4\2UUuu\4") buf.write(u"\2VVvv\4\2WWww\4\2XXxx\4\2YYyy\4\2ZZzz\4\2[[{{\4\2\\") buf.write(u"\\||\3\2\63\63\3\2\64\64\3\2\65\65\n\2\"#%&((*+-\60\62") buf.write(u";B\\b|\4\2\13\13\"\"\3\2\62;\3\2\60\60\2\u02ce\2\67\3") buf.write(u"\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2") buf.write(u"A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2") buf.write(u"\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2") buf.write(u"\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]\3\2") buf.write(u"\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2\2e\3\2\2\2\2g\3") buf.write(u"\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2\2\2o\3\2\2\2\2") buf.write(u"q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2\2\2\2y\3\2\2\2") buf.write(u"\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2\u0081\3\2\2\2") buf.write(u"\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087\3\2\2\2\2\u0089") buf.write(u"\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2\2\2\u008f\3\2") buf.write(u"\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2\u0095\3\2\2\2") buf.write(u"\2\u0097\3\2\2\2\2\u0099\3\2\2\2\2\u009b\3\2\2\2\2\u009d") buf.write(u"\3\2\2\2\2\u009f\3\2\2\2\2\u00a1\3\2\2\2\2\u00a3\3\2") buf.write(u"\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2\2\2\2\u00a9\3\2\2\2") buf.write(u"\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2\2\u00af\3\2\2\2\2\u00b1") buf.write(u"\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5\3\2\2\2\2\u00b7\3\2") buf.write(u"\2\2\2\u00b9\3\2\2\2\2\u00bb\3\2\2\2\2\u00bd\3\2\2\2") buf.write(u"\2\u00bf\3\2\2\2\2\u00c1\3\2\2\2\2\u00c3\3\2\2\2\2\u00c5") buf.write(u"\3\2\2\2\2\u00c7\3\2\2\2\2\u00c9\3\2\2\2\2\u00cb\3\2") buf.write(u"\2\2\3\u00cd\3\2\2\2\5\u00cf\3\2\2\2\7\u00d1\3\2\2\2") buf.write(u"\t\u00d3\3\2\2\2\13\u00d5\3\2\2\2\r\u00d7\3\2\2\2\17") buf.write(u"\u00d9\3\2\2\2\21\u00db\3\2\2\2\23\u00dd\3\2\2\2\25\u00df") buf.write(u"\3\2\2\2\27\u00e1\3\2\2\2\31\u00e3\3\2\2\2\33\u00e5\3") buf.write(u"\2\2\2\35\u00e7\3\2\2\2\37\u00e9\3\2\2\2!\u00eb\3\2\2") buf.write(u"\2#\u00ed\3\2\2\2%\u00ef\3\2\2\2\'\u00f1\3\2\2\2)\u00f3") buf.write(u"\3\2\2\2+\u00f5\3\2\2\2-\u00f7\3\2\2\2/\u00f9\3\2\2\2") buf.write(u"\61\u00fb\3\2\2\2\63\u00fd\3\2\2\2\65\u00ff\3\2\2\2\67") buf.write(u"\u0101\3\2\2\29\u0106\3\2\2\2;\u010a\3\2\2\2=\u010c\3") buf.write(u"\2\2\2?\u010e\3\2\2\2A\u0111\3\2\2\2C\u0117\3\2\2\2E") buf.write(u"\u011b\3\2\2\2G\u0120\3\2\2\2I\u012a\3\2\2\2K\u0130\3") buf.write(u"\2\2\2M\u0136\3\2\2\2O\u013b\3\2\2\2Q\u0144\3\2\2\2S") buf.write(u"\u014a\3\2\2\2U\u014f\3\2\2\2W\u0155\3\2\2\2Y\u015b\3") buf.write(u"\2\2\2[\u0160\3\2\2\2]\u0165\3\2\2\2_\u016a\3\2\2\2a") buf.write(u"\u016e\3\2\2\2c\u0172\3\2\2\2e\u0178\3\2\2\2g\u0180\3") buf.write(u"\2\2\2i\u0187\3\2\2\2k\u018d\3\2\2\2m\u0190\3\2\2\2o") buf.write(u"\u0195\3\2\2\2q\u019a\3\2\2\2s\u01a0\3\2\2\2u\u01a7\3") buf.write(u"\2\2\2w\u01ae\3\2\2\2y\u01b3\3\2\2\2{\u01b7\3\2\2\2}") buf.write(u"\u01bc\3\2\2\2\177\u01c3\3\2\2\2\u0081\u01c8\3\2\2\2") buf.write(u"\u0083\u01cd\3\2\2\2\u0085\u01d0\3\2\2\2\u0087\u01d9") buf.write(u"\3\2\2\2\u0089\u01de\3\2\2\2\u008b\u01e5\3\2\2\2\u008d") buf.write(u"\u01ed\3\2\2\2\u008f\u01f3\3\2\2\2\u0091\u01fd\3\2\2") buf.write(u"\2\u0093\u0207\3\2\2\2\u0095\u0211\3\2\2\2\u0097\u0218") buf.write(u"\3\2\2\2\u0099\u0222\3\2\2\2\u009b\u0229\3\2\2\2\u009d") buf.write(u"\u022e\3\2\2\2\u009f\u0234\3\2\2\2\u00a1\u023b\3\2\2") buf.write(u"\2\u00a3\u0240\3\2\2\2\u00a5\u0249\3\2\2\2\u00a7\u0250") buf.write(u"\3\2\2\2\u00a9\u0256\3\2\2\2\u00ab\u025e\3\2\2\2\u00ad") buf.write(u"\u026c\3\2\2\2\u00af\u0276\3\2\2\2\u00b1\u027b\3\2\2") buf.write(u"\2\u00b3\u0283\3\2\2\2\u00b5\u0289\3\2\2\2\u00b7\u028e") buf.write(u"\3\2\2\2\u00b9\u0291\3\2\2\2\u00bb\u0297\3\2\2\2\u00bd") buf.write(u"\u029c\3\2\2\2\u00bf\u02a3\3\2\2\2\u00c1\u02ab\3\2\2") buf.write(u"\2\u00c3\u02af\3\2\2\2\u00c5\u02b8\3\2\2\2\u00c7\u02c2") buf.write(u"\3\2\2\2\u00c9\u02cd\3\2\2\2\u00cb\u02d4\3\2\2\2\u00cd") buf.write(u"\u00ce\t\2\2\2\u00ce\4\3\2\2\2\u00cf\u00d0\t\3\2\2\u00d0") buf.write(u"\6\3\2\2\2\u00d1\u00d2\t\4\2\2\u00d2\b\3\2\2\2\u00d3") buf.write(u"\u00d4\t\5\2\2\u00d4\n\3\2\2\2\u00d5\u00d6\t\6\2\2\u00d6") buf.write(u"\f\3\2\2\2\u00d7\u00d8\t\7\2\2\u00d8\16\3\2\2\2\u00d9") buf.write(u"\u00da\t\b\2\2\u00da\20\3\2\2\2\u00db\u00dc\t\t\2\2\u00dc") buf.write(u"\22\3\2\2\2\u00dd\u00de\t\n\2\2\u00de\24\3\2\2\2\u00df") buf.write(u"\u00e0\t\13\2\2\u00e0\26\3\2\2\2\u00e1\u00e2\t\f\2\2") buf.write(u"\u00e2\30\3\2\2\2\u00e3\u00e4\t\r\2\2\u00e4\32\3\2\2") buf.write(u"\2\u00e5\u00e6\t\16\2\2\u00e6\34\3\2\2\2\u00e7\u00e8") buf.write(u"\t\17\2\2\u00e8\36\3\2\2\2\u00e9\u00ea\t\20\2\2\u00ea") buf.write(u" \3\2\2\2\u00eb\u00ec\t\21\2\2\u00ec\"\3\2\2\2\u00ed") buf.write(u"\u00ee\t\22\2\2\u00ee$\3\2\2\2\u00ef\u00f0\t\23\2\2\u00f0") buf.write(u"&\3\2\2\2\u00f1\u00f2\t\24\2\2\u00f2(\3\2\2\2\u00f3\u00f4") buf.write(u"\t\25\2\2\u00f4*\3\2\2\2\u00f5\u00f6\t\26\2\2\u00f6,") buf.write(u"\3\2\2\2\u00f7\u00f8\t\27\2\2\u00f8.\3\2\2\2\u00f9\u00fa") buf.write(u"\t\30\2\2\u00fa\60\3\2\2\2\u00fb\u00fc\t\31\2\2\u00fc") buf.write(u"\62\3\2\2\2\u00fd\u00fe\t\32\2\2\u00fe\64\3\2\2\2\u00ff") buf.write(u"\u0100\t\33\2\2\u0100\66\3\2\2\2\u0101\u0102\5/\30\2") buf.write(u"\u0102\u0103\5\21\t\2\u0103\u0104\5\13\6\2\u0104\u0105") buf.write(u"\5\35\17\2\u01058\3\2\2\2\u0106\u0107\5\3\2\2\u0107\u0108") buf.write(u"\5!\21\2\u0108\u0109\5!\21\2\u0109:\3\2\2\2\u010a\u010b") buf.write(u"\7<\2\2\u010b<\3\2\2\2\u010c\u010d\7=\2\2\u010d>\3\2") buf.write(u"\2\2\u010e\u010f\5\23\n\2\u010f\u0110\5\35\17\2\u0110") buf.write(u"@\3\2\2\2\u0111\u0112\5\7\4\2\u0112\u0113\5\21\t\2\u0113") buf.write(u"\u0114\5\13\6\2\u0114\u0115\5\7\4\2\u0115\u0116\5\27") buf.write(u"\f\2\u0116B\3\2\2\2\u0117\u0118\5\r\7\2\u0118\u0119\5") buf.write(u"\37\20\2\u0119\u011a\5%\23\2\u011aD\3\2\2\2\u011b\u011c") buf.write(u"\5\'\24\2\u011c\u011d\5\3\2\2\u011d\u011e\5\33\16\2\u011e") buf.write(u"\u011f\5\13\6\2\u011fF\3\2\2\2\u0120\u0121\5\t\5\2\u0121") buf.write(u"\u0122\5\23\n\2\u0122\u0123\5\r\7\2\u0123\u0124\5\r\7") buf.write(u"\2\u0124\u0125\5\13\6\2\u0125\u0126\5%\23\2\u0126\u0127") buf.write(u"\5\13\6\2\u0127\u0128\5\35\17\2\u0128\u0129\5)\25\2\u0129") buf.write(u"H\3\2\2\2\u012a\u012b\5\'\24\2\u012b\u012c\5)\25\2\u012c") buf.write(u"\u012d\5\3\2\2\u012d\u012e\5)\25\2\u012e\u012f\5\13\6") buf.write(u"\2\u012fJ\3\2\2\2\u0130\u0131\5\23\n\2\u0131\u0132\5") buf.write(u"\35\17\2\u0132\u0133\5!\21\2\u0133\u0134\5+\26\2\u0134") buf.write(u"\u0135\5)\25\2\u0135L\3\2\2\2\u0136\u0137\5\35\17\2\u0137") buf.write(u"\u0138\5\3\2\2\u0138\u0139\5\33\16\2\u0139\u013a\5\13") buf.write(u"\6\2\u013aN\3\2\2\2\u013b\u013c\5!\21\2\u013c\u013d\5") buf.write(u"\3\2\2\u013d\u013e\5\'\24\2\u013e\u013f\5\'\24\2\u013f") buf.write(u"\u0140\5/\30\2\u0140\u0141\5\37\20\2\u0141\u0142\5%\23") buf.write(u"\2\u0142\u0143\5\t\5\2\u0143P\3\2\2\2\u0144\u0145\5\7") buf.write(u"\4\2\u0145\u0146\5\31\r\2\u0146\u0147\5\23\n\2\u0147") buf.write(u"\u0148\5\7\4\2\u0148\u0149\5\27\f\2\u0149R\3\2\2\2\u014a") buf.write(u"\u014b\5\35\17\2\u014b\u014c\5\13\6\2\u014c\u014d\5\61") buf.write(u"\31\2\u014d\u014e\5)\25\2\u014eT\3\2\2\2\u014f\u0150") buf.write(u"\5\7\4\2\u0150\u0151\5\31\r\2\u0151\u0152\5\37\20\2\u0152") buf.write(u"\u0153\5\'\24\2\u0153\u0154\5\13\6\2\u0154V\3\2\2\2\u0155") buf.write(u"\u0156\5!\21\2\u0156\u0157\5%\23\2\u0157\u0158\5\13\6") buf.write(u"\2\u0158\u0159\5\'\24\2\u0159\u015a\5\'\24\2\u015aX\3") buf.write(u"\2\2\2\u015b\u015c\5\5\3\2\u015c\u015d\5\3\2\2\u015d") buf.write(u"\u015e\5\7\4\2\u015e\u015f\5\27\f\2\u015fZ\3\2\2\2\u0160") buf.write(u"\u0161\5\31\r\2\u0161\u0162\5\23\n\2\u0162\u0163\5\35") buf.write(u"\17\2\u0163\u0164\5\13\6\2\u0164\\\3\2\2\2\u0165\u0166") buf.write(u"\5\31\r\2\u0166\u0167\5\37\20\2\u0167\u0168\5\35\17\2") buf.write(u"\u0168\u0169\5\17\b\2\u0169^\3\2\2\2\u016a\u016b\5\3") buf.write(u"\2\2\u016b\u016c\5\31\r\2\u016c\u016d\5\31\r\2\u016d") buf.write(u"`\3\2\2\2\u016e\u016f\5+\26\2\u016f\u0170\5%\23\2\u0170") buf.write(u"\u0171\5\31\r\2\u0171b\3\2\2\2\u0172\u0173\5\13\6\2\u0173") buf.write(u"\u0174\5\35\17\2\u0174\u0175\5)\25\2\u0175\u0176\5\13") buf.write(u"\6\2\u0176\u0177\5%\23\2\u0177d\3\2\2\2\u0178\u0179\5") buf.write(u"\33\16\2\u0179\u017a\5\13\6\2\u017a\u017b\5\'\24\2\u017b") buf.write(u"\u017c\5\'\24\2\u017c\u017d\5\3\2\2\u017d\u017e\5\17") buf.write(u"\b\2\u017e\u017f\5\13\6\2\u017ff\3\2\2\2\u0180\u0181") buf.write(u"\5)\25\2\u0181\u0182\5\37\20\2\u0182\u0183\5\17\b\2\u0183") buf.write(u"\u0184\5\17\b\2\u0184\u0185\5\31\r\2\u0185\u0186\5\13") buf.write(u"\6\2\u0186h\3\2\2\2\u0187\u0188\5\'\24\2\u0188\u0189") buf.write(u"\5/\30\2\u0189\u018a\5\23\n\2\u018a\u018b\5!\21\2\u018b") buf.write(u"\u018c\5\13\6\2\u018cj\3\2\2\2\u018d\u018e\5+\26\2\u018e") buf.write(u"\u018f\5!\21\2\u018fl\3\2\2\2\u0190\u0191\5\t\5\2\u0191") buf.write(u"\u0192\5\37\20\2\u0192\u0193\5/\30\2\u0193\u0194\5\35") buf.write(u"\17\2\u0194n\3\2\2\2\u0195\u0196\5\31\r\2\u0196\u0197") buf.write(u"\5\13\6\2\u0197\u0198\5\r\7\2\u0198\u0199\5)\25\2\u0199") buf.write(u"p\3\2\2\2\u019a\u019b\5%\23\2\u019b\u019c\5\23\n\2\u019c") buf.write(u"\u019d\5\17\b\2\u019d\u019e\5\21\t\2\u019e\u019f\5)\25") buf.write(u"\2\u019fr\3\2\2\2\u01a0\u01a1\5\'\24\2\u01a1\u01a2\5") buf.write(u"\13\6\2\u01a2\u01a3\5\3\2\2\u01a3\u01a4\5%\23\2\u01a4") buf.write(u"\u01a5\5\7\4\2\u01a5\u01a6\5\21\t\2\u01a6t\3\2\2\2\u01a7") buf.write(u"\u01a8\5\7\4\2\u01a8\u01a9\5\13\6\2\u01a9\u01aa\5\35") buf.write(u"\17\2\u01aa\u01ab\5)\25\2\u01ab\u01ac\5\13\6\2\u01ac") buf.write(u"\u01ad\5%\23\2\u01adv\3\2\2\2\u01ae\u01af\5)\25\2\u01af") buf.write(u"\u01b0\5\23\n\2\u01b0\u01b1\5\7\4\2\u01b1\u01b2\5\27") buf.write(u"\f\2\u01b2x\3\2\2\2\u01b3\u01b4\5\3\2\2\u01b4\u01b5\5") buf.write(u"\t\5\2\u01b5\u01b6\5\t\5\2\u01b6z\3\2\2\2\u01b7\u01b8") buf.write(u"\5)\25\2\u01b8\u01b9\5\3\2\2\u01b9\u01ba\5\'\24\2\u01ba") buf.write(u"\u01bb\5\27\f\2\u01bb|\3\2\2\2\u01bc\u01bd\5\7\4\2\u01bd") buf.write(u"\u01be\5+\26\2\u01be\u01bf\5\'\24\2\u01bf\u01c0\5)\25") buf.write(u"\2\u01c0\u01c1\5\37\20\2\u01c1\u01c2\5\33\16\2\u01c2") buf.write(u"~\3\2\2\2\u01c3\u01c4\5\t\5\2\u01c4\u01c5\5%\23\2\u01c5") buf.write(u"\u01c6\5\3\2\2\u01c6\u01c7\5\17\b\2\u01c7\u0080\3\2\2") buf.write(u"\2\u01c8\u01c9\5\r\7\2\u01c9\u01ca\5%\23\2\u01ca\u01cb") buf.write(u"\5\37\20\2\u01cb\u01cc\5\33\16\2\u01cc\u0082\3\2\2\2") buf.write(u"\u01cd\u01ce\5)\25\2\u01ce\u01cf\5\37\20\2\u01cf\u0084") buf.write(u"\3\2\2\2\u01d0\u01d1\5\t\5\2\u01d1\u01d2\5+\26\2\u01d2") buf.write(u"\u01d3\5%\23\2\u01d3\u01d4\5\3\2\2\u01d4\u01d5\5)\25") buf.write(u"\2\u01d5\u01d6\5\23\n\2\u01d6\u01d7\5\37\20\2\u01d7\u01d8") buf.write(u"\5\35\17\2\u01d8\u0086\3\2\2\2\u01d9\u01da\5)\25\2\u01da") buf.write(u"\u01db\5\63\32\2\u01db\u01dc\5!\21\2\u01dc\u01dd\5\13") buf.write(u"\6\2\u01dd\u0088\3\2\2\2\u01de\u01df\5\t\5\2\u01df\u01e0") buf.write(u"\5\13\6\2\u01e0\u01e1\5-\27\2\u01e1\u01e2\5\23\n\2\u01e2") buf.write(u"\u01e3\5\7\4\2\u01e3\u01e4\5\13\6\2\u01e4\u008a\3\2\2") buf.write(u"\2\u01e5\u01e6\5\13\6\2\u01e6\u01e7\5\61\31\2\u01e7\u01e8") buf.write(u"\5\13\6\2\u01e8\u01e9\5\7\4\2\u01e9\u01ea\5+\26\2\u01ea") buf.write(u"\u01eb\5)\25\2\u01eb\u01ec\5\13\6\2\u01ec\u008c\3\2\2") buf.write(u"\2\u01ed\u01ee\5\'\24\2\u01ee\u01ef\5\31\r\2\u01ef\u01f0") buf.write(u"\5\13\6\2\u01f0\u01f1\5\13\6\2\u01f1\u01f2\5!\21\2\u01f2") buf.write(u"\u008e\3\2\2\2\u01f3\u01f4\5)\25\2\u01f4\u01f5\5\13\6") buf.write(u"\2\u01f5\u01f6\5\'\24\2\u01f6\u01f7\5)\25\2\u01f7\u01f8") buf.write(u"\5\'\24\2\u01f8\u01f9\5\31\r\2\u01f9\u01fa\5\37\20\2") buf.write(u"\u01fa\u01fb\5)\25\2\u01fb\u01fc\t\34\2\2\u01fc\u0090") buf.write(u"\3\2\2\2\u01fd\u01fe\5)\25\2\u01fe\u01ff\5\13\6\2\u01ff") buf.write(u"\u0200\5\'\24\2\u0200\u0201\5)\25\2\u0201\u0202\5\'\24") buf.write(u"\2\u0202\u0203\5\31\r\2\u0203\u0204\5\37\20\2\u0204\u0205") buf.write(u"\5)\25\2\u0205\u0206\t\35\2\2\u0206\u0092\3\2\2\2\u0207") buf.write(u"\u0208\5)\25\2\u0208\u0209\5\13\6\2\u0209\u020a\5\'\24") buf.write(u"\2\u020a\u020b\5)\25\2\u020b\u020c\5\'\24\2\u020c\u020d") buf.write(u"\5\31\r\2\u020d\u020e\5\37\20\2\u020e\u020f\5)\25\2\u020f") buf.write(u"\u0210\t\36\2\2\u0210\u0094\3\2\2\2\u0211\u0212\5\3\2") buf.write(u"\2\u0212\u0213\5\'\24\2\u0213\u0214\5\'\24\2\u0214\u0215") buf.write(u"\5\13\6\2\u0215\u0216\5%\23\2\u0216\u0217\5)\25\2\u0217") buf.write(u"\u0096\3\2\2\2\u0218\u0219\5\31\r\2\u0219\u021a\5\23") buf.write(u"\n\2\u021a\u021b\5\35\17\2\u021b\u021c\5\13\6\2\u021c") buf.write(u"\u021d\5\7\4\2\u021d\u021e\5\37\20\2\u021e\u021f\5+\26") buf.write(u"\2\u021f\u0220\5\35\17\2\u0220\u0221\5)\25\2\u0221\u0098") buf.write(u"\3\2\2\2\u0222\u0223\5\13\6\2\u0223\u0224\5#\22\2\u0224") buf.write(u"\u0225\5+\26\2\u0225\u0226\5\3\2\2\u0226\u0227\5\31\r") buf.write(u"\2\u0227\u0228\5\'\24\2\u0228\u009a\3\2\2\2\u0229\u022a") buf.write(u"\5)\25\2\u022a\u022b\5\13\6\2\u022b\u022c\5\61\31\2\u022c") buf.write(u"\u022d\5)\25\2\u022d\u009c\3\2\2\2\u022e\u022f\5\7\4") buf.write(u"\2\u022f\u0230\5\31\r\2\u0230\u0231\5\13\6\2\u0231\u0232") buf.write(u"\5\3\2\2\u0232\u0233\5%\23\2\u0233\u009e\3\2\2\2\u0234") buf.write(u"\u0235\5\r\7\2\u0235\u0236\5\23\n\2\u0236\u0237\5\13") buf.write(u"\6\2\u0237\u0238\5\31\r\2\u0238\u0239\5\t\5\2\u0239\u023a") buf.write(u"\5\'\24\2\u023a\u00a0\3\2\2\2\u023b\u023c\5\35\17\2\u023c") buf.write(u"\u023d\5\13\6\2\u023d\u023e\5/\30\2\u023e\u023f\5\'\24") buf.write(u"\2\u023f\u00a2\3\2\2\2\u0240\u0241\5\'\24\2\u0241\u0242") buf.write(u"\5\21\t\2\u0242\u0243\5\37\20\2\u0243\u0244\5!\21\2\u0244") buf.write(u"\u0245\5!\21\2\u0245\u0246\5\23\n\2\u0246\u0247\5\35") buf.write(u"\17\2\u0247\u0248\5\17\b\2\u0248\u00a4\3\2\2\2\u0249") buf.write(u"\u024a\5\'\24\2\u024a\u024b\5\37\20\2\u024b\u024c\5\7") buf.write(u"\4\2\u024c\u024d\5\23\n\2\u024d\u024e\5\3\2\2\u024e\u024f") buf.write(u"\5\31\r\2\u024f\u00a6\3\2\2\2\u0250\u0251\5-\27\2\u0251") buf.write(u"\u0252\5\23\n\2\u0252\u0253\5\t\5\2\u0253\u0254\5\13") buf.write(u"\6\2\u0254\u0255\5\37\20\2\u0255\u00a8\3\2\2\2\u0256") buf.write(u"\u0257\5/\30\2\u0257\u0258\5\13\6\2\u0258\u0259\5\3\2") buf.write(u"\2\u0259\u025a\5)\25\2\u025a\u025b\5\21\t\2\u025b\u025c") buf.write(u"\5\13\6\2\u025c\u025d\5%\23\2\u025d\u00aa\3\2\2\2\u025e") buf.write(u"\u025f\5\7\4\2\u025f\u0260\5\37\20\2\u0260\u0261\5\33") buf.write(u"\16\2\u0261\u0262\5\33\16\2\u0262\u0263\5+\26\2\u0263") buf.write(u"\u0264\5\35\17\2\u0264\u0265\5\23\n\2\u0265\u0266\5\7") buf.write(u"\4\2\u0266\u0267\5\3\2\2\u0267\u0268\5)\25\2\u0268\u0269") buf.write(u"\5\23\n\2\u0269\u026a\5\37\20\2\u026a\u026b\5\35\17\2") buf.write(u"\u026b\u00ac\3\2\2\2\u026c\u026d\5\13\6\2\u026d\u026e") buf.write(u"\5\t\5\2\u026e\u026f\5+\26\2\u026f\u0270\5\7\4\2\u0270") buf.write(u"\u0271\5\3\2\2\u0271\u0272\5)\25\2\u0272\u0273\5\23\n") buf.write(u"\2\u0273\u0274\5\37\20\2\u0274\u0275\5\35\17\2\u0275") buf.write(u"\u00ae\3\2\2\2\u0276\u0277\5\r\7\2\u0277\u0278\5\37\20") buf.write(u"\2\u0278\u0279\5\37\20\2\u0279\u027a\5\t\5\2\u027a\u00b0") buf.write(u"\3\2\2\2\u027b\u027c\5\33\16\2\u027c\u027d\5\13\6\2\u027d") buf.write(u"\u027e\5\t\5\2\u027e\u027f\5\23\n\2\u027f\u0280\5\7\4") buf.write(u"\2\u0280\u0281\5\3\2\2\u0281\u0282\5\31\r\2\u0282\u00b2") buf.write(u"\3\2\2\2\u0283\u0284\5\3\2\2\u0284\u0285\5+\26\2\u0285") buf.write(u"\u0286\5\t\5\2\u0286\u0287\5\23\n\2\u0287\u0288\5\37") buf.write(u"\20\2\u0288\u00b4\3\2\2\2\u0289\u028a\5)\25\2\u028a\u028b") buf.write(u"\5\37\20\2\u028b\u028c\5\t\5\2\u028c\u028d\5\37\20\2") buf.write(u"\u028d\u00b6\3\2\2\2\u028e\u028f\5\3\2\2\u028f\u0290") buf.write(u"\5\t\5\2\u0290\u00b8\3\2\2\2\u0291\u0292\5\31\r\2\u0292") buf.write(u"\u0293\5\37\20\2\u0293\u0294\5\17\b\2\u0294\u0295\5\23") buf.write(u"\n\2\u0295\u0296\5\35\17\2\u0296\u00ba\3\2\2\2\u0297") buf.write(u"\u0298\5\31\r\2\u0298\u0299\5\23\n\2\u0299\u029a\5\'") buf.write(u"\24\2\u029a\u029b\5)\25\2\u029b\u00bc\3\2\2\2\u029c\u029d") buf.write(u"\5!\21\2\u029d\u029e\5\37\20\2\u029e\u029f\5%\23\2\u029f") buf.write(u"\u02a0\5)\25\2\u02a0\u02a1\5\3\2\2\u02a1\u02a2\5\31\r") buf.write(u"\2\u02a2\u00be\3\2\2\2\u02a3\u02a4\5\5\3\2\u02a4\u02a5") buf.write(u"\5%\23\2\u02a5\u02a6\5\37\20\2\u02a6\u02a7\5/\30\2\u02a7") buf.write(u"\u02a8\5\'\24\2\u02a8\u02a9\5\13\6\2\u02a9\u02aa\5%\23") buf.write(u"\2\u02aa\u00c0\3\2\2\2\u02ab\u02ac\5\33\16\2\u02ac\u02ad") buf.write(u"\5\3\2\2\u02ad\u02ae\5!\21\2\u02ae\u00c2\3\2\2\2\u02af") buf.write(u"\u02b0\5\33\16\2\u02b0\u02b1\5\13\6\2\u02b1\u02b2\5\'") buf.write(u"\24\2\u02b2\u02b3\5\'\24\2\u02b3\u02b4\5\3\2\2\u02b4") buf.write(u"\u02b5\5\17\b\2\u02b5\u02b6\5\13\6\2\u02b6\u02b7\5\'") buf.write(u"\24\2\u02b7\u00c4\3\2\2\2\u02b8\u02bc\7$\2\2\u02b9\u02bb") buf.write(u"\t\37\2\2\u02ba\u02b9\3\2\2\2\u02bb\u02be\3\2\2\2\u02bc") buf.write(u"\u02ba\3\2\2\2\u02bc\u02bd\3\2\2\2\u02bd\u02bf\3\2\2") buf.write(u"\2\u02be\u02bc\3\2\2\2\u02bf\u02c0\7$\2\2\u02c0\u00c6") buf.write(u"\3\2\2\2\u02c1\u02c3\t \2\2\u02c2\u02c1\3\2\2\2\u02c3") buf.write(u"\u02c4\3\2\2\2\u02c4\u02c2\3\2\2\2\u02c4\u02c5\3\2\2") buf.write(u"\2\u02c5\u02c6\3\2\2\2\u02c6\u02c7\bd\2\2\u02c7\u00c8") buf.write(u"\3\2\2\2\u02c8\u02ca\7\17\2\2\u02c9\u02c8\3\2\2\2\u02c9") buf.write(u"\u02ca\3\2\2\2\u02ca\u02cb\3\2\2\2\u02cb\u02ce\7\f\2") buf.write(u"\2\u02cc\u02ce\7\17\2\2\u02cd\u02c9\3\2\2\2\u02cd\u02cc") buf.write(u"\3\2\2\2\u02ce\u02cf\3\2\2\2\u02cf\u02cd\3\2\2\2\u02cf") buf.write(u"\u02d0\3\2\2\2\u02d0\u02d1\3\2\2\2\u02d1\u02d2\be\2\2") buf.write(u"\u02d2\u00ca\3\2\2\2\u02d3\u02d5\t!\2\2\u02d4\u02d3\3") buf.write(u"\2\2\2\u02d5\u02d6\3\2\2\2\u02d6\u02d4\3\2\2\2\u02d6") buf.write(u"\u02d7\3\2\2\2\u02d7\u02d9\3\2\2\2\u02d8\u02da\t\"\2") buf.write(u"\2\u02d9\u02d8\3\2\2\2\u02d9\u02da\3\2\2\2\u02da\u02de") buf.write(u"\3\2\2\2\u02db\u02dd\t!\2\2\u02dc\u02db\3\2\2\2\u02dd") buf.write(u"\u02e0\3\2\2\2\u02de\u02dc\3\2\2\2\u02de\u02df\3\2\2") buf.write(u"\2\u02df\u00cc\3\2\2\2\u02e0\u02de\3\2\2\2\13\2\u02bc") buf.write(u"\u02c4\u02c9\u02cd\u02cf\u02d6\u02d9\u02de\3\b\2\2") return buf.getvalue() class scriptingLanguageLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] WHEN = 1 APP = 2 COL = 3 SEMICOL = 4 IN = 5 CHECK = 6 FOR = 7 SAME = 8 DIFFERENT = 9 STATE = 10 INPUT = 11 NAME = 12 PASSWORD = 13 CLICK = 14 NEXT = 15 CLOSE = 16 PRESS = 17 BACK = 18 LINE = 19 LONG = 20 ALL = 21 URL = 22 ENTER = 23 MESSAGE = 24 TOGGLE = 25 SWIPE = 26 UP = 27 DOWN = 28 LEFT = 29 RIGHT = 30 SEARCH = 31 CENTER = 32 TICK = 33 ADD = 34 TASK = 35 CUSTOM = 36 DRAG = 37 FROM = 38 TO = 39 DURATION = 40 TYPE = 41 DEVICE = 42 EXECUTE = 43 SLEEP = 44 TESTSLOT1 = 45 TESTSLOT2 = 46 TESTSLOT3 = 47 ASSERT = 48 LINECOUNT = 49 EQUALS = 50 TEXT = 51 CLEAR = 52 FIELDS = 53 APPCAT1 = 54 APPCAT2 = 55 APPCAT3 = 56 APPCAT4 = 57 APPCAT5 = 58 APPCAT6 = 59 APPCAT7 = 60 APPCAT8 = 61 APPCAT9 = 62 APPCAT10 = 63 ACTTYPE1 = 64 ACTTYPE2 = 65 ACTTYPE3 = 66 ACTTYPE4 = 67 ACTTYPE5 = 68 ACTTYPE6 = 69 ACTTYPE7 = 70 ACTTYPE8 = 71 QUOTEDSTRING = 72 WHITESPACE = 73 NEWLINE = 74 NUMBER = 75 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ u"DEFAULT_MODE" ] literalNames = [ u"<INVALID>", u"':'", u"';'" ] symbolicNames = [ u"<INVALID>", u"WHEN", u"APP", u"COL", u"SEMICOL", u"IN", u"CHECK", u"FOR", u"SAME", u"DIFFERENT", u"STATE", u"INPUT", u"NAME", u"PASSWORD", u"CLICK", u"NEXT", u"CLOSE", u"PRESS", u"BACK", u"LINE", u"LONG", u"ALL", u"URL", u"ENTER", u"MESSAGE", u"TOGGLE", u"SWIPE", u"UP", u"DOWN", u"LEFT", u"RIGHT", u"SEARCH", u"CENTER", u"TICK", u"ADD", u"TASK", u"CUSTOM", u"DRAG", u"FROM", u"TO", u"DURATION", u"TYPE", u"DEVICE", u"EXECUTE", u"SLEEP", u"TESTSLOT1", u"TESTSLOT2", u"TESTSLOT3", u"ASSERT", u"LINECOUNT", u"EQUALS", u"TEXT", u"CLEAR", u"FIELDS", u"APPCAT1", u"APPCAT2", u"APPCAT3", u"APPCAT4", u"APPCAT5", u"APPCAT6", u"APPCAT7", u"APPCAT8", u"APPCAT9", u"APPCAT10", u"ACTTYPE1", u"ACTTYPE2", u"ACTTYPE3", u"ACTTYPE4", u"ACTTYPE5", u"ACTTYPE6", u"ACTTYPE7", u"ACTTYPE8", u"QUOTEDSTRING", u"WHITESPACE", u"NEWLINE", u"NUMBER" ] ruleNames = [ u"A", u"B", u"C", u"D", u"E", u"F", u"G", u"H", u"I", u"J", u"K", u"L", u"M", u"N", u"O", u"P", u"Q", u"R", u"S", u"T", u"U", u"V", u"W", u"X", u"Y", u"Z", u"WHEN", u"APP", u"COL", u"SEMICOL", u"IN", u"CHECK", u"FOR", u"SAME", u"DIFFERENT", u"STATE", u"INPUT", u"NAME", u"PASSWORD", u"CLICK", u"NEXT", u"CLOSE", u"PRESS", u"BACK", u"LINE", u"LONG", u"ALL", u"URL", u"ENTER", u"MESSAGE", u"TOGGLE", u"SWIPE", u"UP", u"DOWN", u"LEFT", u"RIGHT", u"SEARCH", u"CENTER", u"TICK", u"ADD", u"TASK", u"CUSTOM", u"DRAG", u"FROM", u"TO", u"DURATION", u"TYPE", u"DEVICE", u"EXECUTE", u"SLEEP", u"TESTSLOT1", u"TESTSLOT2", u"TESTSLOT3", u"ASSERT", u"LINECOUNT", u"EQUALS", u"TEXT", u"CLEAR", u"FIELDS", u"APPCAT1", u"APPCAT2", u"APPCAT3", u"APPCAT4", u"APPCAT5", u"APPCAT6", u"APPCAT7", u"APPCAT8", u"APPCAT9", u"APPCAT10", u"ACTTYPE1", u"ACTTYPE2", u"ACTTYPE3", u"ACTTYPE4", u"ACTTYPE5", u"ACTTYPE6", u"ACTTYPE7", u"ACTTYPE8", u"QUOTEDSTRING", u"WHITESPACE", u"NEWLINE", u"NUMBER" ] grammarFileName = u"scriptingLanguage.g4" def __init__(self, input=None, output=sys.stdout): super(scriptingLanguageLexer, self).__init__(input, output=output) self.checkVersion("4.7.1") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
{"/graphPlotter.py": ["/stateNode.py"]}
50,835
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/graphPlotter.py
import networkx as nx import matplotlib.pyplot as plt from stateNode import stateNode from graphviz import Digraph import re def drawCurrentlyExploredNodes(statesCompletelyExplored): # Instantiating the directional graph graph = nx.DiGraph() # Iterating over all states that are completely explored for exploredState in statesCompletelyExplored: # Iterating over the outgoing edges of this state edges = exploredState.getOutgoingStateDictionary() for uiKey, arrivingState in edges.items(): graph.add_edge(exploredState.getStateName(), arrivingState.getStateName()) # Setting the layout type for the graph pos = nx.spring_layout(graph) # Setting the figure size plt.figure(dpi=500) nx.draw(graph, pos, with_labels=True) plt.show() # plt.savefig("simple_path.png") def drawCurrentlyExploredNodesGraphivz(statesCompletelyExplored): # Instantiating the directional graph graph = Digraph('G', filename='C:/Users/artur/PycharmProjects/AndroidTestingPy27/charts/outputGraph.gv', format='png') # Iterating over all states that are completely explored for exploredState in statesCompletelyExplored: # Iterating over the outgoing edges of this state edges = exploredState.getOutgoingStateDictionary() for uiKey, arrivingState in edges.items(): # Crafting a compact version of the node name startNum = re.sub("[^0-9]", "", exploredState.getStateName()) arrivingNum = re.sub("[^0-9]", "", arrivingState.getStateName()) startName = "s" + startNum arrivingName = "s" + arrivingNum # Instantiating the new edge graph.edge(startName, arrivingName, label=str(uiKey)) graph.render(filename='C:/Users/artur/PycharmProjects/AndroidTestingPy27/charts/outputGraph.gv', format='png')
{"/graphPlotter.py": ["/stateNode.py"]}
50,836
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/customLanguageInterpreter/scriptingLanguageListener.py
# Generated from scriptingLanguage.g4 by ANTLR 4.7.1 from antlr4 import * from testClass import testClass # This class defines a complete listener for a parse tree produced by scriptingLanguageParser. class scriptingLanguageListener(ParseTreeListener): # This function the INITIALIZATION function called when the Listener is instantiated def __init__(self, suiteObject): # Setting the variables that will be used by the other functions that will be called in the future self.testValue = 33 self.suiteObject = suiteObject # Enter a parse tree produced by scriptingLanguageParser#suite. def enterSuite(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#suite. def exitSuite(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#apptype. def enterApptype(self, ctx): # Finding out the app category appCategory = ctx.children[0] # Setting it to the suiteObject self.suiteObject.setTargetAppCategory(appCategory) pass # Exit a parse tree produced by scriptingLanguageParser#apptype. def exitApptype(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testlist. def enterTestlist(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testlist. def exitTestlist(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype1. def enterTesttype1(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype1. def exitTesttype1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype2. def enterTesttype2(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype2. def exitTesttype2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype3. def enterTesttype3(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype3. def exitTesttype3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype4. def enterTesttype4(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype4. def exitTesttype4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype5. def enterTesttype5(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype5. def exitTesttype5(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype6. def enterTesttype6(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype6. def exitTesttype6(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype7. def enterTesttype7(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype7. def exitTesttype7(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testtype8. def enterTesttype8(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testtype8. def exitTesttype8(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testsame1. def enterTestsame1(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame1. def exitTestsame1(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff1. def enterTestdiff1(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff1. def exitTestdiff1(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testsame2. def enterTestsame2(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame2. def exitTestsame2(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff2. def enterTestdiff2(self, ctx): # Retrieving the starting activity type startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff2. def exitTestdiff2(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testsame3. def enterTestsame3(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame3. def exitTestsame3(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff3. def enterTestdiff3(self, ctx): # Retrieving the starting activity type startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff3. def exitTestdiff3(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testsame4. def enterTestsame4(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame4. def exitTestsame4(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff4. def enterTestdiff4(self, ctx): # Retrieving the starting activity type startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff4. def exitTestdiff4(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testsame5. def enterTestsame5(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame5. def exitTestsame5(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff5. def enterTestdiff5(self, ctx): # Retrieving the starting activity type startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff5. def exitTestdiff5(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testsame6. def enterTestsame6(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame6. def exitTestsame6(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff6. def enterTestdiff6(self, ctx): # Retrieving the starting activity type startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff6. def exitTestdiff6(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testsame7. def enterTestsame7(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame7. def exitTestsame7(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff7. def enterTestdiff7(self, ctx): # Retrieving the starting activity type startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff7. def exitTestdiff7(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testsame8. def enterTestsame8(self, ctx): # This is the case of LOGIN activity startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, True) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testsame8. def exitTestsame8(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#testdiff8. def enterTestdiff8(self, ctx): # Retrieving the starting activity type startingActivity = str(ctx.children[1]) print "\nAbout to parse a test for activity: " + startingActivity # Instantiating the test object testObject = testClass(startingActivity, False, str(ctx.children[6].children[0])) # Setting this object as temporary up to when we have filled all its commands self.tempTest = testObject pass # Exit a parse tree produced by scriptingLanguageParser#testdiff8. def exitTestdiff8(self, ctx): # Eventually adding the test to its suite self.suiteObject.addTestObject(self.tempTest) print "Done with " + str(len(self.suiteObject.testCasesList)) + " tests" pass # Enter a parse tree produced by scriptingLanguageParser#activitytype. def enterActivitytype(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#activitytype. def exitActivitytype(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist1. def enterCommandlist1(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist1. def exitCommandlist1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver1. def enterCommand1ver1(self, ctx): # Retrieving the input string for the note name inputString = str(ctx.children[2]) # Creafting the command string commandString = "test.todoAddNewNote(" + inputString + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command1ver1. def exitCommand1ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver2. def enterCommand1ver2(self, ctx): # Retrieving the input string for the note name lineNum = str(ctx.children[2]) # Creafting the command string commandString = "test.tickLine(" + str(lineNum) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command1ver2. def exitCommand1ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver3. def enterCommand1ver3(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command1ver3. def exitCommand1ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver4. def enterCommand1ver4(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command1ver4. def exitCommand1ver4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver5. def enterCommand1ver5(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command1ver5. def exitCommand1ver5(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver6. def enterCommand1ver6(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command1ver6. def exitCommand1ver6(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver7. def enterCommand1ver7(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command1ver7. def exitCommand1ver7(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command1ver7. def enterCommand1ver8(self, ctx): # Retrieving the input string for the note name assertingNum = str(ctx.children[3]) # Creafting the command string commandString = "test.assertNumNotes(" + str(assertingNum) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command1ver7. def exitCommand1ver8(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist2. def enterCommandlist2(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist2. def exitCommandlist2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command2ver1. def enterCommand2ver1(self, ctx): # Creafting the command string commandString = "test.closeAd()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command2ver1. def exitCommand2ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command2ver2. def enterCommand2ver2(self, ctx): # Creafting the command string commandString = "test.openAd()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command2ver2. def exitCommand2ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command2ver3. def enterCommand2ver3(self, ctx): # Creafting the command string commandString = "test.backAd()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command2ver3. def exitCommand2ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist3. def enterCommandlist3(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist3. def exitCommandlist3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command3ver1. def enterCommand3ver1(self, ctx): # Retrieving and elaborating the input string inputString = str(ctx.children[2]) # Crafting the command string commandString = "test.loginInputName(" + inputString + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command3ver1. def exitCommand3ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command3ver2. def enterCommand3ver2(self, ctx): # Retrieving and elaborating the input string inputString = str(ctx.children[2]) # Crafting the command string commandString = "test.loginInputPassword(" + inputString + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command3ver2. def exitCommand3ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command3ver3. def enterCommand3ver3(self, ctx): # Simply adding the 'click next' command commandString = "test.clickNext()" self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command3ver3. def exitCommand3ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command3ver3. def enterCommand3ver4(self, ctx): # Simply adding the 'click next' command commandString = "test.clearFields()" self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command3ver3. def exitCommand3ver4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist4. def enterCommandlist4(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist4. def exitCommandlist4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command4ver1. def enterCommand4ver1(self, ctx): # Retrieving and elaborating the input string lineNumber = str(ctx.children[2]) # Crafting the command string commandString = "test.clickListLine(" + lineNumber + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command4ver1. def exitCommand4ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command4ver2. def enterCommand4ver2(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command4ver2. def exitCommand4ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command4ver3. def enterCommand4ver3(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command4ver3. def exitCommand4ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command4ver4. def enterCommand4ver4(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command4ver4. def exitCommand4ver4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command4ver5. def enterCommand4ver5(self, ctx): # Crafting the command string commandString = "test.customPressBack()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command4ver5. def exitCommand4ver5(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command4ver6. def enterCommand4ver6(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command4ver6. def exitCommand4ver6(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command4ver7. def enterCommand4ver7(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command4ver7. def exitCommand4ver7(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist5. def enterCommandlist5(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist5. def exitCommandlist5(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command5ver1. def enterCommand5ver1(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command5ver1. def exitCommand5ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command5ver2. def enterCommand5ver2(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command5ver2. def exitCommand5ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command5ver3. def enterCommand5ver3(self, ctx): # Crafting the command string commandString = "test.swipeLeftPortal()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command5ver3. def exitCommand5ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command5ver4. def enterCommand5ver4(self, ctx): # Crafting the command string commandString = "test.swipeRightPortal()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command5ver4. def exitCommand5ver4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist6. def enterCommandlist6(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist6. def exitCommandlist6(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command6ver1. def enterCommand6ver1(self, ctx): # Retrieving and elaborating the input string inputString = str(ctx.children[2]) # Crafting the command string commandString = "test.inputUrl(" + inputString + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command6ver1. def exitCommand6ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command6ver2. def enterCommand6ver2(self, ctx): # Crafting the command string commandString = "test.pressEnterUrl()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command6ver2. def exitCommand6ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command6ver3. def enterCommand6ver3(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command6ver3. def exitCommand6ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist7. def enterCommandlist7(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist7. def exitCommandlist7(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command7ver1. def enterCommand7ver1(self, ctx): # Retrieving and elaborating the input string inputString = str(ctx.children[2]) # Crafting the command string commandString = "test.searchOnMap(" + inputString + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command7ver1. def exitCommand7ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command7ver2. def enterCommand7ver2(self, ctx): # Crafting the command string commandString = "test.swipeUp()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command7ver2. def exitCommand7ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command7ver3. def enterCommand7ver3(self, ctx): # Crafting the command string commandString = "test.swipeDown()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command7ver3. def exitCommand7ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command7ver4. def enterCommand7ver4(self, ctx): # Crafting the command string commandString = "test.swipeLeft()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command7ver4. def exitCommand7ver4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command7ver5. def enterCommand7ver5(self, ctx): # Crafting the command string commandString = "test.swipeRight()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command7ver5. def exitCommand7ver5(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command7ver6. def enterCommand7ver6(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command7ver6. def exitCommand7ver6(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command7ver7. def enterCommand7ver7(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command7ver7. def exitCommand7ver7(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandlist8. def enterCommandlist8(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#commandlist8. def exitCommandlist8(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command8ver1. def enterCommand8ver1(self, ctx): # Retrieving and elaborating the input string inputString = str(ctx.children[2]) # Crafting the command string commandString = "test.inputMessage(" + inputString + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command8ver1. def exitCommand8ver1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command8ver2. def enterCommand8ver2(self, ctx): # Crafting the command string commandString = "test.sendMessage()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#command8ver2. def exitCommand8ver2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command8ver3. def enterCommand8ver3(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command8ver3. def exitCommand8ver3(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command8ver4. def enterCommand8ver4(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command8ver4. def exitCommand8ver4(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#command8ver5. def enterCommand8ver5(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#command8ver5. def exitCommand8ver5(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomClick. def enterCommandCustomClick(self, ctx): # Retrieving screen coordinates x = ctx.children[2].children[0] y = ctx.children[2].children[1] # Crafting the command string commandString = "test.customClick(" + str(x) + "," + str(y) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomClick. def exitCommandCustomClick(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomLongClick. def enterCommandCustomLongClick(self, ctx): # Retrieving screen coordinates x = ctx.children[3].children[0] y = ctx.children[3].children[1] # Crafting the command string commandString = "test.customLongClick(" + str(x) + "," + str(y) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomLongClick. def exitCommandCustomLongClick(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomDrag. def enterCommandCustomDrag(self, ctx): # Retrieving screen coordinates and drag duration xStart = ctx.children[3].children[0] yStart = ctx.children[3].children[1] xEnd = ctx.children[5].children[0] yEnd = ctx.children[5].children[1] duration = ctx.children[7] # Crafting the command string commandString = "test.customDrag(" + str(xStart) + "," + str(yStart) + "," + str(xEnd) + "," + str(yEnd) + "," + str(duration) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomDrag. def exitCommandCustomDrag(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomType. def enterCommandCustomType(self, ctx): # Retrieving screen coordinates inputString = ctx.children[2] # Crafting the command string commandString = "test.customType(" + str(inputString) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomType. def exitCommandCustomType(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomBack. def enterCommandCustomBack(self, ctx): # Crafting the command string commandString = "test.customPressBack()" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomBack. def exitCommandCustomBack(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomSleep. def enterCommandCustomSleep(self, ctx): # Getting the seconds of sleep inputString = ctx.children[2] # Crafting the command string commandString = "test.customSleep(" + str(inputString) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomSleep. def exitCommandCustomSleep(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomSleep. def enterCommandCustomAssertText(self, ctx): # Getting the seconds of sleep inputString = ctx.children[4] # Crafting the command string commandString = "test.customAssertText(" + str(inputString) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomSleep. def exitCommandCustomAssertText(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#commandCustomSleep. def enterCommandCustomClickText(self, ctx): # Getting the seconds of sleep inputString = ctx.children[3] # Crafting the command string commandString = "test.customClickText(" + str(inputString) + ")" # Adding the command to the list of the temporary test self.tempTest.appendCommandFunction(commandString) print "Entering command: " + commandString pass # Exit a parse tree produced by scriptingLanguageParser#commandCustomSleep. def exitCommandCustomClickText(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#coordinate. def enterCoordinate(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#coordinate. def exitCoordinate(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testCustom. def enterTestCustom(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testCustom. def exitTestCustom(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testSlot1. def enterTestSlot1(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testSlot1. def exitTestSlot1(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testSlot2. def enterTestSlot2(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testSlot2. def exitTestSlot2(self, ctx): pass # Enter a parse tree produced by scriptingLanguageParser#testSlot3. def enterTestSlot3(self, ctx): pass # Exit a parse tree produced by scriptingLanguageParser#testSlot3. def exitTestSlot3(self, ctx): pass
{"/graphPlotter.py": ["/stateNode.py"]}
50,837
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/customLanguageInterpreter/suiteClass.py
from testClass import testClass class suiteClass: # This class coincides with the concept of the test suite def __init__(self): # This is the list of test cases being initialized self.testCasesList = [] # This is the type of App APK for which this test suite is for self.targetAppCategory = "" def setTargetAppCategory(self, appCategory): self.targetAppCategory = appCategory def addTestObject(self, testObject): self.testCasesList.append(testObject)
{"/graphPlotter.py": ["/stateNode.py"]}
50,838
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/main.py
import re import sys import time import os import subprocess from com.dtmilano.android.viewclient import ViewClient, View, ViewClientOptions from com.dtmilano.android.adb import adbclient from com.dtmilano.android.common import debugArgsToDict from stateNode import stateNode import graphPlotter as gp import pickle ################################ ########## FUNCTIONS ########### # Given a dump line, this function returns the name/value pair corresponding to the given argument string (needle) def findPairContaining(originalStr = "", needle = ""): wordList = originalStr.split() for word in wordList: word = word.strip() if needle in word: return word return "" # Given a dump line, this function returns the name/value pairs contained in it (all UI element's attributes) def extractAttributesDictionaryFromDumpLine(dumpLine =""): # Get every field except for bound dictionary = {} wordList = dumpLine.split() for word in wordList: if '=' in word and 'bounds=' not in word: (name,value) = word.split("=",1) dictionary[name] = value # Bound field is discarded due to its different structure, so we need to find it manually now boundRegex = re.search("bounds.*\)\)", dumpLine) if boundRegex: found = boundRegex.group(0) if '=' in found: (name, value) = found.split("=") dictionary[name] = value return dictionary # This function dumps the current view and transform it into a viewList def dumpAndReturnViewList(vc): # Updating the dump for the current view: need to dump every time the view changes vc.dump(window='-1') # Printing the dump structure to output file myFileHandle = open("output.txt", "w+") transform = View.__str__ # This parameter tells the dump traverser to print all informations vc.traverse("ROOT", "", transform, myFileHandle) myFileHandle.close() # Parsing the saved dump into the viewList variable with open("output.txt", "r") as myFileHandle: line = myFileHandle.readline() viewList = [] while line: viewList.append(line.strip()) line = myFileHandle.readline() return viewList # Generator used to get UI elements from a state queue until None is returned def UIelementGenerator(state): while True: element = state.popUIelementToAnalyze() if element is None: break yield element # This method moves from the root state to the argument state, following its roadmap def traverseFromRootToState(startActivityName, finalState): print "---> Reaching state " + finalState.getStateName() + " from root " + startActivityName roadMapToFollow = finalState.getRoadMap() print "---> Following roadMap " + str(roadMapToFollow) device.startActivity(startActivityName) # Iterate through all UI elements necessary to reach that state from root vc.sleep(2) for element in roadMapToFollow: vc.dump(window='-1') if element != 'START': handle = vc.findViewWithAttributeOrRaise('uniqueId', element, "ROOT") (x, y) = handle.getXY() # Press it vc.touch(x, y) vc.sleep(2) # This method tries to reduce the duplicate states def shrinkStates(statesToExploreQueue, numAddedNewStates): # If we know the number of states added in the last iteration, we just need to check them numAdded = numAddedNewStates totLength = len(statesToExploreQueue) while numAdded > 0: # Finding the index of the state to check index = totLength - numAdded numAdded = numAdded - 1 stateToConsider = statesToExploreQueue[index] # Checking if this state is in the 'completed list' toRemove = False for completed in statesCompletelyExplored: if completed.getAttributesDictionary() == stateToConsider.getAttributesDictionary(): toRemove = True # Adjusting the children list for the father, which is now pointing to nothing fatherDictionary = stateToConsider.getFather().getOutgoingStateDictionary() for ui, state in fatherDictionary.items(): if state.getStateName() == stateToConsider.getStateName(): fatherDictionary[ui] = completed stateToConsider.getFather().updateOutgoingStateDictionary(fatherDictionary) # Checking if this state is in the 'still to explore list' if toRemove == False: for i in range(0, totLength): if i != index and statesToExploreQueue[i].getAttributesDictionary() == stateToConsider.getAttributesDictionary(): if i > index: numAdded = numAdded - 1 toRemove = True # Adjusting the children list for the father, which is now pointing to nothing fatherDictionary = stateToConsider.getFather().getOutgoingStateDictionary() for ui, state in fatherDictionary.items(): if state.getStateName() == stateToConsider.getStateName(): fatherDictionary[ui] = statesToExploreQueue[i] stateToConsider.getFather().updateOutgoingStateDictionary(fatherDictionary) # Removing if necessary if toRemove == True: statesToExploreQueue.remove(stateToConsider) totLength = totLength - 1 print '[[ REMOVED DUPLICATE STATE ' + stateToConsider.getStateName() + " ]]" else: print '[[ No duplicates were removed from queue ]]' return statesToExploreQueue ################################ ################################ # Setting the ViewClient's options kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': True} kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': False} # Connecting to the Device device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1) # Instatiation of the ViewClient for the selected Device: this is an interface for the device's views vc = ViewClient(device, serialno, **kwargs2) if vc.useUiAutomator: print "ViewClient: using UiAutomator backend" ################################################################ print "################## Android OS VERSION TEST ####################" # Starting an activity by its name #device.startActivity('com.android.settings/.Settings') #device.startActivity('com.google.android.apps.messaging/com.google.android.apps.messaging.ui.ConversationListActivity') print 'Starting exploration...' # Saving the name of the starting activity startingActivityName = device.getFocusedWindowName() # Preparing the initial START STATE of the application vc.dump(window='-1') elementToAttributesDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') elementToAttributesDictionary[elementAttributes['uniqueId']] = elementAttributes # Generating the Start State startState = stateNode(['START'], elementToAttributesDictionary) # Preparing the queue of state that we will analyze statesToExploreQueue = [] statesCompletelyExplored = [] statesToExploreQueue.append(startState) numAddedNewStates = 0 print 'Start state successfully generated and states queue initialized!' # Main loop: keep going as long as we have new states to explore in our queue while len(statesToExploreQueue) != 0: print "---------------------------------------------------" # Trying to reduce the number of states in the queue statesToExploreQueue = shrinkStates(statesToExploreQueue, numAddedNewStates) # Drawing graph chart gp.drawCurrentlyExploredNodesGraphivz(statesCompletelyExplored) numAddedNewStates = 0 # Saving the Graph Explored up to this moment pickleFile = open('C:/Users/artur/PycharmProjects/AndroidTestingPy27/outputFiles/resultingGraphObject.obj', 'w') pickle.dump(statesCompletelyExplored, pickleFile) pickleFile.close() # Pop a state currentState = statesToExploreQueue.pop(0) # Move from root to that state and update the dump to allow for button pressure traverseFromRootToState(startingActivityName, currentState) # vc.sleep(2) # UPDATING THE UI ELEMENTS DICTIONARY FOR POPPED STATE vc.dump(window='-1') newDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') newDictionary[elementAttributes['uniqueId']] = elementAttributes currentState.updateAttributes(newDictionary) print '\nAnalyzing state ' + currentState.getStateName() while True: # This loop is necessary to keep retrying if UI elements are not found try: # Inner loop: keep going as long as we have UI elements still to explore for UiElement in UIelementGenerator(currentState): if str(currentState.attributesDictionary[UiElement]['clickable']) == 'false': continue # Getting info about this UI element currentDictionary = currentState.getAttributesDictionary() # if currentDictionary[UiElement]['focusable'] == 'false': # continue print '\nYet to analyze ' + str(currentState.getCurrentQueueLength()) + ' UI elements' # UiElement is the UniqueId of the UI element in question viewHandle = vc.findViewWithAttributeOrRaise('uniqueId', UiElement, "ROOT") (x, y) = viewHandle.getXY() # Press it print 'Pressing ' + str(UiElement) vc.touch(x, y) vc.sleep(2) # Now we MIGHT have ended in a new state... # First check if state has changed by dumping its content vc.dump(window='-1') newDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') newDictionary[elementAttributes['uniqueId']] = elementAttributes # Determine if the resulting state is new if newDictionary == currentState.getAttributesDictionary(): # Same State print 'Still in same state' else: # New State: generating it newRoadMap = currentState.getRoadMap() newRoadMap.append(UiElement) newState = stateNode(newRoadMap, newDictionary, currentState) # Insert it into the states queue statesToExploreQueue.append(newState) # Update the outgoing dictionary for the current state currentState.addOutgoingState(UiElement, newState) # Now go back to the 'current state'... print 'NEW STATE: ' + newState.getStateName() + ' ||| Queue to explore size: ' + str( len(statesToExploreQueue)) traverseFromRootToState(startingActivityName, currentState) numAddedNewStates = numAddedNewStates + 1 vc.sleep(2) vc.dump(window='-1') break except: print "+++ UI has changed and could not find an element. Trying again! +++" # UPDATING THE UI ELEMENTS DICTIONARY FOR POPPED STATE traverseFromRootToState(startingActivityName, currentState) vc.sleep(2) vc.dump(window='-1') newDictionary = {} for element in vc.viewsById: # element is a string (uniqueID) # Getting the dictionary of attributes for this specific UI element ('attribute name -> value') elementAttributes = vc.viewsById[element].map # Adding that to the general dictionary for all UI elements of this state ('UI element -> attributes dictionary') newDictionary[elementAttributes['uniqueId']] = elementAttributes currentState.updateAttributes(newDictionary) print '\nAnalyzing state ' + currentState.getStateName() # We finished exploring the current state, so we put it into the 'completed list' statesCompletelyExplored.append(currentState) # Updating the dump for the current view: need to dump every time the view changes vc.dump(window='-1') # Printing the dump structure to output file myFileHandle = open("output.txt","w+") transform = View.__str__ # This parameter tells the dump traverser to print all informations vc.traverse("ROOT", "", transform, myFileHandle) myFileHandle.close() # Parsing the saved dump into the viewList variable with open("output.txt","r") as myFileHandle: line = myFileHandle.readline() viewList = [] while line: viewList.append(line.strip()) line = myFileHandle.readline() # Trying to press UI elements previousActivity = device.getFocusedWindowName() counter = 0 tot = len(viewList) for viewElement in viewList: counter = counter + 1 print "Touching element " + str(counter) + "/" + str(tot) # Extract all attributes for the current UI element elementAttributes = extractAttributesDictionaryFromDumpLine(viewElement) # Use its uniqueID to get an handle for it uniqueID = elementAttributes['uniqueId'] viewHandle = vc.findViewWithAttributeOrRaise('uniqueId',uniqueID,"ROOT") (x,y) = viewHandle.getXY() # Press it vc.touch(x,y) vc.sleep(1) currentActivity = device.getFocusedWindowName() print currentActivity vc.sleep(2) # Press back if we ended up in a new activity if currentActivity != previousActivity: # Press back again if keyboard has come up if device.isKeyboardShown(): subprocess.call("adb shell input keyevent KEYCODE_BACK", shell=True) if 'PopupWindow' in currentActivity: print "A popup with " + str(len(dumpAndReturnViewList(vc))) + " has been found!" subprocess.call("adb shell input keyevent KEYCODE_BACK", shell=True) vc.sleep(1) # If we end up with new screen items in the same activity elif dumpAndReturnViewList(vc) != viewList: print "Different screen!!!!" # Press back if the keyboard has come up but we're still in same search (search bar) if device.isKeyboardShown(): subprocess.call("adb shell input keyevent KEYCODE_BACK", shell=True) # Find a specific view from the dump of the view, get its coordinates, and touch them foundButton = vc.findViewWithTextOrRaise("Battery","ROOT") (x,y) = foundButton.getXY() print device.getFocusedWindowName() vc.touch(x,y) vc.sleep(3) print device.getFocusedWindowName() # Pressing back button on OS bottom bar subprocess.call("adb shell input keyevent KEYCODE_BACK",shell=True) foundButton = vc.findViewWithTextOrRaise("Display","ROOT") (x,y) = foundButton.getXY() print device.getFocusedWindowName() vc.touch(x,y) vc.sleep(3) print device.getFocusedWindowName()
{"/graphPlotter.py": ["/stateNode.py"]}
50,839
ArtyZiff35/Android-Application-State-Graph-Model-Parser
refs/heads/master
/customLanguageInterpreter/scriptingLanguageParser.py
# Generated from scriptingLanguage.g4 by ANTLR 4.7.1 # encoding: utf-8 from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3") buf.write(u"M\u02fa\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t") buf.write(u"\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r") buf.write(u"\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4") buf.write(u"\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30") buf.write(u"\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t") buf.write(u"\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$") buf.write(u"\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t") buf.write(u",\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63") buf.write(u"\t\63\4\64\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\4") buf.write(u"9\t9\4:\t:\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA") buf.write(u"\4B\tB\4C\tC\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\t") buf.write(u"J\4K\tK\4L\tL\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S") buf.write(u"\tS\4T\tT\4U\tU\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\3") buf.write(u"\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3") buf.write(u"\4\3\4\3\4\6\4\u00c7\n\4\r\4\16\4\u00c8\3\5\3\5\5\5\u00cd") buf.write(u"\n\5\3\6\3\6\5\6\u00d1\n\6\3\7\3\7\5\7\u00d5\n\7\3\b") buf.write(u"\3\b\5\b\u00d9\n\b\3\t\3\t\5\t\u00dd\n\t\3\n\3\n\5\n") buf.write(u"\u00e1\n\n\3\13\3\13\5\13\u00e5\n\13\3\f\3\f\5\f\u00e9") buf.write(u"\n\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16\3") buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\17\3\17\3\17") buf.write(u"\3\17\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20\3") buf.write(u"\20\3\20\3\20\3\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21") buf.write(u"\3\21\3\21\3\21\3\21\3\22\3\22\3\22\3\22\3\22\3\22\3") buf.write(u"\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\23\3\23") buf.write(u"\3\23\3\23\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3") buf.write(u"\24\3\24\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25") buf.write(u"\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3") buf.write(u"\27\3\27\3\27\3\27\3\27\3\27\3\27\3\27\3\27\3\30\3\30") buf.write(u"\3\30\3\30\3\30\3\30\3\30\3\30\3\30\3\30\3\31\3\31\3") buf.write(u"\31\3\31\3\31\3\31\3\31\3\31\3\31\3\32\3\32\3\32\3\32") buf.write(u"\3\32\3\32\3\32\3\32\3\32\3\32\3\33\3\33\3\33\3\33\3") buf.write(u"\33\3\33\3\33\3\33\3\33\3\34\3\34\3\34\3\34\3\34\3\34") buf.write(u"\3\34\3\34\3\34\3\34\3\35\3\35\3\36\3\36\3\36\3\36\3") buf.write(u"\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36") buf.write(u"\3\36\3\36\5\36\u0196\n\36\3\36\3\36\6\36\u019a\n\36") buf.write(u"\r\36\16\36\u019b\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3!") buf.write(u"\3!\3!\3\"\3\"\3\"\3\"\3#\3#\3#\3$\3$\3$\3%\3%\3%\3&") buf.write(u"\3&\3&\3&\3&\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'") buf.write(u"\3\'\3\'\5\'\u01c7\n\'\3\'\3\'\6\'\u01cb\n\'\r\'\16\'") buf.write(u"\u01cc\3(\3(\3(\3)\3)\3)\3*\3*\3*\3+\3+\3+\3+\3+\3+\3") buf.write(u"+\3+\3+\3+\3+\3+\3+\5+\u01e5\n+\3+\3+\6+\u01e9\n+\r+") buf.write(u"\16+\u01ea\3,\3,\3,\3,\3-\3-\3-\3-\3.\3.\3.\3/\3/\3/") buf.write(u"\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3") buf.write(u"\60\3\60\3\60\3\60\3\60\3\60\5\60\u020b\n\60\3\60\3\60") buf.write(u"\6\60\u020f\n\60\r\60\16\60\u0210\3\61\3\61\3\61\3\61") buf.write(u"\3\62\3\62\3\62\3\62\3\63\3\63\3\63\3\63\3\63\3\64\3") buf.write(u"\64\3\64\3\64\3\65\3\65\3\65\3\66\3\66\3\66\3\67\3\67") buf.write(u"\3\67\38\38\38\38\38\38\38\38\38\38\38\38\38\58\u023a") buf.write(u"\n8\38\38\68\u023e\n8\r8\168\u023f\39\39\39\3:\3:\3:") buf.write(u"\3;\3;\3;\3<\3<\3<\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3") buf.write(u"=\5=\u025a\n=\3=\3=\6=\u025e\n=\r=\16=\u025f\3>\3>\3") buf.write(u">\3>\3?\3?\3?\3@\3@\3@\3A\3A\3A\3A\3A\3A\3A\3A\3A\3A") buf.write(u"\3A\3A\3A\3A\3A\3A\5A\u027c\nA\3A\3A\6A\u0280\nA\rA\16") buf.write(u"A\u0281\3B\3B\3B\3B\3C\3C\3C\3D\3D\3D\3E\3E\3E\3F\3F") buf.write(u"\3F\3G\3G\3G\3H\3H\3H\3H\3I\3I\3I\3I\3I\3I\3I\3I\3I\3") buf.write(u"I\3I\3I\3I\3I\5I\u02a9\nI\3I\3I\6I\u02ad\nI\rI\16I\u02ae") buf.write(u"\3J\3J\3J\3J\3K\3K\3K\3L\3L\3L\3M\3M\3M\3N\3N\3N\3O\3") buf.write(u"O\3O\3O\3P\3P\3P\3P\3P\3Q\3Q\3Q\3Q\3Q\3Q\3Q\3Q\3Q\3R") buf.write(u"\3R\3R\3R\3S\3S\3S\3S\3S\3T\3T\3T\3T\3U\3U\3U\3U\3U\3") buf.write(u"U\3V\3V\3V\3V\3V\3W\3W\3W\3X\3X\3X\3X\5X\u02f2\nX\3Y") buf.write(u"\3Y\3Z\3Z\3[\3[\3[\2\2\\\2\4\6\b\n\f\16\20\22\24\26\30") buf.write(u"\32\34\36 \"$&(*,.\60\62\64\668:<>@BDFHJLNPRTVXZ\\^`") buf.write(u"bdfhjlnprtvxz|~\u0080\u0082\u0084\u0086\u0088\u008a\u008c") buf.write(u"\u008e\u0090\u0092\u0094\u0096\u0098\u009a\u009c\u009e") buf.write(u"\u00a0\u00a2\u00a4\u00a6\u00a8\u00aa\u00ac\u00ae\u00b0") buf.write(u"\u00b2\u00b4\2\4\3\28A\3\2BI\2\u0322\2\u00b6\3\2\2\2") buf.write(u"\4\u00bc\3\2\2\2\6\u00c6\3\2\2\2\b\u00cc\3\2\2\2\n\u00d0") buf.write(u"\3\2\2\2\f\u00d4\3\2\2\2\16\u00d8\3\2\2\2\20\u00dc\3") buf.write(u"\2\2\2\22\u00e0\3\2\2\2\24\u00e4\3\2\2\2\26\u00e8\3\2") buf.write(u"\2\2\30\u00ea\3\2\2\2\32\u00f3\3\2\2\2\34\u00fd\3\2\2") buf.write(u"\2\36\u0106\3\2\2\2 \u0110\3\2\2\2\"\u0119\3\2\2\2$\u0123") buf.write(u"\3\2\2\2&\u012c\3\2\2\2(\u0136\3\2\2\2*\u013f\3\2\2\2") buf.write(u",\u0149\3\2\2\2.\u0152\3\2\2\2\60\u015c\3\2\2\2\62\u0165") buf.write(u"\3\2\2\2\64\u016f\3\2\2\2\66\u0178\3\2\2\28\u0182\3\2") buf.write(u"\2\2:\u0199\3\2\2\2<\u019d\3\2\2\2>\u01a1\3\2\2\2@\u01a5") buf.write(u"\3\2\2\2B\u01a8\3\2\2\2D\u01ac\3\2\2\2F\u01af\3\2\2\2") buf.write(u"H\u01b2\3\2\2\2J\u01b5\3\2\2\2L\u01ca\3\2\2\2N\u01ce") buf.write(u"\3\2\2\2P\u01d1\3\2\2\2R\u01d4\3\2\2\2T\u01e8\3\2\2\2") buf.write(u"V\u01ec\3\2\2\2X\u01f0\3\2\2\2Z\u01f4\3\2\2\2\\\u01f7") buf.write(u"\3\2\2\2^\u020e\3\2\2\2`\u0212\3\2\2\2b\u0216\3\2\2\2") buf.write(u"d\u021a\3\2\2\2f\u021f\3\2\2\2h\u0223\3\2\2\2j\u0226") buf.write(u"\3\2\2\2l\u0229\3\2\2\2n\u023d\3\2\2\2p\u0241\3\2\2\2") buf.write(u"r\u0244\3\2\2\2t\u0247\3\2\2\2v\u024a\3\2\2\2x\u025d") buf.write(u"\3\2\2\2z\u0261\3\2\2\2|\u0265\3\2\2\2~\u0268\3\2\2\2") buf.write(u"\u0080\u027f\3\2\2\2\u0082\u0283\3\2\2\2\u0084\u0287") buf.write(u"\3\2\2\2\u0086\u028a\3\2\2\2\u0088\u028d\3\2\2\2\u008a") buf.write(u"\u0290\3\2\2\2\u008c\u0293\3\2\2\2\u008e\u0296\3\2\2") buf.write(u"\2\u0090\u02ac\3\2\2\2\u0092\u02b0\3\2\2\2\u0094\u02b4") buf.write(u"\3\2\2\2\u0096\u02b7\3\2\2\2\u0098\u02ba\3\2\2\2\u009a") buf.write(u"\u02bd\3\2\2\2\u009c\u02c0\3\2\2\2\u009e\u02c4\3\2\2") buf.write(u"\2\u00a0\u02c9\3\2\2\2\u00a2\u02d2\3\2\2\2\u00a4\u02d6") buf.write(u"\3\2\2\2\u00a6\u02db\3\2\2\2\u00a8\u02df\3\2\2\2\u00aa") buf.write(u"\u02e5\3\2\2\2\u00ac\u02ea\3\2\2\2\u00ae\u02ed\3\2\2") buf.write(u"\2\u00b0\u02f3\3\2\2\2\u00b2\u02f5\3\2\2\2\u00b4\u02f7") buf.write(u"\3\2\2\2\u00b6\u00b7\7\3\2\2\u00b7\u00b8\5\4\3\2\u00b8") buf.write(u"\u00b9\7\4\2\2\u00b9\u00ba\7\5\2\2\u00ba\u00bb\5\6\4") buf.write(u"\2\u00bb\3\3\2\2\2\u00bc\u00bd\t\2\2\2\u00bd\5\3\2\2") buf.write(u"\2\u00be\u00c7\5\b\5\2\u00bf\u00c7\5\n\6\2\u00c0\u00c7") buf.write(u"\5\f\7\2\u00c1\u00c7\5\16\b\2\u00c2\u00c7\5\20\t\2\u00c3") buf.write(u"\u00c7\5\22\n\2\u00c4\u00c7\5\24\13\2\u00c5\u00c7\5\26") buf.write(u"\f\2\u00c6\u00be\3\2\2\2\u00c6\u00bf\3\2\2\2\u00c6\u00c0") buf.write(u"\3\2\2\2\u00c6\u00c1\3\2\2\2\u00c6\u00c2\3\2\2\2\u00c6") buf.write(u"\u00c3\3\2\2\2\u00c6\u00c4\3\2\2\2\u00c6\u00c5\3\2\2") buf.write(u"\2\u00c7\u00c8\3\2\2\2\u00c8\u00c6\3\2\2\2\u00c8\u00c9") buf.write(u"\3\2\2\2\u00c9\7\3\2\2\2\u00ca\u00cd\5\30\r\2\u00cb\u00cd") buf.write(u"\5\32\16\2\u00cc\u00ca\3\2\2\2\u00cc\u00cb\3\2\2\2\u00cd") buf.write(u"\t\3\2\2\2\u00ce\u00d1\5\34\17\2\u00cf\u00d1\5\36\20") buf.write(u"\2\u00d0\u00ce\3\2\2\2\u00d0\u00cf\3\2\2\2\u00d1\13\3") buf.write(u"\2\2\2\u00d2\u00d5\5 \21\2\u00d3\u00d5\5\"\22\2\u00d4") buf.write(u"\u00d2\3\2\2\2\u00d4\u00d3\3\2\2\2\u00d5\r\3\2\2\2\u00d6") buf.write(u"\u00d9\5$\23\2\u00d7\u00d9\5&\24\2\u00d8\u00d6\3\2\2") buf.write(u"\2\u00d8\u00d7\3\2\2\2\u00d9\17\3\2\2\2\u00da\u00dd\5") buf.write(u"(\25\2\u00db\u00dd\5*\26\2\u00dc\u00da\3\2\2\2\u00dc") buf.write(u"\u00db\3\2\2\2\u00dd\21\3\2\2\2\u00de\u00e1\5,\27\2\u00df") buf.write(u"\u00e1\5.\30\2\u00e0\u00de\3\2\2\2\u00e0\u00df\3\2\2") buf.write(u"\2\u00e1\23\3\2\2\2\u00e2\u00e5\5\60\31\2\u00e3\u00e5") buf.write(u"\5\62\32\2\u00e4\u00e2\3\2\2\2\u00e4\u00e3\3\2\2\2\u00e5") buf.write(u"\25\3\2\2\2\u00e6\u00e9\5\64\33\2\u00e7\u00e9\5\66\34") buf.write(u"\2\u00e8\u00e6\3\2\2\2\u00e8\u00e7\3\2\2\2\u00e9\27\3") buf.write(u"\2\2\2\u00ea\u00eb\7\7\2\2\u00eb\u00ec\7B\2\2\u00ec\u00ed") buf.write(u"\7\b\2\2\u00ed\u00ee\7\t\2\2\u00ee\u00ef\7\n\2\2\u00ef") buf.write(u"\u00f0\7\f\2\2\u00f0\u00f1\7\5\2\2\u00f1\u00f2\5:\36") buf.write(u"\2\u00f2\31\3\2\2\2\u00f3\u00f4\7\7\2\2\u00f4\u00f5\7") buf.write(u"B\2\2\u00f5\u00f6\7\b\2\2\u00f6\u00f7\7\t\2\2\u00f7\u00f8") buf.write(u"\7\13\2\2\u00f8\u00f9\7\f\2\2\u00f9\u00fa\58\35\2\u00fa") buf.write(u"\u00fb\7\5\2\2\u00fb\u00fc\5:\36\2\u00fc\33\3\2\2\2\u00fd") buf.write(u"\u00fe\7\7\2\2\u00fe\u00ff\7C\2\2\u00ff\u0100\7\b\2\2") buf.write(u"\u0100\u0101\7\t\2\2\u0101\u0102\7\n\2\2\u0102\u0103") buf.write(u"\7\f\2\2\u0103\u0104\7\5\2\2\u0104\u0105\5L\'\2\u0105") buf.write(u"\35\3\2\2\2\u0106\u0107\7\7\2\2\u0107\u0108\7C\2\2\u0108") buf.write(u"\u0109\7\b\2\2\u0109\u010a\7\t\2\2\u010a\u010b\7\13\2") buf.write(u"\2\u010b\u010c\7\f\2\2\u010c\u010d\58\35\2\u010d\u010e") buf.write(u"\7\5\2\2\u010e\u010f\5L\'\2\u010f\37\3\2\2\2\u0110\u0111") buf.write(u"\7\7\2\2\u0111\u0112\7D\2\2\u0112\u0113\7\b\2\2\u0113") buf.write(u"\u0114\7\t\2\2\u0114\u0115\7\n\2\2\u0115\u0116\7\f\2") buf.write(u"\2\u0116\u0117\7\5\2\2\u0117\u0118\5T+\2\u0118!\3\2\2") buf.write(u"\2\u0119\u011a\7\7\2\2\u011a\u011b\7D\2\2\u011b\u011c") buf.write(u"\7\b\2\2\u011c\u011d\7\t\2\2\u011d\u011e\7\13\2\2\u011e") buf.write(u"\u011f\7\f\2\2\u011f\u0120\58\35\2\u0120\u0121\7\5\2") buf.write(u"\2\u0121\u0122\5T+\2\u0122#\3\2\2\2\u0123\u0124\7\7\2") buf.write(u"\2\u0124\u0125\7E\2\2\u0125\u0126\7\b\2\2\u0126\u0127") buf.write(u"\7\t\2\2\u0127\u0128\7\n\2\2\u0128\u0129\7\f\2\2\u0129") buf.write(u"\u012a\7\5\2\2\u012a\u012b\5^\60\2\u012b%\3\2\2\2\u012c") buf.write(u"\u012d\7\7\2\2\u012d\u012e\7E\2\2\u012e\u012f\7\b\2\2") buf.write(u"\u012f\u0130\7\t\2\2\u0130\u0131\7\13\2\2\u0131\u0132") buf.write(u"\7\f\2\2\u0132\u0133\58\35\2\u0133\u0134\7\5\2\2\u0134") buf.write(u"\u0135\5^\60\2\u0135\'\3\2\2\2\u0136\u0137\7\7\2\2\u0137") buf.write(u"\u0138\7F\2\2\u0138\u0139\7\b\2\2\u0139\u013a\7\t\2\2") buf.write(u"\u013a\u013b\7\n\2\2\u013b\u013c\7\f\2\2\u013c\u013d") buf.write(u"\7\5\2\2\u013d\u013e\5n8\2\u013e)\3\2\2\2\u013f\u0140") buf.write(u"\7\7\2\2\u0140\u0141\7F\2\2\u0141\u0142\7\b\2\2\u0142") buf.write(u"\u0143\7\t\2\2\u0143\u0144\7\13\2\2\u0144\u0145\7\f\2") buf.write(u"\2\u0145\u0146\58\35\2\u0146\u0147\7\5\2\2\u0147\u0148") buf.write(u"\5n8\2\u0148+\3\2\2\2\u0149\u014a\7\7\2\2\u014a\u014b") buf.write(u"\7G\2\2\u014b\u014c\7\b\2\2\u014c\u014d\7\t\2\2\u014d") buf.write(u"\u014e\7\n\2\2\u014e\u014f\7\f\2\2\u014f\u0150\7\5\2") buf.write(u"\2\u0150\u0151\5x=\2\u0151-\3\2\2\2\u0152\u0153\7\7\2") buf.write(u"\2\u0153\u0154\7G\2\2\u0154\u0155\7\b\2\2\u0155\u0156") buf.write(u"\7\t\2\2\u0156\u0157\7\13\2\2\u0157\u0158\7\f\2\2\u0158") buf.write(u"\u0159\58\35\2\u0159\u015a\7\5\2\2\u015a\u015b\5x=\2") buf.write(u"\u015b/\3\2\2\2\u015c\u015d\7\7\2\2\u015d\u015e\7H\2") buf.write(u"\2\u015e\u015f\7\b\2\2\u015f\u0160\7\t\2\2\u0160\u0161") buf.write(u"\7\n\2\2\u0161\u0162\7\f\2\2\u0162\u0163\7\5\2\2\u0163") buf.write(u"\u0164\5\u0080A\2\u0164\61\3\2\2\2\u0165\u0166\7\7\2") buf.write(u"\2\u0166\u0167\7H\2\2\u0167\u0168\7\b\2\2\u0168\u0169") buf.write(u"\7\t\2\2\u0169\u016a\7\13\2\2\u016a\u016b\7\f\2\2\u016b") buf.write(u"\u016c\58\35\2\u016c\u016d\7\5\2\2\u016d\u016e\5\u0080") buf.write(u"A\2\u016e\63\3\2\2\2\u016f\u0170\7\7\2\2\u0170\u0171") buf.write(u"\7I\2\2\u0171\u0172\7\b\2\2\u0172\u0173\7\t\2\2\u0173") buf.write(u"\u0174\7\n\2\2\u0174\u0175\7\f\2\2\u0175\u0176\7\5\2") buf.write(u"\2\u0176\u0177\5\u0090I\2\u0177\65\3\2\2\2\u0178\u0179") buf.write(u"\7\7\2\2\u0179\u017a\7I\2\2\u017a\u017b\7\b\2\2\u017b") buf.write(u"\u017c\7\t\2\2\u017c\u017d\7\13\2\2\u017d\u017e\7\f\2") buf.write(u"\2\u017e\u017f\58\35\2\u017f\u0180\7\5\2\2\u0180\u0181") buf.write(u"\5\u0090I\2\u0181\67\3\2\2\2\u0182\u0183\t\3\2\2\u0183") buf.write(u"9\3\2\2\2\u0184\u0196\5<\37\2\u0185\u0196\5> \2\u0186") buf.write(u"\u0196\5@!\2\u0187\u0196\5B\"\2\u0188\u0196\5D#\2\u0189") buf.write(u"\u0196\5F$\2\u018a\u0196\5H%\2\u018b\u0196\5J&\2\u018c") buf.write(u"\u0196\5\u009cO\2\u018d\u0196\5\u009eP\2\u018e\u0196") buf.write(u"\5\u00a0Q\2\u018f\u0196\5\u00a2R\2\u0190\u0196\5\u00a4") buf.write(u"S\2\u0191\u0196\5\u00a6T\2\u0192\u0196\5\u00aeX\2\u0193") buf.write(u"\u0196\5\u00a8U\2\u0194\u0196\5\u00aaV\2\u0195\u0184") buf.write(u"\3\2\2\2\u0195\u0185\3\2\2\2\u0195\u0186\3\2\2\2\u0195") buf.write(u"\u0187\3\2\2\2\u0195\u0188\3\2\2\2\u0195\u0189\3\2\2") buf.write(u"\2\u0195\u018a\3\2\2\2\u0195\u018b\3\2\2\2\u0195\u018c") buf.write(u"\3\2\2\2\u0195\u018d\3\2\2\2\u0195\u018e\3\2\2\2\u0195") buf.write(u"\u018f\3\2\2\2\u0195\u0190\3\2\2\2\u0195\u0191\3\2\2") buf.write(u"\2\u0195\u0192\3\2\2\2\u0195\u0193\3\2\2\2\u0195\u0194") buf.write(u"\3\2\2\2\u0196\u0197\3\2\2\2\u0197\u0198\7\6\2\2\u0198") buf.write(u"\u019a\3\2\2\2\u0199\u0195\3\2\2\2\u019a\u019b\3\2\2") buf.write(u"\2\u019b\u0199\3\2\2\2\u019b\u019c\3\2\2\2\u019c;\3\2") buf.write(u"\2\2\u019d\u019e\7$\2\2\u019e\u019f\7%\2\2\u019f\u01a0") buf.write(u"\7J\2\2\u01a0=\3\2\2\2\u01a1\u01a2\7#\2\2\u01a2\u01a3") buf.write(u"\7\25\2\2\u01a3\u01a4\7M\2\2\u01a4?\3\2\2\2\u01a5\u01a6") buf.write(u"\7#\2\2\u01a6\u01a7\7\27\2\2\u01a7A\3\2\2\2\u01a8\u01a9") buf.write(u"\7\20\2\2\u01a9\u01aa\7\25\2\2\u01aa\u01ab\7M\2\2\u01ab") buf.write(u"C\3\2\2\2\u01ac\u01ad\7\23\2\2\u01ad\u01ae\7\24\2\2\u01ae") buf.write(u"E\3\2\2\2\u01af\u01b0\7\34\2\2\u01b0\u01b1\7\35\2\2\u01b1") buf.write(u"G\3\2\2\2\u01b2\u01b3\7\34\2\2\u01b3\u01b4\7\36\2\2\u01b4") buf.write(u"I\3\2\2\2\u01b5\u01b6\7\62\2\2\u01b6\u01b7\7\63\2\2\u01b7") buf.write(u"\u01b8\7\64\2\2\u01b8\u01b9\7M\2\2\u01b9K\3\2\2\2\u01ba") buf.write(u"\u01c7\5N(\2\u01bb\u01c7\5P)\2\u01bc\u01c7\5R*\2\u01bd") buf.write(u"\u01c7\5\u009cO\2\u01be\u01c7\5\u009eP\2\u01bf\u01c7") buf.write(u"\5\u00a0Q\2\u01c0\u01c7\5\u00a2R\2\u01c1\u01c7\5\u00a4") buf.write(u"S\2\u01c2\u01c7\5\u00a6T\2\u01c3\u01c7\5\u00aeX\2\u01c4") buf.write(u"\u01c7\5\u00a8U\2\u01c5\u01c7\5\u00aaV\2\u01c6\u01ba") buf.write(u"\3\2\2\2\u01c6\u01bb\3\2\2\2\u01c6\u01bc\3\2\2\2\u01c6") buf.write(u"\u01bd\3\2\2\2\u01c6\u01be\3\2\2\2\u01c6\u01bf\3\2\2") buf.write(u"\2\u01c6\u01c0\3\2\2\2\u01c6\u01c1\3\2\2\2\u01c6\u01c2") buf.write(u"\3\2\2\2\u01c6\u01c3\3\2\2\2\u01c6\u01c4\3\2\2\2\u01c6") buf.write(u"\u01c5\3\2\2\2\u01c7\u01c8\3\2\2\2\u01c8\u01c9\7\6\2") buf.write(u"\2\u01c9\u01cb\3\2\2\2\u01ca\u01c6\3\2\2\2\u01cb\u01cc") buf.write(u"\3\2\2\2\u01cc\u01ca\3\2\2\2\u01cc\u01cd\3\2\2\2\u01cd") buf.write(u"M\3\2\2\2\u01ce\u01cf\7\20\2\2\u01cf\u01d0\7\22\2\2\u01d0") buf.write(u"O\3\2\2\2\u01d1\u01d2\7\20\2\2\u01d2\u01d3\7C\2\2\u01d3") buf.write(u"Q\3\2\2\2\u01d4\u01d5\7\23\2\2\u01d5\u01d6\7\24\2\2\u01d6") buf.write(u"S\3\2\2\2\u01d7\u01e5\5V,\2\u01d8\u01e5\5X-\2\u01d9\u01e5") buf.write(u"\5Z.\2\u01da\u01e5\5\\/\2\u01db\u01e5\5\u009cO\2\u01dc") buf.write(u"\u01e5\5\u009eP\2\u01dd\u01e5\5\u00a0Q\2\u01de\u01e5") buf.write(u"\5\u00a2R\2\u01df\u01e5\5\u00a4S\2\u01e0\u01e5\5\u00a6") buf.write(u"T\2\u01e1\u01e5\5\u00aeX\2\u01e2\u01e5\5\u00a8U\2\u01e3") buf.write(u"\u01e5\5\u00aaV\2\u01e4\u01d7\3\2\2\2\u01e4\u01d8\3\2") buf.write(u"\2\2\u01e4\u01d9\3\2\2\2\u01e4\u01da\3\2\2\2\u01e4\u01db") buf.write(u"\3\2\2\2\u01e4\u01dc\3\2\2\2\u01e4\u01dd\3\2\2\2\u01e4") buf.write(u"\u01de\3\2\2\2\u01e4\u01df\3\2\2\2\u01e4\u01e0\3\2\2") buf.write(u"\2\u01e4\u01e1\3\2\2\2\u01e4\u01e2\3\2\2\2\u01e4\u01e3") buf.write(u"\3\2\2\2\u01e5\u01e6\3\2\2\2\u01e6\u01e7\7\6\2\2\u01e7") buf.write(u"\u01e9\3\2\2\2\u01e8\u01e4\3\2\2\2\u01e9\u01ea\3\2\2") buf.write(u"\2\u01ea\u01e8\3\2\2\2\u01ea\u01eb\3\2\2\2\u01ebU\3\2") buf.write(u"\2\2\u01ec\u01ed\7\r\2\2\u01ed\u01ee\7\16\2\2\u01ee\u01ef") buf.write(u"\7J\2\2\u01efW\3\2\2\2\u01f0\u01f1\7\r\2\2\u01f1\u01f2") buf.write(u"\7\17\2\2\u01f2\u01f3\7J\2\2\u01f3Y\3\2\2\2\u01f4\u01f5") buf.write(u"\7\20\2\2\u01f5\u01f6\7\21\2\2\u01f6[\3\2\2\2\u01f7\u01f8") buf.write(u"\7\66\2\2\u01f8\u01f9\7\67\2\2\u01f9]\3\2\2\2\u01fa\u020b") buf.write(u"\5`\61\2\u01fb\u020b\5b\62\2\u01fc\u020b\5d\63\2\u01fd") buf.write(u"\u020b\5f\64\2\u01fe\u020b\5h\65\2\u01ff\u020b\5j\66") buf.write(u"\2\u0200\u020b\5l\67\2\u0201\u020b\5\u009cO\2\u0202\u020b") buf.write(u"\5\u009eP\2\u0203\u020b\5\u00a0Q\2\u0204\u020b\5\u00a2") buf.write(u"R\2\u0205\u020b\5\u00a4S\2\u0206\u020b\5\u00a6T\2\u0207") buf.write(u"\u020b\5\u00aeX\2\u0208\u020b\5\u00a8U\2\u0209\u020b") buf.write(u"\5\u00aaV\2\u020a\u01fa\3\2\2\2\u020a\u01fb\3\2\2\2\u020a") buf.write(u"\u01fc\3\2\2\2\u020a\u01fd\3\2\2\2\u020a\u01fe\3\2\2") buf.write(u"\2\u020a\u01ff\3\2\2\2\u020a\u0200\3\2\2\2\u020a\u0201") buf.write(u"\3\2\2\2\u020a\u0202\3\2\2\2\u020a\u0203\3\2\2\2\u020a") buf.write(u"\u0204\3\2\2\2\u020a\u0205\3\2\2\2\u020a\u0206\3\2\2") buf.write(u"\2\u020a\u0207\3\2\2\2\u020a\u0208\3\2\2\2\u020a\u0209") buf.write(u"\3\2\2\2\u020b\u020c\3\2\2\2\u020c\u020d\7\6\2\2\u020d") buf.write(u"\u020f\3\2\2\2\u020e\u020a\3\2\2\2\u020f\u0210\3\2\2") buf.write(u"\2\u0210\u020e\3\2\2\2\u0210\u0211\3\2\2\2\u0211_\3\2") buf.write(u"\2\2\u0212\u0213\7\20\2\2\u0213\u0214\7\25\2\2\u0214") buf.write(u"\u0215\7M\2\2\u0215a\3\2\2\2\u0216\u0217\7\33\2\2\u0217") buf.write(u"\u0218\7\25\2\2\u0218\u0219\7M\2\2\u0219c\3\2\2\2\u021a") buf.write(u"\u021b\7\26\2\2\u021b\u021c\7\20\2\2\u021c\u021d\7\25") buf.write(u"\2\2\u021d\u021e\7M\2\2\u021ee\3\2\2\2\u021f\u0220\7") buf.write(u"\26\2\2\u0220\u0221\7\20\2\2\u0221\u0222\7\27\2\2\u0222") buf.write(u"g\3\2\2\2\u0223\u0224\7\23\2\2\u0224\u0225\7\24\2\2\u0225") buf.write(u"i\3\2\2\2\u0226\u0227\7\34\2\2\u0227\u0228\7\35\2\2\u0228") buf.write(u"k\3\2\2\2\u0229\u022a\7\34\2\2\u022a\u022b\7\36\2\2\u022b") buf.write(u"m\3\2\2\2\u022c\u023a\5p9\2\u022d\u023a\5r:\2\u022e\u023a") buf.write(u"\5t;\2\u022f\u023a\5v<\2\u0230\u023a\5\u009cO\2\u0231") buf.write(u"\u023a\5\u009eP\2\u0232\u023a\5\u00a0Q\2\u0233\u023a") buf.write(u"\5\u00a2R\2\u0234\u023a\5\u00a4S\2\u0235\u023a\5\u00a6") buf.write(u"T\2\u0236\u023a\5\u00aeX\2\u0237\u023a\5\u00a8U\2\u0238") buf.write(u"\u023a\5\u00aaV\2\u0239\u022c\3\2\2\2\u0239\u022d\3\2") buf.write(u"\2\2\u0239\u022e\3\2\2\2\u0239\u022f\3\2\2\2\u0239\u0230") buf.write(u"\3\2\2\2\u0239\u0231\3\2\2\2\u0239\u0232\3\2\2\2\u0239") buf.write(u"\u0233\3\2\2\2\u0239\u0234\3\2\2\2\u0239\u0235\3\2\2") buf.write(u"\2\u0239\u0236\3\2\2\2\u0239\u0237\3\2\2\2\u0239\u0238") buf.write(u"\3\2\2\2\u023a\u023b\3\2\2\2\u023b\u023c\7\6\2\2\u023c") buf.write(u"\u023e\3\2\2\2\u023d\u0239\3\2\2\2\u023e\u023f\3\2\2") buf.write(u"\2\u023f\u023d\3\2\2\2\u023f\u0240\3\2\2\2\u0240o\3\2") buf.write(u"\2\2\u0241\u0242\7\34\2\2\u0242\u0243\7\35\2\2\u0243") buf.write(u"q\3\2\2\2\u0244\u0245\7\34\2\2\u0245\u0246\7\36\2\2\u0246") buf.write(u"s\3\2\2\2\u0247\u0248\7\34\2\2\u0248\u0249\7\37\2\2\u0249") buf.write(u"u\3\2\2\2\u024a\u024b\7\34\2\2\u024b\u024c\7 \2\2\u024c") buf.write(u"w\3\2\2\2\u024d\u025a\5z>\2\u024e\u025a\5|?\2\u024f\u025a") buf.write(u"\5~@\2\u0250\u025a\5\u009cO\2\u0251\u025a\5\u009eP\2") buf.write(u"\u0252\u025a\5\u00a0Q\2\u0253\u025a\5\u00a2R\2\u0254") buf.write(u"\u025a\5\u00a4S\2\u0255\u025a\5\u00a6T\2\u0256\u025a") buf.write(u"\5\u00aeX\2\u0257\u025a\5\u00a8U\2\u0258\u025a\5\u00aa") buf.write(u"V\2\u0259\u024d\3\2\2\2\u0259\u024e\3\2\2\2\u0259\u024f") buf.write(u"\3\2\2\2\u0259\u0250\3\2\2\2\u0259\u0251\3\2\2\2\u0259") buf.write(u"\u0252\3\2\2\2\u0259\u0253\3\2\2\2\u0259\u0254\3\2\2") buf.write(u"\2\u0259\u0255\3\2\2\2\u0259\u0256\3\2\2\2\u0259\u0257") buf.write(u"\3\2\2\2\u0259\u0258\3\2\2\2\u025a\u025b\3\2\2\2\u025b") buf.write(u"\u025c\7\6\2\2\u025c\u025e\3\2\2\2\u025d\u0259\3\2\2") buf.write(u"\2\u025e\u025f\3\2\2\2\u025f\u025d\3\2\2\2\u025f\u0260") buf.write(u"\3\2\2\2\u0260y\3\2\2\2\u0261\u0262\7\r\2\2\u0262\u0263") buf.write(u"\7\30\2\2\u0263\u0264\7J\2\2\u0264{\3\2\2\2\u0265\u0266") buf.write(u"\7\23\2\2\u0266\u0267\7\31\2\2\u0267}\3\2\2\2\u0268\u0269") buf.write(u"\7\23\2\2\u0269\u026a\7\24\2\2\u026a\177\3\2\2\2\u026b") buf.write(u"\u027c\5\u0082B\2\u026c\u027c\5\u0084C\2\u026d\u027c") buf.write(u"\5\u0086D\2\u026e\u027c\5\u0088E\2\u026f\u027c\5\u008a") buf.write(u"F\2\u0270\u027c\5\u008cG\2\u0271\u027c\5\u008eH\2\u0272") buf.write(u"\u027c\5\u009cO\2\u0273\u027c\5\u009eP\2\u0274\u027c") buf.write(u"\5\u00a0Q\2\u0275\u027c\5\u00a2R\2\u0276\u027c\5\u00a4") buf.write(u"S\2\u0277\u027c\5\u00a6T\2\u0278\u027c\5\u00aeX\2\u0279") buf.write(u"\u027c\5\u00a8U\2\u027a\u027c\5\u00aaV\2\u027b\u026b") buf.write(u"\3\2\2\2\u027b\u026c\3\2\2\2\u027b\u026d\3\2\2\2\u027b") buf.write(u"\u026e\3\2\2\2\u027b\u026f\3\2\2\2\u027b\u0270\3\2\2") buf.write(u"\2\u027b\u0271\3\2\2\2\u027b\u0272\3\2\2\2\u027b\u0273") buf.write(u"\3\2\2\2\u027b\u0274\3\2\2\2\u027b\u0275\3\2\2\2\u027b") buf.write(u"\u0276\3\2\2\2\u027b\u0277\3\2\2\2\u027b\u0278\3\2\2") buf.write(u"\2\u027b\u0279\3\2\2\2\u027b\u027a\3\2\2\2\u027c\u027d") buf.write(u"\3\2\2\2\u027d\u027e\7\6\2\2\u027e\u0280\3\2\2\2\u027f") buf.write(u"\u027b\3\2\2\2\u0280\u0281\3\2\2\2\u0281\u027f\3\2\2") buf.write(u"\2\u0281\u0282\3\2\2\2\u0282\u0081\3\2\2\2\u0283\u0284") buf.write(u"\7\r\2\2\u0284\u0285\7!\2\2\u0285\u0286\7J\2\2\u0286") buf.write(u"\u0083\3\2\2\2\u0287\u0288\7\34\2\2\u0288\u0289\7\35") buf.write(u"\2\2\u0289\u0085\3\2\2\2\u028a\u028b\7\34\2\2\u028b\u028c") buf.write(u"\7\36\2\2\u028c\u0087\3\2\2\2\u028d\u028e\7\34\2\2\u028e") buf.write(u"\u028f\7\37\2\2\u028f\u0089\3\2\2\2\u0290\u0291\7\34") buf.write(u"\2\2\u0291\u0292\7 \2\2\u0292\u008b\3\2\2\2\u0293\u0294") buf.write(u"\7\20\2\2\u0294\u0295\7\"\2\2\u0295\u008d\3\2\2\2\u0296") buf.write(u"\u0297\7\26\2\2\u0297\u0298\7\20\2\2\u0298\u0299\7\"") buf.write(u"\2\2\u0299\u008f\3\2\2\2\u029a\u02a9\5\u0092J\2\u029b") buf.write(u"\u02a9\5\u0094K\2\u029c\u02a9\5\u0096L\2\u029d\u02a9") buf.write(u"\5\u0098M\2\u029e\u02a9\5\u009aN\2\u029f\u02a9\5\u009c") buf.write(u"O\2\u02a0\u02a9\5\u009eP\2\u02a1\u02a9\5\u00a0Q\2\u02a2") buf.write(u"\u02a9\5\u00a2R\2\u02a3\u02a9\5\u00a4S\2\u02a4\u02a9") buf.write(u"\5\u00a6T\2\u02a5\u02a9\5\u00aeX\2\u02a6\u02a9\5\u00a8") buf.write(u"U\2\u02a7\u02a9\5\u00aaV\2\u02a8\u029a\3\2\2\2\u02a8") buf.write(u"\u029b\3\2\2\2\u02a8\u029c\3\2\2\2\u02a8\u029d\3\2\2") buf.write(u"\2\u02a8\u029e\3\2\2\2\u02a8\u029f\3\2\2\2\u02a8\u02a0") buf.write(u"\3\2\2\2\u02a8\u02a1\3\2\2\2\u02a8\u02a2\3\2\2\2\u02a8") buf.write(u"\u02a3\3\2\2\2\u02a8\u02a4\3\2\2\2\u02a8\u02a5\3\2\2") buf.write(u"\2\u02a8\u02a6\3\2\2\2\u02a8\u02a7\3\2\2\2\u02a9\u02aa") buf.write(u"\3\2\2\2\u02aa\u02ab\7\6\2\2\u02ab\u02ad\3\2\2\2\u02ac") buf.write(u"\u02a8\3\2\2\2\u02ad\u02ae\3\2\2\2\u02ae\u02ac\3\2\2") buf.write(u"\2\u02ae\u02af\3\2\2\2\u02af\u0091\3\2\2\2\u02b0\u02b1") buf.write(u"\7\r\2\2\u02b1\u02b2\7\32\2\2\u02b2\u02b3\7J\2\2\u02b3") buf.write(u"\u0093\3\2\2\2\u02b4\u02b5\7\23\2\2\u02b5\u02b6\7\31") buf.write(u"\2\2\u02b6\u0095\3\2\2\2\u02b7\u02b8\7\23\2\2\u02b8\u02b9") buf.write(u"\7\24\2\2\u02b9\u0097\3\2\2\2\u02ba\u02bb\7\34\2\2\u02bb") buf.write(u"\u02bc\7\35\2\2\u02bc\u0099\3\2\2\2\u02bd\u02be\7\34") buf.write(u"\2\2\u02be\u02bf\7\36\2\2\u02bf\u009b\3\2\2\2\u02c0\u02c1") buf.write(u"\7&\2\2\u02c1\u02c2\7\20\2\2\u02c2\u02c3\5\u00acW\2\u02c3") buf.write(u"\u009d\3\2\2\2\u02c4\u02c5\7&\2\2\u02c5\u02c6\7\26\2") buf.write(u"\2\u02c6\u02c7\7\20\2\2\u02c7\u02c8\5\u00acW\2\u02c8") buf.write(u"\u009f\3\2\2\2\u02c9\u02ca\7&\2\2\u02ca\u02cb\7\'\2\2") buf.write(u"\u02cb\u02cc\7(\2\2\u02cc\u02cd\5\u00acW\2\u02cd\u02ce") buf.write(u"\7)\2\2\u02ce\u02cf\5\u00acW\2\u02cf\u02d0\7*\2\2\u02d0") buf.write(u"\u02d1\7M\2\2\u02d1\u00a1\3\2\2\2\u02d2\u02d3\7&\2\2") buf.write(u"\u02d3\u02d4\7+\2\2\u02d4\u02d5\7J\2\2\u02d5\u00a3\3") buf.write(u"\2\2\2\u02d6\u02d7\7&\2\2\u02d7\u02d8\7\23\2\2\u02d8") buf.write(u"\u02d9\7,\2\2\u02d9\u02da\7\24\2\2\u02da\u00a5\3\2\2") buf.write(u"\2\u02db\u02dc\7&\2\2\u02dc\u02dd\7.\2\2\u02dd\u02de") buf.write(u"\7M\2\2\u02de\u00a7\3\2\2\2\u02df\u02e0\7&\2\2\u02e0") buf.write(u"\u02e1\7\62\2\2\u02e1\u02e2\7\65\2\2\u02e2\u02e3\7\64") buf.write(u"\2\2\u02e3\u02e4\7J\2\2\u02e4\u00a9\3\2\2\2\u02e5\u02e6") buf.write(u"\7&\2\2\u02e6\u02e7\7\20\2\2\u02e7\u02e8\7\65\2\2\u02e8") buf.write(u"\u02e9\7J\2\2\u02e9\u00ab\3\2\2\2\u02ea\u02eb\7M\2\2") buf.write(u"\u02eb\u02ec\7M\2\2\u02ec\u00ad\3\2\2\2\u02ed\u02f1\7") buf.write(u"-\2\2\u02ee\u02f2\5\u00b0Y\2\u02ef\u02f2\5\u00b2Z\2\u02f0") buf.write(u"\u02f2\5\u00b4[\2\u02f1\u02ee\3\2\2\2\u02f1\u02ef\3\2") buf.write(u"\2\2\u02f1\u02f0\3\2\2\2\u02f2\u00af\3\2\2\2\u02f3\u02f4") buf.write(u"\7/\2\2\u02f4\u00b1\3\2\2\2\u02f5\u02f6\7\60\2\2\u02f6") buf.write(u"\u00b3\3\2\2\2\u02f7\u02f8\7\61\2\2\u02f8\u00b5\3\2\2") buf.write(u"\2\35\u00c6\u00c8\u00cc\u00d0\u00d4\u00d8\u00dc\u00e0") buf.write(u"\u00e4\u00e8\u0195\u019b\u01c6\u01cc\u01e4\u01ea\u020a") buf.write(u"\u0210\u0239\u023f\u0259\u025f\u027b\u0281\u02a8\u02ae") buf.write(u"\u02f1") return buf.getvalue() class scriptingLanguageParser ( Parser ): grammarFileName = "scriptingLanguage.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ u"<INVALID>", u"<INVALID>", u"<INVALID>", u"':'", u"';'" ] symbolicNames = [ u"<INVALID>", u"WHEN", u"APP", u"COL", u"SEMICOL", u"IN", u"CHECK", u"FOR", u"SAME", u"DIFFERENT", u"STATE", u"INPUT", u"NAME", u"PASSWORD", u"CLICK", u"NEXT", u"CLOSE", u"PRESS", u"BACK", u"LINE", u"LONG", u"ALL", u"URL", u"ENTER", u"MESSAGE", u"TOGGLE", u"SWIPE", u"UP", u"DOWN", u"LEFT", u"RIGHT", u"SEARCH", u"CENTER", u"TICK", u"ADD", u"TASK", u"CUSTOM", u"DRAG", u"FROM", u"TO", u"DURATION", u"TYPE", u"DEVICE", u"EXECUTE", u"SLEEP", u"TESTSLOT1", u"TESTSLOT2", u"TESTSLOT3", u"ASSERT", u"LINECOUNT", u"EQUALS", u"TEXT", u"CLEAR", u"FIELDS", u"APPCAT1", u"APPCAT2", u"APPCAT3", u"APPCAT4", u"APPCAT5", u"APPCAT6", u"APPCAT7", u"APPCAT8", u"APPCAT9", u"APPCAT10", u"ACTTYPE1", u"ACTTYPE2", u"ACTTYPE3", u"ACTTYPE4", u"ACTTYPE5", u"ACTTYPE6", u"ACTTYPE7", u"ACTTYPE8", u"QUOTEDSTRING", u"WHITESPACE", u"NEWLINE", u"NUMBER" ] RULE_suite = 0 RULE_apptype = 1 RULE_testlist = 2 RULE_testtype1 = 3 RULE_testtype2 = 4 RULE_testtype3 = 5 RULE_testtype4 = 6 RULE_testtype5 = 7 RULE_testtype6 = 8 RULE_testtype7 = 9 RULE_testtype8 = 10 RULE_testsame1 = 11 RULE_testdiff1 = 12 RULE_testsame2 = 13 RULE_testdiff2 = 14 RULE_testsame3 = 15 RULE_testdiff3 = 16 RULE_testsame4 = 17 RULE_testdiff4 = 18 RULE_testsame5 = 19 RULE_testdiff5 = 20 RULE_testsame6 = 21 RULE_testdiff6 = 22 RULE_testsame7 = 23 RULE_testdiff7 = 24 RULE_testsame8 = 25 RULE_testdiff8 = 26 RULE_activitytype = 27 RULE_commandlist1 = 28 RULE_command1ver1 = 29 RULE_command1ver2 = 30 RULE_command1ver3 = 31 RULE_command1ver4 = 32 RULE_command1ver5 = 33 RULE_command1ver6 = 34 RULE_command1ver7 = 35 RULE_command1ver8 = 36 RULE_commandlist2 = 37 RULE_command2ver1 = 38 RULE_command2ver2 = 39 RULE_command2ver3 = 40 RULE_commandlist3 = 41 RULE_command3ver1 = 42 RULE_command3ver2 = 43 RULE_command3ver3 = 44 RULE_command3ver4 = 45 RULE_commandlist4 = 46 RULE_command4ver1 = 47 RULE_command4ver2 = 48 RULE_command4ver3 = 49 RULE_command4ver4 = 50 RULE_command4ver5 = 51 RULE_command4ver6 = 52 RULE_command4ver7 = 53 RULE_commandlist5 = 54 RULE_command5ver1 = 55 RULE_command5ver2 = 56 RULE_command5ver3 = 57 RULE_command5ver4 = 58 RULE_commandlist6 = 59 RULE_command6ver1 = 60 RULE_command6ver2 = 61 RULE_command6ver3 = 62 RULE_commandlist7 = 63 RULE_command7ver1 = 64 RULE_command7ver2 = 65 RULE_command7ver3 = 66 RULE_command7ver4 = 67 RULE_command7ver5 = 68 RULE_command7ver6 = 69 RULE_command7ver7 = 70 RULE_commandlist8 = 71 RULE_command8ver1 = 72 RULE_command8ver2 = 73 RULE_command8ver3 = 74 RULE_command8ver4 = 75 RULE_command8ver5 = 76 RULE_commandCustomClick = 77 RULE_commandCustomLongClick = 78 RULE_commandCustomDrag = 79 RULE_commandCustomType = 80 RULE_commandCustomBack = 81 RULE_commandCustomSleep = 82 RULE_commandCustomAssertText = 83 RULE_commandCustomClickText = 84 RULE_coordinate = 85 RULE_testCustom = 86 RULE_testSlot1 = 87 RULE_testSlot2 = 88 RULE_testSlot3 = 89 ruleNames = [ u"suite", u"apptype", u"testlist", u"testtype1", u"testtype2", u"testtype3", u"testtype4", u"testtype5", u"testtype6", u"testtype7", u"testtype8", u"testsame1", u"testdiff1", u"testsame2", u"testdiff2", u"testsame3", u"testdiff3", u"testsame4", u"testdiff4", u"testsame5", u"testdiff5", u"testsame6", u"testdiff6", u"testsame7", u"testdiff7", u"testsame8", u"testdiff8", u"activitytype", u"commandlist1", u"command1ver1", u"command1ver2", u"command1ver3", u"command1ver4", u"command1ver5", u"command1ver6", u"command1ver7", u"command1ver8", u"commandlist2", u"command2ver1", u"command2ver2", u"command2ver3", u"commandlist3", u"command3ver1", u"command3ver2", u"command3ver3", u"command3ver4", u"commandlist4", u"command4ver1", u"command4ver2", u"command4ver3", u"command4ver4", u"command4ver5", u"command4ver6", u"command4ver7", u"commandlist5", u"command5ver1", u"command5ver2", u"command5ver3", u"command5ver4", u"commandlist6", u"command6ver1", u"command6ver2", u"command6ver3", u"commandlist7", u"command7ver1", u"command7ver2", u"command7ver3", u"command7ver4", u"command7ver5", u"command7ver6", u"command7ver7", u"commandlist8", u"command8ver1", u"command8ver2", u"command8ver3", u"command8ver4", u"command8ver5", u"commandCustomClick", u"commandCustomLongClick", u"commandCustomDrag", u"commandCustomType", u"commandCustomBack", u"commandCustomSleep", u"commandCustomAssertText", u"commandCustomClickText", u"coordinate", u"testCustom", u"testSlot1", u"testSlot2", u"testSlot3" ] EOF = Token.EOF WHEN=1 APP=2 COL=3 SEMICOL=4 IN=5 CHECK=6 FOR=7 SAME=8 DIFFERENT=9 STATE=10 INPUT=11 NAME=12 PASSWORD=13 CLICK=14 NEXT=15 CLOSE=16 PRESS=17 BACK=18 LINE=19 LONG=20 ALL=21 URL=22 ENTER=23 MESSAGE=24 TOGGLE=25 SWIPE=26 UP=27 DOWN=28 LEFT=29 RIGHT=30 SEARCH=31 CENTER=32 TICK=33 ADD=34 TASK=35 CUSTOM=36 DRAG=37 FROM=38 TO=39 DURATION=40 TYPE=41 DEVICE=42 EXECUTE=43 SLEEP=44 TESTSLOT1=45 TESTSLOT2=46 TESTSLOT3=47 ASSERT=48 LINECOUNT=49 EQUALS=50 TEXT=51 CLEAR=52 FIELDS=53 APPCAT1=54 APPCAT2=55 APPCAT3=56 APPCAT4=57 APPCAT5=58 APPCAT6=59 APPCAT7=60 APPCAT8=61 APPCAT9=62 APPCAT10=63 ACTTYPE1=64 ACTTYPE2=65 ACTTYPE3=66 ACTTYPE4=67 ACTTYPE5=68 ACTTYPE6=69 ACTTYPE7=70 ACTTYPE8=71 QUOTEDSTRING=72 WHITESPACE=73 NEWLINE=74 NUMBER=75 def __init__(self, input, output=sys.stdout): super(scriptingLanguageParser, self).__init__(input, output=output) self.checkVersion("4.7.1") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class SuiteContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.SuiteContext, self).__init__(parent, invokingState) self.parser = parser def WHEN(self): return self.getToken(scriptingLanguageParser.WHEN, 0) def apptype(self): return self.getTypedRuleContext(scriptingLanguageParser.ApptypeContext,0) def APP(self): return self.getToken(scriptingLanguageParser.APP, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def testlist(self): return self.getTypedRuleContext(scriptingLanguageParser.TestlistContext,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_suite def enterRule(self, listener): if hasattr(listener, "enterSuite"): listener.enterSuite(self) def exitRule(self, listener): if hasattr(listener, "exitSuite"): listener.exitSuite(self) def suite(self): localctx = scriptingLanguageParser.SuiteContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_suite) try: self.enterOuterAlt(localctx, 1) self.state = 180 self.match(scriptingLanguageParser.WHEN) self.state = 181 self.apptype() self.state = 182 self.match(scriptingLanguageParser.APP) self.state = 183 self.match(scriptingLanguageParser.COL) self.state = 184 self.testlist() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ApptypeContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.ApptypeContext, self).__init__(parent, invokingState) self.parser = parser def APPCAT1(self): return self.getToken(scriptingLanguageParser.APPCAT1, 0) def APPCAT2(self): return self.getToken(scriptingLanguageParser.APPCAT2, 0) def APPCAT3(self): return self.getToken(scriptingLanguageParser.APPCAT3, 0) def APPCAT4(self): return self.getToken(scriptingLanguageParser.APPCAT4, 0) def APPCAT5(self): return self.getToken(scriptingLanguageParser.APPCAT5, 0) def APPCAT6(self): return self.getToken(scriptingLanguageParser.APPCAT6, 0) def APPCAT7(self): return self.getToken(scriptingLanguageParser.APPCAT7, 0) def APPCAT8(self): return self.getToken(scriptingLanguageParser.APPCAT8, 0) def APPCAT9(self): return self.getToken(scriptingLanguageParser.APPCAT9, 0) def APPCAT10(self): return self.getToken(scriptingLanguageParser.APPCAT10, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_apptype def enterRule(self, listener): if hasattr(listener, "enterApptype"): listener.enterApptype(self) def exitRule(self, listener): if hasattr(listener, "exitApptype"): listener.exitApptype(self) def apptype(self): localctx = scriptingLanguageParser.ApptypeContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_apptype) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 186 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.APPCAT1) | (1 << scriptingLanguageParser.APPCAT2) | (1 << scriptingLanguageParser.APPCAT3) | (1 << scriptingLanguageParser.APPCAT4) | (1 << scriptingLanguageParser.APPCAT5) | (1 << scriptingLanguageParser.APPCAT6) | (1 << scriptingLanguageParser.APPCAT7) | (1 << scriptingLanguageParser.APPCAT8) | (1 << scriptingLanguageParser.APPCAT9) | (1 << scriptingLanguageParser.APPCAT10))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TestlistContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.TestlistContext, self).__init__(parent, invokingState) self.parser = parser def testtype1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype1Context,i) def testtype2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype2Context,i) def testtype3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype3Context,i) def testtype4(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype4Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype4Context,i) def testtype5(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype5Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype5Context,i) def testtype6(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype6Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype6Context,i) def testtype7(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype7Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype7Context,i) def testtype8(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Testtype8Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Testtype8Context,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_testlist def enterRule(self, listener): if hasattr(listener, "enterTestlist"): listener.enterTestlist(self) def exitRule(self, listener): if hasattr(listener, "exitTestlist"): listener.exitTestlist(self) def testlist(self): localctx = scriptingLanguageParser.TestlistContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_testlist) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 196 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 196 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,0,self._ctx) if la_ == 1: self.state = 188 self.testtype1() pass elif la_ == 2: self.state = 189 self.testtype2() pass elif la_ == 3: self.state = 190 self.testtype3() pass elif la_ == 4: self.state = 191 self.testtype4() pass elif la_ == 5: self.state = 192 self.testtype5() pass elif la_ == 6: self.state = 193 self.testtype6() pass elif la_ == 7: self.state = 194 self.testtype7() pass elif la_ == 8: self.state = 195 self.testtype8() pass self.state = 198 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==scriptingLanguageParser.IN): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype1Context, self).__init__(parent, invokingState) self.parser = parser def testsame1(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame1Context,0) def testdiff1(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff1Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype1 def enterRule(self, listener): if hasattr(listener, "enterTesttype1"): listener.enterTesttype1(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype1"): listener.exitTesttype1(self) def testtype1(self): localctx = scriptingLanguageParser.Testtype1Context(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_testtype1) try: self.enterOuterAlt(localctx, 1) self.state = 202 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,2,self._ctx) if la_ == 1: self.state = 200 self.testsame1() pass elif la_ == 2: self.state = 201 self.testdiff1() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype2Context, self).__init__(parent, invokingState) self.parser = parser def testsame2(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame2Context,0) def testdiff2(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff2Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype2 def enterRule(self, listener): if hasattr(listener, "enterTesttype2"): listener.enterTesttype2(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype2"): listener.exitTesttype2(self) def testtype2(self): localctx = scriptingLanguageParser.Testtype2Context(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_testtype2) try: self.enterOuterAlt(localctx, 1) self.state = 206 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,3,self._ctx) if la_ == 1: self.state = 204 self.testsame2() pass elif la_ == 2: self.state = 205 self.testdiff2() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype3Context, self).__init__(parent, invokingState) self.parser = parser def testsame3(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame3Context,0) def testdiff3(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff3Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype3 def enterRule(self, listener): if hasattr(listener, "enterTesttype3"): listener.enterTesttype3(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype3"): listener.exitTesttype3(self) def testtype3(self): localctx = scriptingLanguageParser.Testtype3Context(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_testtype3) try: self.enterOuterAlt(localctx, 1) self.state = 210 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,4,self._ctx) if la_ == 1: self.state = 208 self.testsame3() pass elif la_ == 2: self.state = 209 self.testdiff3() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype4Context, self).__init__(parent, invokingState) self.parser = parser def testsame4(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame4Context,0) def testdiff4(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff4Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype4 def enterRule(self, listener): if hasattr(listener, "enterTesttype4"): listener.enterTesttype4(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype4"): listener.exitTesttype4(self) def testtype4(self): localctx = scriptingLanguageParser.Testtype4Context(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_testtype4) try: self.enterOuterAlt(localctx, 1) self.state = 214 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,5,self._ctx) if la_ == 1: self.state = 212 self.testsame4() pass elif la_ == 2: self.state = 213 self.testdiff4() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype5Context, self).__init__(parent, invokingState) self.parser = parser def testsame5(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame5Context,0) def testdiff5(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff5Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype5 def enterRule(self, listener): if hasattr(listener, "enterTesttype5"): listener.enterTesttype5(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype5"): listener.exitTesttype5(self) def testtype5(self): localctx = scriptingLanguageParser.Testtype5Context(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_testtype5) try: self.enterOuterAlt(localctx, 1) self.state = 218 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,6,self._ctx) if la_ == 1: self.state = 216 self.testsame5() pass elif la_ == 2: self.state = 217 self.testdiff5() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype6Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype6Context, self).__init__(parent, invokingState) self.parser = parser def testsame6(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame6Context,0) def testdiff6(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff6Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype6 def enterRule(self, listener): if hasattr(listener, "enterTesttype6"): listener.enterTesttype6(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype6"): listener.exitTesttype6(self) def testtype6(self): localctx = scriptingLanguageParser.Testtype6Context(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_testtype6) try: self.enterOuterAlt(localctx, 1) self.state = 222 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,7,self._ctx) if la_ == 1: self.state = 220 self.testsame6() pass elif la_ == 2: self.state = 221 self.testdiff6() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype7Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype7Context, self).__init__(parent, invokingState) self.parser = parser def testsame7(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame7Context,0) def testdiff7(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff7Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype7 def enterRule(self, listener): if hasattr(listener, "enterTesttype7"): listener.enterTesttype7(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype7"): listener.exitTesttype7(self) def testtype7(self): localctx = scriptingLanguageParser.Testtype7Context(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_testtype7) try: self.enterOuterAlt(localctx, 1) self.state = 226 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,8,self._ctx) if la_ == 1: self.state = 224 self.testsame7() pass elif la_ == 2: self.state = 225 self.testdiff7() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testtype8Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testtype8Context, self).__init__(parent, invokingState) self.parser = parser def testsame8(self): return self.getTypedRuleContext(scriptingLanguageParser.Testsame8Context,0) def testdiff8(self): return self.getTypedRuleContext(scriptingLanguageParser.Testdiff8Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testtype8 def enterRule(self, listener): if hasattr(listener, "enterTesttype8"): listener.enterTesttype8(self) def exitRule(self, listener): if hasattr(listener, "exitTesttype8"): listener.exitTesttype8(self) def testtype8(self): localctx = scriptingLanguageParser.Testtype8Context(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_testtype8) try: self.enterOuterAlt(localctx, 1) self.state = 230 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,9,self._ctx) if la_ == 1: self.state = 228 self.testsame8() pass elif la_ == 2: self.state = 229 self.testdiff8() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame1Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE1(self): return self.getToken(scriptingLanguageParser.ACTTYPE1, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist1(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist1Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame1 def enterRule(self, listener): if hasattr(listener, "enterTestsame1"): listener.enterTestsame1(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame1"): listener.exitTestsame1(self) def testsame1(self): localctx = scriptingLanguageParser.Testsame1Context(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_testsame1) try: self.enterOuterAlt(localctx, 1) self.state = 232 self.match(scriptingLanguageParser.IN) self.state = 233 self.match(scriptingLanguageParser.ACTTYPE1) self.state = 234 self.match(scriptingLanguageParser.CHECK) self.state = 235 self.match(scriptingLanguageParser.FOR) self.state = 236 self.match(scriptingLanguageParser.SAME) self.state = 237 self.match(scriptingLanguageParser.STATE) self.state = 238 self.match(scriptingLanguageParser.COL) self.state = 239 self.commandlist1() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff1Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE1(self): return self.getToken(scriptingLanguageParser.ACTTYPE1, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist1(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist1Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff1 def enterRule(self, listener): if hasattr(listener, "enterTestdiff1"): listener.enterTestdiff1(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff1"): listener.exitTestdiff1(self) def testdiff1(self): localctx = scriptingLanguageParser.Testdiff1Context(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_testdiff1) try: self.enterOuterAlt(localctx, 1) self.state = 241 self.match(scriptingLanguageParser.IN) self.state = 242 self.match(scriptingLanguageParser.ACTTYPE1) self.state = 243 self.match(scriptingLanguageParser.CHECK) self.state = 244 self.match(scriptingLanguageParser.FOR) self.state = 245 self.match(scriptingLanguageParser.DIFFERENT) self.state = 246 self.match(scriptingLanguageParser.STATE) self.state = 247 self.activitytype() self.state = 248 self.match(scriptingLanguageParser.COL) self.state = 249 self.commandlist1() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame2Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE2(self): return self.getToken(scriptingLanguageParser.ACTTYPE2, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist2(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist2Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame2 def enterRule(self, listener): if hasattr(listener, "enterTestsame2"): listener.enterTestsame2(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame2"): listener.exitTestsame2(self) def testsame2(self): localctx = scriptingLanguageParser.Testsame2Context(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_testsame2) try: self.enterOuterAlt(localctx, 1) self.state = 251 self.match(scriptingLanguageParser.IN) self.state = 252 self.match(scriptingLanguageParser.ACTTYPE2) self.state = 253 self.match(scriptingLanguageParser.CHECK) self.state = 254 self.match(scriptingLanguageParser.FOR) self.state = 255 self.match(scriptingLanguageParser.SAME) self.state = 256 self.match(scriptingLanguageParser.STATE) self.state = 257 self.match(scriptingLanguageParser.COL) self.state = 258 self.commandlist2() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff2Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE2(self): return self.getToken(scriptingLanguageParser.ACTTYPE2, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist2(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist2Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff2 def enterRule(self, listener): if hasattr(listener, "enterTestdiff2"): listener.enterTestdiff2(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff2"): listener.exitTestdiff2(self) def testdiff2(self): localctx = scriptingLanguageParser.Testdiff2Context(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_testdiff2) try: self.enterOuterAlt(localctx, 1) self.state = 260 self.match(scriptingLanguageParser.IN) self.state = 261 self.match(scriptingLanguageParser.ACTTYPE2) self.state = 262 self.match(scriptingLanguageParser.CHECK) self.state = 263 self.match(scriptingLanguageParser.FOR) self.state = 264 self.match(scriptingLanguageParser.DIFFERENT) self.state = 265 self.match(scriptingLanguageParser.STATE) self.state = 266 self.activitytype() self.state = 267 self.match(scriptingLanguageParser.COL) self.state = 268 self.commandlist2() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame3Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE3(self): return self.getToken(scriptingLanguageParser.ACTTYPE3, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist3(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist3Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame3 def enterRule(self, listener): if hasattr(listener, "enterTestsame3"): listener.enterTestsame3(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame3"): listener.exitTestsame3(self) def testsame3(self): localctx = scriptingLanguageParser.Testsame3Context(self, self._ctx, self.state) self.enterRule(localctx, 30, self.RULE_testsame3) try: self.enterOuterAlt(localctx, 1) self.state = 270 self.match(scriptingLanguageParser.IN) self.state = 271 self.match(scriptingLanguageParser.ACTTYPE3) self.state = 272 self.match(scriptingLanguageParser.CHECK) self.state = 273 self.match(scriptingLanguageParser.FOR) self.state = 274 self.match(scriptingLanguageParser.SAME) self.state = 275 self.match(scriptingLanguageParser.STATE) self.state = 276 self.match(scriptingLanguageParser.COL) self.state = 277 self.commandlist3() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff3Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE3(self): return self.getToken(scriptingLanguageParser.ACTTYPE3, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist3(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist3Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff3 def enterRule(self, listener): if hasattr(listener, "enterTestdiff3"): listener.enterTestdiff3(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff3"): listener.exitTestdiff3(self) def testdiff3(self): localctx = scriptingLanguageParser.Testdiff3Context(self, self._ctx, self.state) self.enterRule(localctx, 32, self.RULE_testdiff3) try: self.enterOuterAlt(localctx, 1) self.state = 279 self.match(scriptingLanguageParser.IN) self.state = 280 self.match(scriptingLanguageParser.ACTTYPE3) self.state = 281 self.match(scriptingLanguageParser.CHECK) self.state = 282 self.match(scriptingLanguageParser.FOR) self.state = 283 self.match(scriptingLanguageParser.DIFFERENT) self.state = 284 self.match(scriptingLanguageParser.STATE) self.state = 285 self.activitytype() self.state = 286 self.match(scriptingLanguageParser.COL) self.state = 287 self.commandlist3() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame4Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE4(self): return self.getToken(scriptingLanguageParser.ACTTYPE4, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist4(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist4Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame4 def enterRule(self, listener): if hasattr(listener, "enterTestsame4"): listener.enterTestsame4(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame4"): listener.exitTestsame4(self) def testsame4(self): localctx = scriptingLanguageParser.Testsame4Context(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_testsame4) try: self.enterOuterAlt(localctx, 1) self.state = 289 self.match(scriptingLanguageParser.IN) self.state = 290 self.match(scriptingLanguageParser.ACTTYPE4) self.state = 291 self.match(scriptingLanguageParser.CHECK) self.state = 292 self.match(scriptingLanguageParser.FOR) self.state = 293 self.match(scriptingLanguageParser.SAME) self.state = 294 self.match(scriptingLanguageParser.STATE) self.state = 295 self.match(scriptingLanguageParser.COL) self.state = 296 self.commandlist4() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff4Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE4(self): return self.getToken(scriptingLanguageParser.ACTTYPE4, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist4(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist4Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff4 def enterRule(self, listener): if hasattr(listener, "enterTestdiff4"): listener.enterTestdiff4(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff4"): listener.exitTestdiff4(self) def testdiff4(self): localctx = scriptingLanguageParser.Testdiff4Context(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_testdiff4) try: self.enterOuterAlt(localctx, 1) self.state = 298 self.match(scriptingLanguageParser.IN) self.state = 299 self.match(scriptingLanguageParser.ACTTYPE4) self.state = 300 self.match(scriptingLanguageParser.CHECK) self.state = 301 self.match(scriptingLanguageParser.FOR) self.state = 302 self.match(scriptingLanguageParser.DIFFERENT) self.state = 303 self.match(scriptingLanguageParser.STATE) self.state = 304 self.activitytype() self.state = 305 self.match(scriptingLanguageParser.COL) self.state = 306 self.commandlist4() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame5Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE5(self): return self.getToken(scriptingLanguageParser.ACTTYPE5, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist5(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist5Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame5 def enterRule(self, listener): if hasattr(listener, "enterTestsame5"): listener.enterTestsame5(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame5"): listener.exitTestsame5(self) def testsame5(self): localctx = scriptingLanguageParser.Testsame5Context(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_testsame5) try: self.enterOuterAlt(localctx, 1) self.state = 308 self.match(scriptingLanguageParser.IN) self.state = 309 self.match(scriptingLanguageParser.ACTTYPE5) self.state = 310 self.match(scriptingLanguageParser.CHECK) self.state = 311 self.match(scriptingLanguageParser.FOR) self.state = 312 self.match(scriptingLanguageParser.SAME) self.state = 313 self.match(scriptingLanguageParser.STATE) self.state = 314 self.match(scriptingLanguageParser.COL) self.state = 315 self.commandlist5() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff5Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE5(self): return self.getToken(scriptingLanguageParser.ACTTYPE5, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist5(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist5Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff5 def enterRule(self, listener): if hasattr(listener, "enterTestdiff5"): listener.enterTestdiff5(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff5"): listener.exitTestdiff5(self) def testdiff5(self): localctx = scriptingLanguageParser.Testdiff5Context(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_testdiff5) try: self.enterOuterAlt(localctx, 1) self.state = 317 self.match(scriptingLanguageParser.IN) self.state = 318 self.match(scriptingLanguageParser.ACTTYPE5) self.state = 319 self.match(scriptingLanguageParser.CHECK) self.state = 320 self.match(scriptingLanguageParser.FOR) self.state = 321 self.match(scriptingLanguageParser.DIFFERENT) self.state = 322 self.match(scriptingLanguageParser.STATE) self.state = 323 self.activitytype() self.state = 324 self.match(scriptingLanguageParser.COL) self.state = 325 self.commandlist5() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame6Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame6Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE6(self): return self.getToken(scriptingLanguageParser.ACTTYPE6, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist6(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist6Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame6 def enterRule(self, listener): if hasattr(listener, "enterTestsame6"): listener.enterTestsame6(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame6"): listener.exitTestsame6(self) def testsame6(self): localctx = scriptingLanguageParser.Testsame6Context(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_testsame6) try: self.enterOuterAlt(localctx, 1) self.state = 327 self.match(scriptingLanguageParser.IN) self.state = 328 self.match(scriptingLanguageParser.ACTTYPE6) self.state = 329 self.match(scriptingLanguageParser.CHECK) self.state = 330 self.match(scriptingLanguageParser.FOR) self.state = 331 self.match(scriptingLanguageParser.SAME) self.state = 332 self.match(scriptingLanguageParser.STATE) self.state = 333 self.match(scriptingLanguageParser.COL) self.state = 334 self.commandlist6() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff6Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff6Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE6(self): return self.getToken(scriptingLanguageParser.ACTTYPE6, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist6(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist6Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff6 def enterRule(self, listener): if hasattr(listener, "enterTestdiff6"): listener.enterTestdiff6(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff6"): listener.exitTestdiff6(self) def testdiff6(self): localctx = scriptingLanguageParser.Testdiff6Context(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_testdiff6) try: self.enterOuterAlt(localctx, 1) self.state = 336 self.match(scriptingLanguageParser.IN) self.state = 337 self.match(scriptingLanguageParser.ACTTYPE6) self.state = 338 self.match(scriptingLanguageParser.CHECK) self.state = 339 self.match(scriptingLanguageParser.FOR) self.state = 340 self.match(scriptingLanguageParser.DIFFERENT) self.state = 341 self.match(scriptingLanguageParser.STATE) self.state = 342 self.activitytype() self.state = 343 self.match(scriptingLanguageParser.COL) self.state = 344 self.commandlist6() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame7Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame7Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE7(self): return self.getToken(scriptingLanguageParser.ACTTYPE7, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist7(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist7Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame7 def enterRule(self, listener): if hasattr(listener, "enterTestsame7"): listener.enterTestsame7(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame7"): listener.exitTestsame7(self) def testsame7(self): localctx = scriptingLanguageParser.Testsame7Context(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_testsame7) try: self.enterOuterAlt(localctx, 1) self.state = 346 self.match(scriptingLanguageParser.IN) self.state = 347 self.match(scriptingLanguageParser.ACTTYPE7) self.state = 348 self.match(scriptingLanguageParser.CHECK) self.state = 349 self.match(scriptingLanguageParser.FOR) self.state = 350 self.match(scriptingLanguageParser.SAME) self.state = 351 self.match(scriptingLanguageParser.STATE) self.state = 352 self.match(scriptingLanguageParser.COL) self.state = 353 self.commandlist7() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff7Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff7Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE7(self): return self.getToken(scriptingLanguageParser.ACTTYPE7, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist7(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist7Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff7 def enterRule(self, listener): if hasattr(listener, "enterTestdiff7"): listener.enterTestdiff7(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff7"): listener.exitTestdiff7(self) def testdiff7(self): localctx = scriptingLanguageParser.Testdiff7Context(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_testdiff7) try: self.enterOuterAlt(localctx, 1) self.state = 355 self.match(scriptingLanguageParser.IN) self.state = 356 self.match(scriptingLanguageParser.ACTTYPE7) self.state = 357 self.match(scriptingLanguageParser.CHECK) self.state = 358 self.match(scriptingLanguageParser.FOR) self.state = 359 self.match(scriptingLanguageParser.DIFFERENT) self.state = 360 self.match(scriptingLanguageParser.STATE) self.state = 361 self.activitytype() self.state = 362 self.match(scriptingLanguageParser.COL) self.state = 363 self.commandlist7() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testsame8Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testsame8Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE8(self): return self.getToken(scriptingLanguageParser.ACTTYPE8, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def SAME(self): return self.getToken(scriptingLanguageParser.SAME, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist8(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist8Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testsame8 def enterRule(self, listener): if hasattr(listener, "enterTestsame8"): listener.enterTestsame8(self) def exitRule(self, listener): if hasattr(listener, "exitTestsame8"): listener.exitTestsame8(self) def testsame8(self): localctx = scriptingLanguageParser.Testsame8Context(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_testsame8) try: self.enterOuterAlt(localctx, 1) self.state = 365 self.match(scriptingLanguageParser.IN) self.state = 366 self.match(scriptingLanguageParser.ACTTYPE8) self.state = 367 self.match(scriptingLanguageParser.CHECK) self.state = 368 self.match(scriptingLanguageParser.FOR) self.state = 369 self.match(scriptingLanguageParser.SAME) self.state = 370 self.match(scriptingLanguageParser.STATE) self.state = 371 self.match(scriptingLanguageParser.COL) self.state = 372 self.commandlist8() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Testdiff8Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Testdiff8Context, self).__init__(parent, invokingState) self.parser = parser def IN(self): return self.getToken(scriptingLanguageParser.IN, 0) def ACTTYPE8(self): return self.getToken(scriptingLanguageParser.ACTTYPE8, 0) def CHECK(self): return self.getToken(scriptingLanguageParser.CHECK, 0) def FOR(self): return self.getToken(scriptingLanguageParser.FOR, 0) def DIFFERENT(self): return self.getToken(scriptingLanguageParser.DIFFERENT, 0) def STATE(self): return self.getToken(scriptingLanguageParser.STATE, 0) def activitytype(self): return self.getTypedRuleContext(scriptingLanguageParser.ActivitytypeContext,0) def COL(self): return self.getToken(scriptingLanguageParser.COL, 0) def commandlist8(self): return self.getTypedRuleContext(scriptingLanguageParser.Commandlist8Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testdiff8 def enterRule(self, listener): if hasattr(listener, "enterTestdiff8"): listener.enterTestdiff8(self) def exitRule(self, listener): if hasattr(listener, "exitTestdiff8"): listener.exitTestdiff8(self) def testdiff8(self): localctx = scriptingLanguageParser.Testdiff8Context(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_testdiff8) try: self.enterOuterAlt(localctx, 1) self.state = 374 self.match(scriptingLanguageParser.IN) self.state = 375 self.match(scriptingLanguageParser.ACTTYPE8) self.state = 376 self.match(scriptingLanguageParser.CHECK) self.state = 377 self.match(scriptingLanguageParser.FOR) self.state = 378 self.match(scriptingLanguageParser.DIFFERENT) self.state = 379 self.match(scriptingLanguageParser.STATE) self.state = 380 self.activitytype() self.state = 381 self.match(scriptingLanguageParser.COL) self.state = 382 self.commandlist8() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ActivitytypeContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.ActivitytypeContext, self).__init__(parent, invokingState) self.parser = parser def ACTTYPE1(self): return self.getToken(scriptingLanguageParser.ACTTYPE1, 0) def ACTTYPE2(self): return self.getToken(scriptingLanguageParser.ACTTYPE2, 0) def ACTTYPE3(self): return self.getToken(scriptingLanguageParser.ACTTYPE3, 0) def ACTTYPE4(self): return self.getToken(scriptingLanguageParser.ACTTYPE4, 0) def ACTTYPE5(self): return self.getToken(scriptingLanguageParser.ACTTYPE5, 0) def ACTTYPE6(self): return self.getToken(scriptingLanguageParser.ACTTYPE6, 0) def ACTTYPE7(self): return self.getToken(scriptingLanguageParser.ACTTYPE7, 0) def ACTTYPE8(self): return self.getToken(scriptingLanguageParser.ACTTYPE8, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_activitytype def enterRule(self, listener): if hasattr(listener, "enterActivitytype"): listener.enterActivitytype(self) def exitRule(self, listener): if hasattr(listener, "exitActivitytype"): listener.exitActivitytype(self) def activitytype(self): localctx = scriptingLanguageParser.ActivitytypeContext(self, self._ctx, self.state) self.enterRule(localctx, 54, self.RULE_activitytype) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 384 _la = self._input.LA(1) if not(((((_la - 64)) & ~0x3f) == 0 and ((1 << (_la - 64)) & ((1 << (scriptingLanguageParser.ACTTYPE1 - 64)) | (1 << (scriptingLanguageParser.ACTTYPE2 - 64)) | (1 << (scriptingLanguageParser.ACTTYPE3 - 64)) | (1 << (scriptingLanguageParser.ACTTYPE4 - 64)) | (1 << (scriptingLanguageParser.ACTTYPE5 - 64)) | (1 << (scriptingLanguageParser.ACTTYPE6 - 64)) | (1 << (scriptingLanguageParser.ACTTYPE7 - 64)) | (1 << (scriptingLanguageParser.ACTTYPE8 - 64)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist1Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command1ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver1Context,i) def command1ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver2Context,i) def command1ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver3Context,i) def command1ver4(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver4Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver4Context,i) def command1ver5(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver5Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver5Context,i) def command1ver6(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver6Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver6Context,i) def command1ver7(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver7Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver7Context,i) def command1ver8(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command1ver8Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command1ver8Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist1 def enterRule(self, listener): if hasattr(listener, "enterCommandlist1"): listener.enterCommandlist1(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist1"): listener.exitCommandlist1(self) def commandlist1(self): localctx = scriptingLanguageParser.Commandlist1Context(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_commandlist1) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 407 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 403 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,10,self._ctx) if la_ == 1: self.state = 386 self.command1ver1() pass elif la_ == 2: self.state = 387 self.command1ver2() pass elif la_ == 3: self.state = 388 self.command1ver3() pass elif la_ == 4: self.state = 389 self.command1ver4() pass elif la_ == 5: self.state = 390 self.command1ver5() pass elif la_ == 6: self.state = 391 self.command1ver6() pass elif la_ == 7: self.state = 392 self.command1ver7() pass elif la_ == 8: self.state = 393 self.command1ver8() pass elif la_ == 9: self.state = 394 self.commandCustomClick() pass elif la_ == 10: self.state = 395 self.commandCustomLongClick() pass elif la_ == 11: self.state = 396 self.commandCustomDrag() pass elif la_ == 12: self.state = 397 self.commandCustomType() pass elif la_ == 13: self.state = 398 self.commandCustomBack() pass elif la_ == 14: self.state = 399 self.commandCustomSleep() pass elif la_ == 15: self.state = 400 self.testCustom() pass elif la_ == 16: self.state = 401 self.commandCustomAssertText() pass elif la_ == 17: self.state = 402 self.commandCustomClickText() pass self.state = 405 self.match(scriptingLanguageParser.SEMICOL) self.state = 409 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.CLICK) | (1 << scriptingLanguageParser.PRESS) | (1 << scriptingLanguageParser.SWIPE) | (1 << scriptingLanguageParser.TICK) | (1 << scriptingLanguageParser.ADD) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE) | (1 << scriptingLanguageParser.ASSERT))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver1Context, self).__init__(parent, invokingState) self.parser = parser def ADD(self): return self.getToken(scriptingLanguageParser.ADD, 0) def TASK(self): return self.getToken(scriptingLanguageParser.TASK, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver1"): listener.enterCommand1ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver1"): listener.exitCommand1ver1(self) def command1ver1(self): localctx = scriptingLanguageParser.Command1ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_command1ver1) try: self.enterOuterAlt(localctx, 1) self.state = 411 self.match(scriptingLanguageParser.ADD) self.state = 412 self.match(scriptingLanguageParser.TASK) self.state = 413 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver2Context, self).__init__(parent, invokingState) self.parser = parser def TICK(self): return self.getToken(scriptingLanguageParser.TICK, 0) def LINE(self): return self.getToken(scriptingLanguageParser.LINE, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver2"): listener.enterCommand1ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver2"): listener.exitCommand1ver2(self) def command1ver2(self): localctx = scriptingLanguageParser.Command1ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 60, self.RULE_command1ver2) try: self.enterOuterAlt(localctx, 1) self.state = 415 self.match(scriptingLanguageParser.TICK) self.state = 416 self.match(scriptingLanguageParser.LINE) self.state = 417 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver3Context, self).__init__(parent, invokingState) self.parser = parser def TICK(self): return self.getToken(scriptingLanguageParser.TICK, 0) def ALL(self): return self.getToken(scriptingLanguageParser.ALL, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver3"): listener.enterCommand1ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver3"): listener.exitCommand1ver3(self) def command1ver3(self): localctx = scriptingLanguageParser.Command1ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 62, self.RULE_command1ver3) try: self.enterOuterAlt(localctx, 1) self.state = 419 self.match(scriptingLanguageParser.TICK) self.state = 420 self.match(scriptingLanguageParser.ALL) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver4Context, self).__init__(parent, invokingState) self.parser = parser def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def LINE(self): return self.getToken(scriptingLanguageParser.LINE, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver4 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver4"): listener.enterCommand1ver4(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver4"): listener.exitCommand1ver4(self) def command1ver4(self): localctx = scriptingLanguageParser.Command1ver4Context(self, self._ctx, self.state) self.enterRule(localctx, 64, self.RULE_command1ver4) try: self.enterOuterAlt(localctx, 1) self.state = 422 self.match(scriptingLanguageParser.CLICK) self.state = 423 self.match(scriptingLanguageParser.LINE) self.state = 424 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver5Context, self).__init__(parent, invokingState) self.parser = parser def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def BACK(self): return self.getToken(scriptingLanguageParser.BACK, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver5 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver5"): listener.enterCommand1ver5(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver5"): listener.exitCommand1ver5(self) def command1ver5(self): localctx = scriptingLanguageParser.Command1ver5Context(self, self._ctx, self.state) self.enterRule(localctx, 66, self.RULE_command1ver5) try: self.enterOuterAlt(localctx, 1) self.state = 426 self.match(scriptingLanguageParser.PRESS) self.state = 427 self.match(scriptingLanguageParser.BACK) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver6Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver6Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def UP(self): return self.getToken(scriptingLanguageParser.UP, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver6 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver6"): listener.enterCommand1ver6(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver6"): listener.exitCommand1ver6(self) def command1ver6(self): localctx = scriptingLanguageParser.Command1ver6Context(self, self._ctx, self.state) self.enterRule(localctx, 68, self.RULE_command1ver6) try: self.enterOuterAlt(localctx, 1) self.state = 429 self.match(scriptingLanguageParser.SWIPE) self.state = 430 self.match(scriptingLanguageParser.UP) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver7Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver7Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def DOWN(self): return self.getToken(scriptingLanguageParser.DOWN, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver7 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver7"): listener.enterCommand1ver7(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver7"): listener.exitCommand1ver7(self) def command1ver7(self): localctx = scriptingLanguageParser.Command1ver7Context(self, self._ctx, self.state) self.enterRule(localctx, 70, self.RULE_command1ver7) try: self.enterOuterAlt(localctx, 1) self.state = 432 self.match(scriptingLanguageParser.SWIPE) self.state = 433 self.match(scriptingLanguageParser.DOWN) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command1ver8Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command1ver8Context, self).__init__(parent, invokingState) self.parser = parser def ASSERT(self): return self.getToken(scriptingLanguageParser.ASSERT, 0) def LINECOUNT(self): return self.getToken(scriptingLanguageParser.LINECOUNT, 0) def EQUALS(self): return self.getToken(scriptingLanguageParser.EQUALS, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command1ver8 def enterRule(self, listener): if hasattr(listener, "enterCommand1ver8"): listener.enterCommand1ver8(self) def exitRule(self, listener): if hasattr(listener, "exitCommand1ver8"): listener.exitCommand1ver8(self) def command1ver8(self): localctx = scriptingLanguageParser.Command1ver8Context(self, self._ctx, self.state) self.enterRule(localctx, 72, self.RULE_command1ver8) try: self.enterOuterAlt(localctx, 1) self.state = 435 self.match(scriptingLanguageParser.ASSERT) self.state = 436 self.match(scriptingLanguageParser.LINECOUNT) self.state = 437 self.match(scriptingLanguageParser.EQUALS) self.state = 438 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist2Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command2ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command2ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command2ver1Context,i) def command2ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command2ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command2ver2Context,i) def command2ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command2ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command2ver3Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist2 def enterRule(self, listener): if hasattr(listener, "enterCommandlist2"): listener.enterCommandlist2(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist2"): listener.exitCommandlist2(self) def commandlist2(self): localctx = scriptingLanguageParser.Commandlist2Context(self, self._ctx, self.state) self.enterRule(localctx, 74, self.RULE_commandlist2) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 456 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 452 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,12,self._ctx) if la_ == 1: self.state = 440 self.command2ver1() pass elif la_ == 2: self.state = 441 self.command2ver2() pass elif la_ == 3: self.state = 442 self.command2ver3() pass elif la_ == 4: self.state = 443 self.commandCustomClick() pass elif la_ == 5: self.state = 444 self.commandCustomLongClick() pass elif la_ == 6: self.state = 445 self.commandCustomDrag() pass elif la_ == 7: self.state = 446 self.commandCustomType() pass elif la_ == 8: self.state = 447 self.commandCustomBack() pass elif la_ == 9: self.state = 448 self.commandCustomSleep() pass elif la_ == 10: self.state = 449 self.testCustom() pass elif la_ == 11: self.state = 450 self.commandCustomAssertText() pass elif la_ == 12: self.state = 451 self.commandCustomClickText() pass self.state = 454 self.match(scriptingLanguageParser.SEMICOL) self.state = 458 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.CLICK) | (1 << scriptingLanguageParser.PRESS) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command2ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command2ver1Context, self).__init__(parent, invokingState) self.parser = parser def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def CLOSE(self): return self.getToken(scriptingLanguageParser.CLOSE, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command2ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand2ver1"): listener.enterCommand2ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand2ver1"): listener.exitCommand2ver1(self) def command2ver1(self): localctx = scriptingLanguageParser.Command2ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 76, self.RULE_command2ver1) try: self.enterOuterAlt(localctx, 1) self.state = 460 self.match(scriptingLanguageParser.CLICK) self.state = 461 self.match(scriptingLanguageParser.CLOSE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command2ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command2ver2Context, self).__init__(parent, invokingState) self.parser = parser def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def ACTTYPE2(self): return self.getToken(scriptingLanguageParser.ACTTYPE2, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command2ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand2ver2"): listener.enterCommand2ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand2ver2"): listener.exitCommand2ver2(self) def command2ver2(self): localctx = scriptingLanguageParser.Command2ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 78, self.RULE_command2ver2) try: self.enterOuterAlt(localctx, 1) self.state = 463 self.match(scriptingLanguageParser.CLICK) self.state = 464 self.match(scriptingLanguageParser.ACTTYPE2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command2ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command2ver3Context, self).__init__(parent, invokingState) self.parser = parser def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def BACK(self): return self.getToken(scriptingLanguageParser.BACK, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command2ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand2ver3"): listener.enterCommand2ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand2ver3"): listener.exitCommand2ver3(self) def command2ver3(self): localctx = scriptingLanguageParser.Command2ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 80, self.RULE_command2ver3) try: self.enterOuterAlt(localctx, 1) self.state = 466 self.match(scriptingLanguageParser.PRESS) self.state = 467 self.match(scriptingLanguageParser.BACK) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist3Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command3ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command3ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command3ver1Context,i) def command3ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command3ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command3ver2Context,i) def command3ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command3ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command3ver3Context,i) def command3ver4(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command3ver4Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command3ver4Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist3 def enterRule(self, listener): if hasattr(listener, "enterCommandlist3"): listener.enterCommandlist3(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist3"): listener.exitCommandlist3(self) def commandlist3(self): localctx = scriptingLanguageParser.Commandlist3Context(self, self._ctx, self.state) self.enterRule(localctx, 82, self.RULE_commandlist3) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 486 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 482 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,14,self._ctx) if la_ == 1: self.state = 469 self.command3ver1() pass elif la_ == 2: self.state = 470 self.command3ver2() pass elif la_ == 3: self.state = 471 self.command3ver3() pass elif la_ == 4: self.state = 472 self.command3ver4() pass elif la_ == 5: self.state = 473 self.commandCustomClick() pass elif la_ == 6: self.state = 474 self.commandCustomLongClick() pass elif la_ == 7: self.state = 475 self.commandCustomDrag() pass elif la_ == 8: self.state = 476 self.commandCustomType() pass elif la_ == 9: self.state = 477 self.commandCustomBack() pass elif la_ == 10: self.state = 478 self.commandCustomSleep() pass elif la_ == 11: self.state = 479 self.testCustom() pass elif la_ == 12: self.state = 480 self.commandCustomAssertText() pass elif la_ == 13: self.state = 481 self.commandCustomClickText() pass self.state = 484 self.match(scriptingLanguageParser.SEMICOL) self.state = 488 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.INPUT) | (1 << scriptingLanguageParser.CLICK) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE) | (1 << scriptingLanguageParser.CLEAR))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command3ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command3ver1Context, self).__init__(parent, invokingState) self.parser = parser def INPUT(self): return self.getToken(scriptingLanguageParser.INPUT, 0) def NAME(self): return self.getToken(scriptingLanguageParser.NAME, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command3ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand3ver1"): listener.enterCommand3ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand3ver1"): listener.exitCommand3ver1(self) def command3ver1(self): localctx = scriptingLanguageParser.Command3ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 84, self.RULE_command3ver1) try: self.enterOuterAlt(localctx, 1) self.state = 490 self.match(scriptingLanguageParser.INPUT) self.state = 491 self.match(scriptingLanguageParser.NAME) self.state = 492 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command3ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command3ver2Context, self).__init__(parent, invokingState) self.parser = parser def INPUT(self): return self.getToken(scriptingLanguageParser.INPUT, 0) def PASSWORD(self): return self.getToken(scriptingLanguageParser.PASSWORD, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command3ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand3ver2"): listener.enterCommand3ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand3ver2"): listener.exitCommand3ver2(self) def command3ver2(self): localctx = scriptingLanguageParser.Command3ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 86, self.RULE_command3ver2) try: self.enterOuterAlt(localctx, 1) self.state = 494 self.match(scriptingLanguageParser.INPUT) self.state = 495 self.match(scriptingLanguageParser.PASSWORD) self.state = 496 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command3ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command3ver3Context, self).__init__(parent, invokingState) self.parser = parser def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def NEXT(self): return self.getToken(scriptingLanguageParser.NEXT, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command3ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand3ver3"): listener.enterCommand3ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand3ver3"): listener.exitCommand3ver3(self) def command3ver3(self): localctx = scriptingLanguageParser.Command3ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 88, self.RULE_command3ver3) try: self.enterOuterAlt(localctx, 1) self.state = 498 self.match(scriptingLanguageParser.CLICK) self.state = 499 self.match(scriptingLanguageParser.NEXT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command3ver4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command3ver4Context, self).__init__(parent, invokingState) self.parser = parser def CLEAR(self): return self.getToken(scriptingLanguageParser.CLEAR, 0) def FIELDS(self): return self.getToken(scriptingLanguageParser.FIELDS, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command3ver4 def enterRule(self, listener): if hasattr(listener, "enterCommand3ver4"): listener.enterCommand3ver4(self) def exitRule(self, listener): if hasattr(listener, "exitCommand3ver4"): listener.exitCommand3ver4(self) def command3ver4(self): localctx = scriptingLanguageParser.Command3ver4Context(self, self._ctx, self.state) self.enterRule(localctx, 90, self.RULE_command3ver4) try: self.enterOuterAlt(localctx, 1) self.state = 501 self.match(scriptingLanguageParser.CLEAR) self.state = 502 self.match(scriptingLanguageParser.FIELDS) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist4Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command4ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command4ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command4ver1Context,i) def command4ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command4ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command4ver2Context,i) def command4ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command4ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command4ver3Context,i) def command4ver4(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command4ver4Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command4ver4Context,i) def command4ver5(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command4ver5Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command4ver5Context,i) def command4ver6(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command4ver6Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command4ver6Context,i) def command4ver7(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command4ver7Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command4ver7Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist4 def enterRule(self, listener): if hasattr(listener, "enterCommandlist4"): listener.enterCommandlist4(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist4"): listener.exitCommandlist4(self) def commandlist4(self): localctx = scriptingLanguageParser.Commandlist4Context(self, self._ctx, self.state) self.enterRule(localctx, 92, self.RULE_commandlist4) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 524 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 520 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,16,self._ctx) if la_ == 1: self.state = 504 self.command4ver1() pass elif la_ == 2: self.state = 505 self.command4ver2() pass elif la_ == 3: self.state = 506 self.command4ver3() pass elif la_ == 4: self.state = 507 self.command4ver4() pass elif la_ == 5: self.state = 508 self.command4ver5() pass elif la_ == 6: self.state = 509 self.command4ver6() pass elif la_ == 7: self.state = 510 self.command4ver7() pass elif la_ == 8: self.state = 511 self.commandCustomClick() pass elif la_ == 9: self.state = 512 self.commandCustomLongClick() pass elif la_ == 10: self.state = 513 self.commandCustomDrag() pass elif la_ == 11: self.state = 514 self.commandCustomType() pass elif la_ == 12: self.state = 515 self.commandCustomBack() pass elif la_ == 13: self.state = 516 self.commandCustomSleep() pass elif la_ == 14: self.state = 517 self.testCustom() pass elif la_ == 15: self.state = 518 self.commandCustomAssertText() pass elif la_ == 16: self.state = 519 self.commandCustomClickText() pass self.state = 522 self.match(scriptingLanguageParser.SEMICOL) self.state = 526 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.CLICK) | (1 << scriptingLanguageParser.PRESS) | (1 << scriptingLanguageParser.LONG) | (1 << scriptingLanguageParser.TOGGLE) | (1 << scriptingLanguageParser.SWIPE) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command4ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command4ver1Context, self).__init__(parent, invokingState) self.parser = parser def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def LINE(self): return self.getToken(scriptingLanguageParser.LINE, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command4ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand4ver1"): listener.enterCommand4ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand4ver1"): listener.exitCommand4ver1(self) def command4ver1(self): localctx = scriptingLanguageParser.Command4ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 94, self.RULE_command4ver1) try: self.enterOuterAlt(localctx, 1) self.state = 528 self.match(scriptingLanguageParser.CLICK) self.state = 529 self.match(scriptingLanguageParser.LINE) self.state = 530 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command4ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command4ver2Context, self).__init__(parent, invokingState) self.parser = parser def TOGGLE(self): return self.getToken(scriptingLanguageParser.TOGGLE, 0) def LINE(self): return self.getToken(scriptingLanguageParser.LINE, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command4ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand4ver2"): listener.enterCommand4ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand4ver2"): listener.exitCommand4ver2(self) def command4ver2(self): localctx = scriptingLanguageParser.Command4ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 96, self.RULE_command4ver2) try: self.enterOuterAlt(localctx, 1) self.state = 532 self.match(scriptingLanguageParser.TOGGLE) self.state = 533 self.match(scriptingLanguageParser.LINE) self.state = 534 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command4ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command4ver3Context, self).__init__(parent, invokingState) self.parser = parser def LONG(self): return self.getToken(scriptingLanguageParser.LONG, 0) def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def LINE(self): return self.getToken(scriptingLanguageParser.LINE, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command4ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand4ver3"): listener.enterCommand4ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand4ver3"): listener.exitCommand4ver3(self) def command4ver3(self): localctx = scriptingLanguageParser.Command4ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 98, self.RULE_command4ver3) try: self.enterOuterAlt(localctx, 1) self.state = 536 self.match(scriptingLanguageParser.LONG) self.state = 537 self.match(scriptingLanguageParser.CLICK) self.state = 538 self.match(scriptingLanguageParser.LINE) self.state = 539 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command4ver4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command4ver4Context, self).__init__(parent, invokingState) self.parser = parser def LONG(self): return self.getToken(scriptingLanguageParser.LONG, 0) def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def ALL(self): return self.getToken(scriptingLanguageParser.ALL, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command4ver4 def enterRule(self, listener): if hasattr(listener, "enterCommand4ver4"): listener.enterCommand4ver4(self) def exitRule(self, listener): if hasattr(listener, "exitCommand4ver4"): listener.exitCommand4ver4(self) def command4ver4(self): localctx = scriptingLanguageParser.Command4ver4Context(self, self._ctx, self.state) self.enterRule(localctx, 100, self.RULE_command4ver4) try: self.enterOuterAlt(localctx, 1) self.state = 541 self.match(scriptingLanguageParser.LONG) self.state = 542 self.match(scriptingLanguageParser.CLICK) self.state = 543 self.match(scriptingLanguageParser.ALL) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command4ver5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command4ver5Context, self).__init__(parent, invokingState) self.parser = parser def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def BACK(self): return self.getToken(scriptingLanguageParser.BACK, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command4ver5 def enterRule(self, listener): if hasattr(listener, "enterCommand4ver5"): listener.enterCommand4ver5(self) def exitRule(self, listener): if hasattr(listener, "exitCommand4ver5"): listener.exitCommand4ver5(self) def command4ver5(self): localctx = scriptingLanguageParser.Command4ver5Context(self, self._ctx, self.state) self.enterRule(localctx, 102, self.RULE_command4ver5) try: self.enterOuterAlt(localctx, 1) self.state = 545 self.match(scriptingLanguageParser.PRESS) self.state = 546 self.match(scriptingLanguageParser.BACK) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command4ver6Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command4ver6Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def UP(self): return self.getToken(scriptingLanguageParser.UP, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command4ver6 def enterRule(self, listener): if hasattr(listener, "enterCommand4ver6"): listener.enterCommand4ver6(self) def exitRule(self, listener): if hasattr(listener, "exitCommand4ver6"): listener.exitCommand4ver6(self) def command4ver6(self): localctx = scriptingLanguageParser.Command4ver6Context(self, self._ctx, self.state) self.enterRule(localctx, 104, self.RULE_command4ver6) try: self.enterOuterAlt(localctx, 1) self.state = 548 self.match(scriptingLanguageParser.SWIPE) self.state = 549 self.match(scriptingLanguageParser.UP) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command4ver7Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command4ver7Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def DOWN(self): return self.getToken(scriptingLanguageParser.DOWN, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command4ver7 def enterRule(self, listener): if hasattr(listener, "enterCommand4ver7"): listener.enterCommand4ver7(self) def exitRule(self, listener): if hasattr(listener, "exitCommand4ver7"): listener.exitCommand4ver7(self) def command4ver7(self): localctx = scriptingLanguageParser.Command4ver7Context(self, self._ctx, self.state) self.enterRule(localctx, 106, self.RULE_command4ver7) try: self.enterOuterAlt(localctx, 1) self.state = 551 self.match(scriptingLanguageParser.SWIPE) self.state = 552 self.match(scriptingLanguageParser.DOWN) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist5Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command5ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command5ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command5ver1Context,i) def command5ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command5ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command5ver2Context,i) def command5ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command5ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command5ver3Context,i) def command5ver4(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command5ver4Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command5ver4Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist5 def enterRule(self, listener): if hasattr(listener, "enterCommandlist5"): listener.enterCommandlist5(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist5"): listener.exitCommandlist5(self) def commandlist5(self): localctx = scriptingLanguageParser.Commandlist5Context(self, self._ctx, self.state) self.enterRule(localctx, 108, self.RULE_commandlist5) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 571 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 567 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,18,self._ctx) if la_ == 1: self.state = 554 self.command5ver1() pass elif la_ == 2: self.state = 555 self.command5ver2() pass elif la_ == 3: self.state = 556 self.command5ver3() pass elif la_ == 4: self.state = 557 self.command5ver4() pass elif la_ == 5: self.state = 558 self.commandCustomClick() pass elif la_ == 6: self.state = 559 self.commandCustomLongClick() pass elif la_ == 7: self.state = 560 self.commandCustomDrag() pass elif la_ == 8: self.state = 561 self.commandCustomType() pass elif la_ == 9: self.state = 562 self.commandCustomBack() pass elif la_ == 10: self.state = 563 self.commandCustomSleep() pass elif la_ == 11: self.state = 564 self.testCustom() pass elif la_ == 12: self.state = 565 self.commandCustomAssertText() pass elif la_ == 13: self.state = 566 self.commandCustomClickText() pass self.state = 569 self.match(scriptingLanguageParser.SEMICOL) self.state = 573 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.SWIPE) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command5ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command5ver1Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def UP(self): return self.getToken(scriptingLanguageParser.UP, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command5ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand5ver1"): listener.enterCommand5ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand5ver1"): listener.exitCommand5ver1(self) def command5ver1(self): localctx = scriptingLanguageParser.Command5ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 110, self.RULE_command5ver1) try: self.enterOuterAlt(localctx, 1) self.state = 575 self.match(scriptingLanguageParser.SWIPE) self.state = 576 self.match(scriptingLanguageParser.UP) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command5ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command5ver2Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def DOWN(self): return self.getToken(scriptingLanguageParser.DOWN, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command5ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand5ver2"): listener.enterCommand5ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand5ver2"): listener.exitCommand5ver2(self) def command5ver2(self): localctx = scriptingLanguageParser.Command5ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 112, self.RULE_command5ver2) try: self.enterOuterAlt(localctx, 1) self.state = 578 self.match(scriptingLanguageParser.SWIPE) self.state = 579 self.match(scriptingLanguageParser.DOWN) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command5ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command5ver3Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def LEFT(self): return self.getToken(scriptingLanguageParser.LEFT, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command5ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand5ver3"): listener.enterCommand5ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand5ver3"): listener.exitCommand5ver3(self) def command5ver3(self): localctx = scriptingLanguageParser.Command5ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 114, self.RULE_command5ver3) try: self.enterOuterAlt(localctx, 1) self.state = 581 self.match(scriptingLanguageParser.SWIPE) self.state = 582 self.match(scriptingLanguageParser.LEFT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command5ver4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command5ver4Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def RIGHT(self): return self.getToken(scriptingLanguageParser.RIGHT, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command5ver4 def enterRule(self, listener): if hasattr(listener, "enterCommand5ver4"): listener.enterCommand5ver4(self) def exitRule(self, listener): if hasattr(listener, "exitCommand5ver4"): listener.exitCommand5ver4(self) def command5ver4(self): localctx = scriptingLanguageParser.Command5ver4Context(self, self._ctx, self.state) self.enterRule(localctx, 116, self.RULE_command5ver4) try: self.enterOuterAlt(localctx, 1) self.state = 584 self.match(scriptingLanguageParser.SWIPE) self.state = 585 self.match(scriptingLanguageParser.RIGHT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist6Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist6Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command6ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command6ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command6ver1Context,i) def command6ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command6ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command6ver2Context,i) def command6ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command6ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command6ver3Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist6 def enterRule(self, listener): if hasattr(listener, "enterCommandlist6"): listener.enterCommandlist6(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist6"): listener.exitCommandlist6(self) def commandlist6(self): localctx = scriptingLanguageParser.Commandlist6Context(self, self._ctx, self.state) self.enterRule(localctx, 118, self.RULE_commandlist6) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 603 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 599 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,20,self._ctx) if la_ == 1: self.state = 587 self.command6ver1() pass elif la_ == 2: self.state = 588 self.command6ver2() pass elif la_ == 3: self.state = 589 self.command6ver3() pass elif la_ == 4: self.state = 590 self.commandCustomClick() pass elif la_ == 5: self.state = 591 self.commandCustomLongClick() pass elif la_ == 6: self.state = 592 self.commandCustomDrag() pass elif la_ == 7: self.state = 593 self.commandCustomType() pass elif la_ == 8: self.state = 594 self.commandCustomBack() pass elif la_ == 9: self.state = 595 self.commandCustomSleep() pass elif la_ == 10: self.state = 596 self.testCustom() pass elif la_ == 11: self.state = 597 self.commandCustomAssertText() pass elif la_ == 12: self.state = 598 self.commandCustomClickText() pass self.state = 601 self.match(scriptingLanguageParser.SEMICOL) self.state = 605 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.INPUT) | (1 << scriptingLanguageParser.PRESS) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command6ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command6ver1Context, self).__init__(parent, invokingState) self.parser = parser def INPUT(self): return self.getToken(scriptingLanguageParser.INPUT, 0) def URL(self): return self.getToken(scriptingLanguageParser.URL, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command6ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand6ver1"): listener.enterCommand6ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand6ver1"): listener.exitCommand6ver1(self) def command6ver1(self): localctx = scriptingLanguageParser.Command6ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 120, self.RULE_command6ver1) try: self.enterOuterAlt(localctx, 1) self.state = 607 self.match(scriptingLanguageParser.INPUT) self.state = 608 self.match(scriptingLanguageParser.URL) self.state = 609 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command6ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command6ver2Context, self).__init__(parent, invokingState) self.parser = parser def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def ENTER(self): return self.getToken(scriptingLanguageParser.ENTER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command6ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand6ver2"): listener.enterCommand6ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand6ver2"): listener.exitCommand6ver2(self) def command6ver2(self): localctx = scriptingLanguageParser.Command6ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 122, self.RULE_command6ver2) try: self.enterOuterAlt(localctx, 1) self.state = 611 self.match(scriptingLanguageParser.PRESS) self.state = 612 self.match(scriptingLanguageParser.ENTER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command6ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command6ver3Context, self).__init__(parent, invokingState) self.parser = parser def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def BACK(self): return self.getToken(scriptingLanguageParser.BACK, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command6ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand6ver3"): listener.enterCommand6ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand6ver3"): listener.exitCommand6ver3(self) def command6ver3(self): localctx = scriptingLanguageParser.Command6ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 124, self.RULE_command6ver3) try: self.enterOuterAlt(localctx, 1) self.state = 614 self.match(scriptingLanguageParser.PRESS) self.state = 615 self.match(scriptingLanguageParser.BACK) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist7Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist7Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command7ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command7ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command7ver1Context,i) def command7ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command7ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command7ver2Context,i) def command7ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command7ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command7ver3Context,i) def command7ver4(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command7ver4Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command7ver4Context,i) def command7ver5(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command7ver5Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command7ver5Context,i) def command7ver6(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command7ver6Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command7ver6Context,i) def command7ver7(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command7ver7Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command7ver7Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist7 def enterRule(self, listener): if hasattr(listener, "enterCommandlist7"): listener.enterCommandlist7(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist7"): listener.exitCommandlist7(self) def commandlist7(self): localctx = scriptingLanguageParser.Commandlist7Context(self, self._ctx, self.state) self.enterRule(localctx, 126, self.RULE_commandlist7) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 637 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 633 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,22,self._ctx) if la_ == 1: self.state = 617 self.command7ver1() pass elif la_ == 2: self.state = 618 self.command7ver2() pass elif la_ == 3: self.state = 619 self.command7ver3() pass elif la_ == 4: self.state = 620 self.command7ver4() pass elif la_ == 5: self.state = 621 self.command7ver5() pass elif la_ == 6: self.state = 622 self.command7ver6() pass elif la_ == 7: self.state = 623 self.command7ver7() pass elif la_ == 8: self.state = 624 self.commandCustomClick() pass elif la_ == 9: self.state = 625 self.commandCustomLongClick() pass elif la_ == 10: self.state = 626 self.commandCustomDrag() pass elif la_ == 11: self.state = 627 self.commandCustomType() pass elif la_ == 12: self.state = 628 self.commandCustomBack() pass elif la_ == 13: self.state = 629 self.commandCustomSleep() pass elif la_ == 14: self.state = 630 self.testCustom() pass elif la_ == 15: self.state = 631 self.commandCustomAssertText() pass elif la_ == 16: self.state = 632 self.commandCustomClickText() pass self.state = 635 self.match(scriptingLanguageParser.SEMICOL) self.state = 639 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.INPUT) | (1 << scriptingLanguageParser.CLICK) | (1 << scriptingLanguageParser.LONG) | (1 << scriptingLanguageParser.SWIPE) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command7ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command7ver1Context, self).__init__(parent, invokingState) self.parser = parser def INPUT(self): return self.getToken(scriptingLanguageParser.INPUT, 0) def SEARCH(self): return self.getToken(scriptingLanguageParser.SEARCH, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command7ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand7ver1"): listener.enterCommand7ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand7ver1"): listener.exitCommand7ver1(self) def command7ver1(self): localctx = scriptingLanguageParser.Command7ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 128, self.RULE_command7ver1) try: self.enterOuterAlt(localctx, 1) self.state = 641 self.match(scriptingLanguageParser.INPUT) self.state = 642 self.match(scriptingLanguageParser.SEARCH) self.state = 643 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command7ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command7ver2Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def UP(self): return self.getToken(scriptingLanguageParser.UP, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command7ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand7ver2"): listener.enterCommand7ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand7ver2"): listener.exitCommand7ver2(self) def command7ver2(self): localctx = scriptingLanguageParser.Command7ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 130, self.RULE_command7ver2) try: self.enterOuterAlt(localctx, 1) self.state = 645 self.match(scriptingLanguageParser.SWIPE) self.state = 646 self.match(scriptingLanguageParser.UP) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command7ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command7ver3Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def DOWN(self): return self.getToken(scriptingLanguageParser.DOWN, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command7ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand7ver3"): listener.enterCommand7ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand7ver3"): listener.exitCommand7ver3(self) def command7ver3(self): localctx = scriptingLanguageParser.Command7ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 132, self.RULE_command7ver3) try: self.enterOuterAlt(localctx, 1) self.state = 648 self.match(scriptingLanguageParser.SWIPE) self.state = 649 self.match(scriptingLanguageParser.DOWN) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command7ver4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command7ver4Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def LEFT(self): return self.getToken(scriptingLanguageParser.LEFT, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command7ver4 def enterRule(self, listener): if hasattr(listener, "enterCommand7ver4"): listener.enterCommand7ver4(self) def exitRule(self, listener): if hasattr(listener, "exitCommand7ver4"): listener.exitCommand7ver4(self) def command7ver4(self): localctx = scriptingLanguageParser.Command7ver4Context(self, self._ctx, self.state) self.enterRule(localctx, 134, self.RULE_command7ver4) try: self.enterOuterAlt(localctx, 1) self.state = 651 self.match(scriptingLanguageParser.SWIPE) self.state = 652 self.match(scriptingLanguageParser.LEFT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command7ver5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command7ver5Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def RIGHT(self): return self.getToken(scriptingLanguageParser.RIGHT, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command7ver5 def enterRule(self, listener): if hasattr(listener, "enterCommand7ver5"): listener.enterCommand7ver5(self) def exitRule(self, listener): if hasattr(listener, "exitCommand7ver5"): listener.exitCommand7ver5(self) def command7ver5(self): localctx = scriptingLanguageParser.Command7ver5Context(self, self._ctx, self.state) self.enterRule(localctx, 136, self.RULE_command7ver5) try: self.enterOuterAlt(localctx, 1) self.state = 654 self.match(scriptingLanguageParser.SWIPE) self.state = 655 self.match(scriptingLanguageParser.RIGHT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command7ver6Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command7ver6Context, self).__init__(parent, invokingState) self.parser = parser def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def CENTER(self): return self.getToken(scriptingLanguageParser.CENTER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command7ver6 def enterRule(self, listener): if hasattr(listener, "enterCommand7ver6"): listener.enterCommand7ver6(self) def exitRule(self, listener): if hasattr(listener, "exitCommand7ver6"): listener.exitCommand7ver6(self) def command7ver6(self): localctx = scriptingLanguageParser.Command7ver6Context(self, self._ctx, self.state) self.enterRule(localctx, 138, self.RULE_command7ver6) try: self.enterOuterAlt(localctx, 1) self.state = 657 self.match(scriptingLanguageParser.CLICK) self.state = 658 self.match(scriptingLanguageParser.CENTER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command7ver7Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command7ver7Context, self).__init__(parent, invokingState) self.parser = parser def LONG(self): return self.getToken(scriptingLanguageParser.LONG, 0) def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def CENTER(self): return self.getToken(scriptingLanguageParser.CENTER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command7ver7 def enterRule(self, listener): if hasattr(listener, "enterCommand7ver7"): listener.enterCommand7ver7(self) def exitRule(self, listener): if hasattr(listener, "exitCommand7ver7"): listener.exitCommand7ver7(self) def command7ver7(self): localctx = scriptingLanguageParser.Command7ver7Context(self, self._ctx, self.state) self.enterRule(localctx, 140, self.RULE_command7ver7) try: self.enterOuterAlt(localctx, 1) self.state = 660 self.match(scriptingLanguageParser.LONG) self.state = 661 self.match(scriptingLanguageParser.CLICK) self.state = 662 self.match(scriptingLanguageParser.CENTER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Commandlist8Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Commandlist8Context, self).__init__(parent, invokingState) self.parser = parser def SEMICOL(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.SEMICOL) else: return self.getToken(scriptingLanguageParser.SEMICOL, i) def command8ver1(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command8ver1Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command8ver1Context,i) def command8ver2(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command8ver2Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command8ver2Context,i) def command8ver3(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command8ver3Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command8ver3Context,i) def command8ver4(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command8ver4Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command8ver4Context,i) def command8ver5(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.Command8ver5Context) else: return self.getTypedRuleContext(scriptingLanguageParser.Command8ver5Context,i) def commandCustomClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickContext,i) def commandCustomLongClick(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomLongClickContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomLongClickContext,i) def commandCustomDrag(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomDragContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomDragContext,i) def commandCustomType(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomTypeContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomTypeContext,i) def commandCustomBack(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomBackContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomBackContext,i) def commandCustomSleep(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomSleepContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomSleepContext,i) def testCustom(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.TestCustomContext) else: return self.getTypedRuleContext(scriptingLanguageParser.TestCustomContext,i) def commandCustomAssertText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomAssertTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomAssertTextContext,i) def commandCustomClickText(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CommandCustomClickTextContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CommandCustomClickTextContext,i) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandlist8 def enterRule(self, listener): if hasattr(listener, "enterCommandlist8"): listener.enterCommandlist8(self) def exitRule(self, listener): if hasattr(listener, "exitCommandlist8"): listener.exitCommandlist8(self) def commandlist8(self): localctx = scriptingLanguageParser.Commandlist8Context(self, self._ctx, self.state) self.enterRule(localctx, 142, self.RULE_commandlist8) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 682 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 678 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,24,self._ctx) if la_ == 1: self.state = 664 self.command8ver1() pass elif la_ == 2: self.state = 665 self.command8ver2() pass elif la_ == 3: self.state = 666 self.command8ver3() pass elif la_ == 4: self.state = 667 self.command8ver4() pass elif la_ == 5: self.state = 668 self.command8ver5() pass elif la_ == 6: self.state = 669 self.commandCustomClick() pass elif la_ == 7: self.state = 670 self.commandCustomLongClick() pass elif la_ == 8: self.state = 671 self.commandCustomDrag() pass elif la_ == 9: self.state = 672 self.commandCustomType() pass elif la_ == 10: self.state = 673 self.commandCustomBack() pass elif la_ == 11: self.state = 674 self.commandCustomSleep() pass elif la_ == 12: self.state = 675 self.testCustom() pass elif la_ == 13: self.state = 676 self.commandCustomAssertText() pass elif la_ == 14: self.state = 677 self.commandCustomClickText() pass self.state = 680 self.match(scriptingLanguageParser.SEMICOL) self.state = 684 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << scriptingLanguageParser.INPUT) | (1 << scriptingLanguageParser.PRESS) | (1 << scriptingLanguageParser.SWIPE) | (1 << scriptingLanguageParser.CUSTOM) | (1 << scriptingLanguageParser.EXECUTE))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command8ver1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command8ver1Context, self).__init__(parent, invokingState) self.parser = parser def INPUT(self): return self.getToken(scriptingLanguageParser.INPUT, 0) def MESSAGE(self): return self.getToken(scriptingLanguageParser.MESSAGE, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command8ver1 def enterRule(self, listener): if hasattr(listener, "enterCommand8ver1"): listener.enterCommand8ver1(self) def exitRule(self, listener): if hasattr(listener, "exitCommand8ver1"): listener.exitCommand8ver1(self) def command8ver1(self): localctx = scriptingLanguageParser.Command8ver1Context(self, self._ctx, self.state) self.enterRule(localctx, 144, self.RULE_command8ver1) try: self.enterOuterAlt(localctx, 1) self.state = 686 self.match(scriptingLanguageParser.INPUT) self.state = 687 self.match(scriptingLanguageParser.MESSAGE) self.state = 688 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command8ver2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command8ver2Context, self).__init__(parent, invokingState) self.parser = parser def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def ENTER(self): return self.getToken(scriptingLanguageParser.ENTER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command8ver2 def enterRule(self, listener): if hasattr(listener, "enterCommand8ver2"): listener.enterCommand8ver2(self) def exitRule(self, listener): if hasattr(listener, "exitCommand8ver2"): listener.exitCommand8ver2(self) def command8ver2(self): localctx = scriptingLanguageParser.Command8ver2Context(self, self._ctx, self.state) self.enterRule(localctx, 146, self.RULE_command8ver2) try: self.enterOuterAlt(localctx, 1) self.state = 690 self.match(scriptingLanguageParser.PRESS) self.state = 691 self.match(scriptingLanguageParser.ENTER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command8ver3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command8ver3Context, self).__init__(parent, invokingState) self.parser = parser def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def BACK(self): return self.getToken(scriptingLanguageParser.BACK, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command8ver3 def enterRule(self, listener): if hasattr(listener, "enterCommand8ver3"): listener.enterCommand8ver3(self) def exitRule(self, listener): if hasattr(listener, "exitCommand8ver3"): listener.exitCommand8ver3(self) def command8ver3(self): localctx = scriptingLanguageParser.Command8ver3Context(self, self._ctx, self.state) self.enterRule(localctx, 148, self.RULE_command8ver3) try: self.enterOuterAlt(localctx, 1) self.state = 693 self.match(scriptingLanguageParser.PRESS) self.state = 694 self.match(scriptingLanguageParser.BACK) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command8ver4Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command8ver4Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def UP(self): return self.getToken(scriptingLanguageParser.UP, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command8ver4 def enterRule(self, listener): if hasattr(listener, "enterCommand8ver4"): listener.enterCommand8ver4(self) def exitRule(self, listener): if hasattr(listener, "exitCommand8ver4"): listener.exitCommand8ver4(self) def command8ver4(self): localctx = scriptingLanguageParser.Command8ver4Context(self, self._ctx, self.state) self.enterRule(localctx, 150, self.RULE_command8ver4) try: self.enterOuterAlt(localctx, 1) self.state = 696 self.match(scriptingLanguageParser.SWIPE) self.state = 697 self.match(scriptingLanguageParser.UP) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Command8ver5Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.Command8ver5Context, self).__init__(parent, invokingState) self.parser = parser def SWIPE(self): return self.getToken(scriptingLanguageParser.SWIPE, 0) def DOWN(self): return self.getToken(scriptingLanguageParser.DOWN, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_command8ver5 def enterRule(self, listener): if hasattr(listener, "enterCommand8ver5"): listener.enterCommand8ver5(self) def exitRule(self, listener): if hasattr(listener, "exitCommand8ver5"): listener.exitCommand8ver5(self) def command8ver5(self): localctx = scriptingLanguageParser.Command8ver5Context(self, self._ctx, self.state) self.enterRule(localctx, 152, self.RULE_command8ver5) try: self.enterOuterAlt(localctx, 1) self.state = 699 self.match(scriptingLanguageParser.SWIPE) self.state = 700 self.match(scriptingLanguageParser.DOWN) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomClickContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomClickContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def coordinate(self): return self.getTypedRuleContext(scriptingLanguageParser.CoordinateContext,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomClick def enterRule(self, listener): if hasattr(listener, "enterCommandCustomClick"): listener.enterCommandCustomClick(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomClick"): listener.exitCommandCustomClick(self) def commandCustomClick(self): localctx = scriptingLanguageParser.CommandCustomClickContext(self, self._ctx, self.state) self.enterRule(localctx, 154, self.RULE_commandCustomClick) try: self.enterOuterAlt(localctx, 1) self.state = 702 self.match(scriptingLanguageParser.CUSTOM) self.state = 703 self.match(scriptingLanguageParser.CLICK) self.state = 704 self.coordinate() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomLongClickContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomLongClickContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def LONG(self): return self.getToken(scriptingLanguageParser.LONG, 0) def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def coordinate(self): return self.getTypedRuleContext(scriptingLanguageParser.CoordinateContext,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomLongClick def enterRule(self, listener): if hasattr(listener, "enterCommandCustomLongClick"): listener.enterCommandCustomLongClick(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomLongClick"): listener.exitCommandCustomLongClick(self) def commandCustomLongClick(self): localctx = scriptingLanguageParser.CommandCustomLongClickContext(self, self._ctx, self.state) self.enterRule(localctx, 156, self.RULE_commandCustomLongClick) try: self.enterOuterAlt(localctx, 1) self.state = 706 self.match(scriptingLanguageParser.CUSTOM) self.state = 707 self.match(scriptingLanguageParser.LONG) self.state = 708 self.match(scriptingLanguageParser.CLICK) self.state = 709 self.coordinate() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomDragContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomDragContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def DRAG(self): return self.getToken(scriptingLanguageParser.DRAG, 0) def FROM(self): return self.getToken(scriptingLanguageParser.FROM, 0) def coordinate(self, i=None): if i is None: return self.getTypedRuleContexts(scriptingLanguageParser.CoordinateContext) else: return self.getTypedRuleContext(scriptingLanguageParser.CoordinateContext,i) def TO(self): return self.getToken(scriptingLanguageParser.TO, 0) def DURATION(self): return self.getToken(scriptingLanguageParser.DURATION, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomDrag def enterRule(self, listener): if hasattr(listener, "enterCommandCustomDrag"): listener.enterCommandCustomDrag(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomDrag"): listener.exitCommandCustomDrag(self) def commandCustomDrag(self): localctx = scriptingLanguageParser.CommandCustomDragContext(self, self._ctx, self.state) self.enterRule(localctx, 158, self.RULE_commandCustomDrag) try: self.enterOuterAlt(localctx, 1) self.state = 711 self.match(scriptingLanguageParser.CUSTOM) self.state = 712 self.match(scriptingLanguageParser.DRAG) self.state = 713 self.match(scriptingLanguageParser.FROM) self.state = 714 self.coordinate() self.state = 715 self.match(scriptingLanguageParser.TO) self.state = 716 self.coordinate() self.state = 717 self.match(scriptingLanguageParser.DURATION) self.state = 718 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomTypeContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomTypeContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def TYPE(self): return self.getToken(scriptingLanguageParser.TYPE, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomType def enterRule(self, listener): if hasattr(listener, "enterCommandCustomType"): listener.enterCommandCustomType(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomType"): listener.exitCommandCustomType(self) def commandCustomType(self): localctx = scriptingLanguageParser.CommandCustomTypeContext(self, self._ctx, self.state) self.enterRule(localctx, 160, self.RULE_commandCustomType) try: self.enterOuterAlt(localctx, 1) self.state = 720 self.match(scriptingLanguageParser.CUSTOM) self.state = 721 self.match(scriptingLanguageParser.TYPE) self.state = 722 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomBackContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomBackContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def PRESS(self): return self.getToken(scriptingLanguageParser.PRESS, 0) def DEVICE(self): return self.getToken(scriptingLanguageParser.DEVICE, 0) def BACK(self): return self.getToken(scriptingLanguageParser.BACK, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomBack def enterRule(self, listener): if hasattr(listener, "enterCommandCustomBack"): listener.enterCommandCustomBack(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomBack"): listener.exitCommandCustomBack(self) def commandCustomBack(self): localctx = scriptingLanguageParser.CommandCustomBackContext(self, self._ctx, self.state) self.enterRule(localctx, 162, self.RULE_commandCustomBack) try: self.enterOuterAlt(localctx, 1) self.state = 724 self.match(scriptingLanguageParser.CUSTOM) self.state = 725 self.match(scriptingLanguageParser.PRESS) self.state = 726 self.match(scriptingLanguageParser.DEVICE) self.state = 727 self.match(scriptingLanguageParser.BACK) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomSleepContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomSleepContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def SLEEP(self): return self.getToken(scriptingLanguageParser.SLEEP, 0) def NUMBER(self): return self.getToken(scriptingLanguageParser.NUMBER, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomSleep def enterRule(self, listener): if hasattr(listener, "enterCommandCustomSleep"): listener.enterCommandCustomSleep(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomSleep"): listener.exitCommandCustomSleep(self) def commandCustomSleep(self): localctx = scriptingLanguageParser.CommandCustomSleepContext(self, self._ctx, self.state) self.enterRule(localctx, 164, self.RULE_commandCustomSleep) try: self.enterOuterAlt(localctx, 1) self.state = 729 self.match(scriptingLanguageParser.CUSTOM) self.state = 730 self.match(scriptingLanguageParser.SLEEP) self.state = 731 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomAssertTextContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomAssertTextContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def ASSERT(self): return self.getToken(scriptingLanguageParser.ASSERT, 0) def TEXT(self): return self.getToken(scriptingLanguageParser.TEXT, 0) def EQUALS(self): return self.getToken(scriptingLanguageParser.EQUALS, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomAssertText def enterRule(self, listener): if hasattr(listener, "enterCommandCustomAssertText"): listener.enterCommandCustomAssertText(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomAssertText"): listener.exitCommandCustomAssertText(self) def commandCustomAssertText(self): localctx = scriptingLanguageParser.CommandCustomAssertTextContext(self, self._ctx, self.state) self.enterRule(localctx, 166, self.RULE_commandCustomAssertText) try: self.enterOuterAlt(localctx, 1) self.state = 733 self.match(scriptingLanguageParser.CUSTOM) self.state = 734 self.match(scriptingLanguageParser.ASSERT) self.state = 735 self.match(scriptingLanguageParser.TEXT) self.state = 736 self.match(scriptingLanguageParser.EQUALS) self.state = 737 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandCustomClickTextContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CommandCustomClickTextContext, self).__init__(parent, invokingState) self.parser = parser def CUSTOM(self): return self.getToken(scriptingLanguageParser.CUSTOM, 0) def CLICK(self): return self.getToken(scriptingLanguageParser.CLICK, 0) def TEXT(self): return self.getToken(scriptingLanguageParser.TEXT, 0) def QUOTEDSTRING(self): return self.getToken(scriptingLanguageParser.QUOTEDSTRING, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_commandCustomClickText def enterRule(self, listener): if hasattr(listener, "enterCommandCustomClickText"): listener.enterCommandCustomClickText(self) def exitRule(self, listener): if hasattr(listener, "exitCommandCustomClickText"): listener.exitCommandCustomClickText(self) def commandCustomClickText(self): localctx = scriptingLanguageParser.CommandCustomClickTextContext(self, self._ctx, self.state) self.enterRule(localctx, 168, self.RULE_commandCustomClickText) try: self.enterOuterAlt(localctx, 1) self.state = 739 self.match(scriptingLanguageParser.CUSTOM) self.state = 740 self.match(scriptingLanguageParser.CLICK) self.state = 741 self.match(scriptingLanguageParser.TEXT) self.state = 742 self.match(scriptingLanguageParser.QUOTEDSTRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CoordinateContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.CoordinateContext, self).__init__(parent, invokingState) self.parser = parser def NUMBER(self, i=None): if i is None: return self.getTokens(scriptingLanguageParser.NUMBER) else: return self.getToken(scriptingLanguageParser.NUMBER, i) def getRuleIndex(self): return scriptingLanguageParser.RULE_coordinate def enterRule(self, listener): if hasattr(listener, "enterCoordinate"): listener.enterCoordinate(self) def exitRule(self, listener): if hasattr(listener, "exitCoordinate"): listener.exitCoordinate(self) def coordinate(self): localctx = scriptingLanguageParser.CoordinateContext(self, self._ctx, self.state) self.enterRule(localctx, 170, self.RULE_coordinate) try: self.enterOuterAlt(localctx, 1) self.state = 744 self.match(scriptingLanguageParser.NUMBER) self.state = 745 self.match(scriptingLanguageParser.NUMBER) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TestCustomContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.TestCustomContext, self).__init__(parent, invokingState) self.parser = parser def EXECUTE(self): return self.getToken(scriptingLanguageParser.EXECUTE, 0) def testSlot1(self): return self.getTypedRuleContext(scriptingLanguageParser.TestSlot1Context,0) def testSlot2(self): return self.getTypedRuleContext(scriptingLanguageParser.TestSlot2Context,0) def testSlot3(self): return self.getTypedRuleContext(scriptingLanguageParser.TestSlot3Context,0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testCustom def enterRule(self, listener): if hasattr(listener, "enterTestCustom"): listener.enterTestCustom(self) def exitRule(self, listener): if hasattr(listener, "exitTestCustom"): listener.exitTestCustom(self) def testCustom(self): localctx = scriptingLanguageParser.TestCustomContext(self, self._ctx, self.state) self.enterRule(localctx, 172, self.RULE_testCustom) try: self.enterOuterAlt(localctx, 1) self.state = 747 self.match(scriptingLanguageParser.EXECUTE) self.state = 751 self._errHandler.sync(self) token = self._input.LA(1) if token in [scriptingLanguageParser.TESTSLOT1]: self.state = 748 self.testSlot1() pass elif token in [scriptingLanguageParser.TESTSLOT2]: self.state = 749 self.testSlot2() pass elif token in [scriptingLanguageParser.TESTSLOT3]: self.state = 750 self.testSlot3() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TestSlot1Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.TestSlot1Context, self).__init__(parent, invokingState) self.parser = parser def TESTSLOT1(self): return self.getToken(scriptingLanguageParser.TESTSLOT1, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testSlot1 def enterRule(self, listener): if hasattr(listener, "enterTestSlot1"): listener.enterTestSlot1(self) def exitRule(self, listener): if hasattr(listener, "exitTestSlot1"): listener.exitTestSlot1(self) def testSlot1(self): localctx = scriptingLanguageParser.TestSlot1Context(self, self._ctx, self.state) self.enterRule(localctx, 174, self.RULE_testSlot1) try: self.enterOuterAlt(localctx, 1) self.state = 753 self.match(scriptingLanguageParser.TESTSLOT1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TestSlot2Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.TestSlot2Context, self).__init__(parent, invokingState) self.parser = parser def TESTSLOT2(self): return self.getToken(scriptingLanguageParser.TESTSLOT2, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testSlot2 def enterRule(self, listener): if hasattr(listener, "enterTestSlot2"): listener.enterTestSlot2(self) def exitRule(self, listener): if hasattr(listener, "exitTestSlot2"): listener.exitTestSlot2(self) def testSlot2(self): localctx = scriptingLanguageParser.TestSlot2Context(self, self._ctx, self.state) self.enterRule(localctx, 176, self.RULE_testSlot2) try: self.enterOuterAlt(localctx, 1) self.state = 755 self.match(scriptingLanguageParser.TESTSLOT2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TestSlot3Context(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(scriptingLanguageParser.TestSlot3Context, self).__init__(parent, invokingState) self.parser = parser def TESTSLOT3(self): return self.getToken(scriptingLanguageParser.TESTSLOT3, 0) def getRuleIndex(self): return scriptingLanguageParser.RULE_testSlot3 def enterRule(self, listener): if hasattr(listener, "enterTestSlot3"): listener.enterTestSlot3(self) def exitRule(self, listener): if hasattr(listener, "exitTestSlot3"): listener.exitTestSlot3(self) def testSlot3(self): localctx = scriptingLanguageParser.TestSlot3Context(self, self._ctx, self.state) self.enterRule(localctx, 178, self.RULE_testSlot3) try: self.enterOuterAlt(localctx, 1) self.state = 757 self.match(scriptingLanguageParser.TESTSLOT3) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx
{"/graphPlotter.py": ["/stateNode.py"]}
50,841
Eksoss/analise_num
refs/heads/master
/src/filters.py
import numpy as np class KZAFilter: def __init__(self, X): self.X = X.copy() self.shape = self.X.shape self.window = self.X.shape[0] self.Z = X.copy() self.D = None self.dD = None self.fD = None def calculate_D(self, q): expanded = np.concatenate((np.full((q, ) + self.shape[1:], np.nan), self.Z, np.full((q, ) + self.shape[1:], np.nan))) self.D = abs(expanded[2*q:] - expanded[:-2*q]) self.dD = np.concatenate((self.D[1:] - self.D[:-1], np.full((1, ) + self.shape[1:], np.nan))) self.fD = 1 - self.D/np.nanmax(self.D, axis=0) def moving_average(self, q): expanded = np.concatenate((np.full((q, ) + self.shape[1:], np.nan), self.Z, np.full((q,) + self.shape[1:], np.nan))) mean = np.zeros(self.shape, dtype=np.float32) base = np.zeros(self.shape, dtype=np.float32) for i in range(2*q + 1): mean = np.nansum([mean, expanded[i: self.window + i, :, :]], axis=0) base = np.nansum([base, expanded[i: self.window + i, :, :]*0 + 1], axis=0) self.Z[:] = mean / base def moving_average_extreme(self, q): expanded_x = np.concatenate((np.full((q, ) + self.shape[1:], np.nan), self.X, np.full((q,) + self.shape[1:], np.nan))) expanded = np.concatenate((np.full((q, ) + self.shape[1:], np.nan), self.Z, np.full((q,) + self.shape[1:], np.nan))) for i in range(self.window): mask = np.full((2*q + 1, ) + self.shape[1:], False) mask[q] = True # tail mask[:q, self.dD[i] > 0] = True mask_range = np.zeros(self.fD[i].shape) mask_range[self.dD[i] <= 0] = (self.fD[i][self.dD[i] <= 0]*q).astype(int) for j in range(q)[::-1]: mask[j][np.where(mask_range > 0)] = True mask_range -= 1 # head mask[q+1:, self.dD[i] < 0] = True mask_range = np.zeros(self.fD[i].shape) mask_range[self.dD[i] >= 0] = (self.fD[i][self.dD[i] >= 0]*q).astype(int) for j in range(q+1, 2*q+1): mask[j][np.where(mask_range > 0)] = True mask_range -= 1 self.Z[i] = np.nansum(expanded[i: i+2*q + 1] * mask.astype(int), axis=0)/np.nansum(mask.astype(int), axis=0) ​ def KZ(self, q, k): self.Z = self.X.copy() for i in range(k): self.moving_average(q) def KZA(self, q, k): self.KZ(q, k) for i in range(k): self.calculate_D(q) self.moving_average_extreme(q)
{"/examples.py": ["/src/integration.py", "/src/splines.py", "/src/interpolation.py"]}
50,842
Eksoss/analise_num
refs/heads/master
/src/splines.py
import numpy as np class ClampedCubicSpline: def __init__(self, x, y, **kwargs): self.x = np.array(x) self.y = np.array(y) self.n = self.x.size # [0, n] self.n1 = self.n - 1 # [0, n-1] self.coefs = np.zeros((self.n, 4), dtype=np.float64) self.coefs[:, 0] = self.y self.FPO = kwargs.get('FPO', 0) self.FPN = kwargs.get('FPN', 0) self.h = np.zeros(self.n1) self.mu = np.zeros(self.n1) self.l = np.zeros(self.n) self.z = np.zeros(self.n) self.alpha = np.zeros(self.n) def run(self): self.define_hi() self.define_a0_an() self.define_a() self.define_lmz0() self.define_lmz() self.define_lzcn() self.define_cbd() # step 1 def define_hi(self): self.h = self.x[1:] - self.x[:-1] # step 2 def define_a0_an(self): self.alpha[0] = 3 * (self.coefs[1, 0] - self.coefs[0, 0])/self.h[0] - 3 * self.FPO self.alpha[-1] = 3 * self.FPN - 3*(self.coefs[-1, 0] - self.coefs[-2, 0])/self.h[-1] # step 3 def define_a(self): self.alpha[1:-1] = 3/self.h[1:] * (self.coefs[2:, 0] - self.coefs[1:-1, 0])\ - 3/self.h[:-1] * (self.coefs[1:-1, 0] - self.coefs[:-2, 0]) # step 4 def define_lmz0(self): self.l[0] = 2 * self.h[0] self.mu[0] = 0.5 self.z[0] = self.alpha[0]/self.l[0] # step 5 def define_lmz(self): for i in range(1, self.n1): self.l[i] = 2 * (self.x[i + 1] - self.x[i - 1]) - self.h[i - 1] * self.mu[i - 1] self.mu[i] = self.h[i]/self.l[i] self.z[i] = (self.alpha[i] - self.h[i - 1]*self.z[i - 1])/self.l[i] # step 6 def define_lzcn(self): self.l[-1] = self.h[-1] * (2 - self.mu[-1]) self.z[-1] = (self.alpha[-1] - self.h[-1]*self.z[-2])/self.l[-1] self.coefs[-1, 2] = self.z[-1] # step 7 def define_cbd(self): for i in np.arange(self.n1)[::-1]: self.coefs[i, 2] = self.z[i] - self.mu[i] * self.coefs[i + 1, 2] self.coefs[i, 1] = (self.coefs[i + 1, 0] - self.coefs[i, 0])/self.h[i]\ - self.h[i] * (self.coefs[i + 1, 2] + 2 * self.coefs[i, 2])/3 self.coefs[i, 3] = (self.coefs[i + 1, 2] - self.coefs[i, 2])/(3 * self.h[i]) # step 8 def output(self): return self.coefs[:-1, :] def gen_function(self): coefs = self.output() intervals = lambda x: (self.n1 - np.argmax((self.x - x)[::-1] <= 0)).clip(0, self.n1 - 1) if x >= self.x.min() and x <= self.x.max() else None S = [] for coef, x0 in zip(coefs, self.x[:-1]): S.append([coef, x0]) def _(x): idx = intervals(x) if idx is None: return np.nan # print(idx) _vars = S[idx] powers = np.power(np.full(4, x) - np.full(4, _vars[1]), [0, 1, 2, 3]) res = _vars[0].dot(powers) return res _ = np.vectorize(_) return _ class NaturalCubicSpline: def __init__(self, x, y): self.x = np.array(x) self.y = np.array(y) self.n = self.x.size # [0, n] self.n1 = self.n - 1 # [0, n-1] self.coefs = np.zeros((self.n, 4), dtype=np.float64) self.h = None self.alpha = np.zeros(self.n1) self.coefs[:, 0] = self.y self.u = np.zeros(self.n) self.l = np.zeros(self.n) self.z = np.zeros(self.n) def run(self): self.define_h() self.define_alpha() self.define_luz0() self.define_luzi() self.define_luzn() self.define_cbd() def define_h(self): self.h = self.x[1:] - self.x[:-1] def define_alpha(self): self.alpha = 3/self.h[1:] * (self.coefs[2:, 0] - self.coefs[1:-1, 0]) - 3/self.h[:-1] * (self.coefs[1:-1, 0] - self.coefs[:-2, 0]) def define_luz0(self): self.l[0] = 1 self.u[0] = 0 self.z[0] = 0 def define_luzi(self): for i in range(1, self.n1): self.l[i] = 2*(self.x[i + 1] - self.x[i - 1]) - self.h[i - 1]*self.u[i - 1] self.u[i] = self.h[i]/self.l[i] self.z[i] = (self.alpha[i - 1] - self.h[i - 1]*self.z[i - 1])/self.l[i] def define_luzn(self): self.l[-1] = 1 self.z[-1] = 0 self.coefs[-1, 2] = 0 def define_cbd(self): for i in np.arange(self.n1)[::-1]: self.coefs[i, 2] = self.z[i] - self.u[i]*self.coefs[i + 1, 2] self.coefs[i, 1] = (self.coefs[i + 1, 0] - self.coefs[i , 0])/self.h[i] - self.h[i]*(self.coefs[i + 1, 2] + 2*self.coefs[i, 2])/3 self.coefs[i, 3] = (self.coefs[i + 1, 2] - self.coefs[i, 2])/(3 * self.h[i]) def output(self): return self.coefs[:-1, :] def gen_function(self): coefs = self.output() intervals = lambda x: (self.n1 - np.argmax((self.x - x)[::-1] <= 0)).clip(0, self.n1 - 1) if x >= self.x.min() and x <= self.x.max() else None S = [] for coef, x0 in zip(coefs, self.x[:-1]): S.append([coef, x0]) def _(x): idx = intervals(x) if idx is None: return np.nan _vars = S[idx] powers = np.power(np.full(4, x) - np.full(4, _vars[1]), [0, 1, 2, 3]) res = _vars[0].dot(powers) return res _ = np.vectorize(_) return _
{"/examples.py": ["/src/integration.py", "/src/splines.py", "/src/interpolation.py"]}
50,843
Eksoss/analise_num
refs/heads/master
/src/physical_object.py
# author Eksoss/chicoviana # from dataclasses import dataclass import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation @dataclass class Physx: position: np.ndarray # (m, m, m) speed: np.ndarray # (m/s, m/s, m/s) mass: float # kg @property def energy(self, ): return self.mass * np.power(self.speed, 2).sum() / 2 def apply_force(self, origin): self.speed += origin.force / self.mass def update(self, dt): self.position += self.speed * dt @dataclass class SpringProperties: # dunno if it's an abuse of properties fixed_point: np.ndarray free_point: np.ndarray neutral_length: float k: float @property def force(self, ): return - self.k * (self.length - self.neutral_length) * self.direction @property def direction(self, ): return (self.free_point - self.fixed_point) / self.length @property def length(self, ): return np.linalg.norm(self.free_point - self.fixed_point) class PointObject(Physx): def __init__(self, **kwargs): super().__init__(**kwargs) class Spring(SpringProperties): def __init__(self, **kwargs): super().__init__(**kwargs) @dataclass class GravityForce: # maybe it's a bad idea to make it this way acceleration: np.ndarray origin: PointObject @property def force(self, ): return self.acceleration * self.origin.mass mola = Spring(fixed_point=np.zeros(3), free_point=np.ones(3), neutral_length=1., k=20.) p1 = PointObject(position=np.array([0.5, 0., 0.]), speed=np.array([0., 0., 0.]), mass=10.) p1_gravity = GravityForce(acceleration=np.array([0., -9.8, 0.]), origin=p1) mola.free_point = p1.position p1.apply_force(mola) fig, ax = plt.subplots() def animate(i): plt.clf() p1.update(0.01) mola.free_point = p1.position p1.apply_force(mola) p1.apply_force(p1_gravity) p1.speed *= 0.98 plt.plot(*p1.position[:2], 'or', label='speed: %s'%np.array2string(p1.speed, formatter={'float': lambda x: "%.3f"%x})) plt.axis([-5., 5., -20., 5.]) plt.plot([0, p1.position[0]], [0, p1.position[1]], 'b', alpha=0.5, label='length: %.3fm'%mola.length) plt.legend() plt.tight_layout() return fig, ani = animation.FuncAnimation(fig, animate, frames=300, interval=5) # ani.save('test.gif') plt.show()
{"/examples.py": ["/src/integration.py", "/src/splines.py", "/src/interpolation.py"]}
50,844
Eksoss/analise_num
refs/heads/master
/src/linalg.py
import numpy as np class TridiagonalLinear: def __init__(self, A, b): self.A = A self.b = b self.n = self.b.size self.l = np.eye(self.n, dtype=np.float64) self.u = np.eye(self.n, dtype=np.float64) self.z = np.zeros(b.shape, dtype=np.float64) self.x = np.zeros(b.shape, dtype=np.float64) def run(self): self.define_luz() self.define_lluz() self.define_llz() self.define_x() def define_luz(self): self.l[0, 0] = self.A[0, 0] self.u[0, 1] = self.A[0, 1]/self.l[0, 0] self.z[0] = self.b[0]/self.l[0, 0] def define_lluz(self): for i in range(1, self.n - 1): self.l[i, i - 1] = self.A[i, i - 1] self.l[i, i] = self.A[i, i] - self.l[i, i - 1]*self.u[i - 1, i] self.u[i, i + 1] = self.A[i, i + 1]/self.l[i, i] self.z[i] = (self.b[i] - self.l[i, i - 1]*self.z[i - 1])/self.l[i, i] def define_llz(self): self.l[-1, -2] = self.A[-1, -2] self.l[-1, -1] = self.A[-1, -1] - self.l[-1, -2]*self.u[-2, -1] self.z[-1] = (self.b[-1] - self.l[-1, -2]*self.z[-2])/self.l[-1, -1] def define_x(self): self.x[-1] = self.z[-1] for i in np.arange(self.n - 1)[::-1]: self.x[i] = self.z[i] - self.u[i, i + 1]*self.x[i + 1] def output(self): return self.x def easy_way(self): return np.linalg.solve(self.A, self.b)
{"/examples.py": ["/src/integration.py", "/src/splines.py", "/src/interpolation.py"]}
50,845
Eksoss/analise_num
refs/heads/master
/src/interpolation.py
import numpy as np class BaseLagrange: def __init__(self, x, y): self.x = np.array(x) self.left, self.right = self.x.min(), self.x.max() self.y = np.array(y) self.integrity = False self.base = [] self.check_integrity() self.create_base() def check_integrity(self): if self.x.shape == self.y.shape: self.integrity = True def within(self, x): return x >= self.left and x <= self.right def create_base(self): """ Li = PROD[(x - xj)] per j!=i/ PROD[(xi - xj)] per j!=i """ self.base = lambda x: np.array([np.prod([x - xj for j, xj in enumerate(self.x) if i!=j])/\ np.prod([xi - xj for j, xj in enumerate(self.x) if i!=j])\ for i, xi in enumerate(self.x)]) def __call__(self, x): if not self.integrity: return np.nan if isinstance(x, (list, np.ndarray)): return np.array( [np.sum(self.y * self.base(xi)) if self.within(xi) else np.nan for xi in x] ) return np.sum(self.y * self.base(x))
{"/examples.py": ["/src/integration.py", "/src/splines.py", "/src/interpolation.py"]}
50,846
Eksoss/analise_num
refs/heads/master
/examples.py
import numpy as np from src.integration import Integrate f = lambda x: 3 + 3*x + 4*x**2 F = Integrate(f) a, b = 0, 4 print('\n### Simpson integration') print(F(a, b, method='simpson')) print('\n### Midpoint integration') print(F(a, b, method='midpoint')) print('\n### Trapezoidal integration') print(F(a, b, method='trapezoidal')) print('\n### Gauss Quadrature integration') print(F(a, b, method='gauss_quad')) from src.splines import ClampedCubicSpline, NaturalCubicSpline x = np.linspace(1, 5, 10) y = f(x) c_spl = ClampedCubicSpline(x, y) func_c_spl = c_spl.gen_function() print('\n### ClampedCubicSpline') print(func_c_spl(np.linspace(0, 6, 30))) n_spl = NaturalCubicSpline(x, y) func_n_spl = n_spl.gen_function() print('\n### NaturalCubicSpline') print(func_n_spl(np.linspace(0, 6, 30))) from src.interpolation import BaseLagrange base = BaseLagrange(x, y) print('\n### BaseLagrange') print(base(np.linspace(0, 6, 30)))
{"/examples.py": ["/src/integration.py", "/src/splines.py", "/src/interpolation.py"]}
50,847
Eksoss/analise_num
refs/heads/master
/src/integration.py
import numpy as np from scipy.special import roots_legendre, legendre class Integrate: def __init__(self, func): self.func = func self.a = None self.b = None self.n = None self.h = None self.X = None self.XI0 = None self.XI1 = None self.XI2 = None self.XI = None def validate(self): if self.a >= self.b: raise "a >= b" if not isinstance(self.n, int): print("n is not integer, modifying to int") self.n = int(self.n) self.validate() if self.n%2 != 0: self.n += 1 print("n is not even, using n = %d"%self.n) if (self.b - self.a)/self.n > 0.5: raise "invalid h, h is too big" def midpoint(self, a, b, n=10000): self.a = a self.b = b self.n = n + 2 self.validate() self.h = (b - a)/self.n self.X = np.linspace(self.a, self.b, self.n) self.XI1 = np.nansum(self.func(self.X[1::2])) self.XI = 2*self.h*self.XI1 return self.XI def trapezoidal(self, a, b, n=10000): self.a = a self.b = b self.n = n self.validate() self.h = (b - a)/self.n self.X = np.linspace(self.a, self.b, self.n)[1:-1] self.XI0 = self.func(a) + self.func(b) self.XI1 = np.nansum(self.func(self.X)) self.XI = self.h/2*(self.XI0 + 2*self.XI1) return self.XI def simpson(self, a, b, n=10000): self.a = a self.b = b self.n = n self.validate() self.h = (b - a)/self.n self.X = np.linspace(self.a, self.b, self.n)[1:-1] self.XI0 = self.func(a) + self.func(b) self.XI1 = np.nansum(self.func(self.X[::2])) # index 0 -> i = 1 self.XI2 = np.nansum(self.func(self.X[1::2])) # index 1 -> i = 2 self.XI = self.h*(self.XI0 + 2*self.XI2 + 4*self.XI1)/3 return self.XI def gauss_quad(self, a, b, n=5): xi, ci = roots_legendre(n) local_func = lambda x: self.func(((b - a)*x + (b + a))/2) * (b - a)/2 return local_func(xi).dot(ci) # integration = <f(roots), weights> def __call__(self, a, b, n=None, method='simpson'): try: args = (n, ) if n is not None else () return getattr(self, method)(a, b, *args) except: raise 'invalid method %s'%method
{"/examples.py": ["/src/integration.py", "/src/splines.py", "/src/interpolation.py"]}
50,850
wulfebw/automotive_behavior_inference
refs/heads/master
/abi/models/rnnvae.py
import collections import numpy as np import os import sys import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector import abi.core.rnn_utils as rnn_utils import abi.misc.tf_utils as tf_utils import abi.misc.utils as utils class RNNVAE(object): def __init__( self, max_len, obs_dim, act_dim, batch_size, dropout_keep_prob=1., enc_hidden_dim=64, z_dim=32, dec_hidden_dim=64, kl_initial=0.0, kl_final=1.0, kl_steps=10000, kl_loss_min=.2, learning_rate=5e-4, grad_clip=1., tile_z=True, n_encoding_batches=2): self.max_len = max_len self.obs_dim = obs_dim self.act_dim = act_dim self.batch_size = batch_size self.dropout_keep_prob = dropout_keep_prob self.enc_hidden_dim = enc_hidden_dim self.z_dim = z_dim self.dec_hidden_dim = dec_hidden_dim self.kl_initial = kl_initial self.kl_final = kl_final self.kl_steps = kl_steps self.kl_loss_min = kl_loss_min self.learning_rate = learning_rate self.grad_clip = grad_clip self.tile_z = tile_z self.n_encoding_batches = n_encoding_batches self._build_model() def _build_model(self): self._build_placeholders() self._build_perception() self._build_encoder() self._build_decoder() self._build_loss() self._build_train_op() self._build_summary_op() def _build_placeholders(self): self.obs = tf.placeholder(tf.float32, (self.batch_size, self.max_len, self.obs_dim), 'obs') self.act = tf.placeholder(tf.float32, (self.batch_size, self.max_len, self.act_dim), 'act') self.lengths = tf.placeholder(tf.int32, (self.batch_size,), 'lengths') self.sequence_mask = tf.sequence_mask(self.lengths, maxlen=self.max_len, dtype=tf.float32) self.dropout_keep_prob_ph = tf.placeholder_with_default(self.dropout_keep_prob, (), 'dropout_keep_prob') self.global_step = tf.Variable(0, trainable=False, name='global_step') def _build_perception(self): self.enc_inputs = tf.concat((self.obs, self.act), axis=-1) self.dec_inputs = self.obs def _build_encoder(self): self.enc_cell_fw = rnn_utils._build_recurrent_cell(self.enc_hidden_dim, self.dropout_keep_prob_ph) self.enc_cell_bw = rnn_utils._build_recurrent_cell(self.enc_hidden_dim, self.dropout_keep_prob_ph) # inputs is assumed to be padded at the start with a <start> token or state # in the case of continuous values, probably just zeros # so for _encoding_ we ignore this padding outputs, states = tf.nn.bidirectional_dynamic_rnn( self.enc_cell_fw, self.enc_cell_bw, inputs=self.enc_inputs, sequence_length=self.lengths, dtype=tf.float32, time_major=False ) # since the inputs are zero-padded, we can't just use the outputs # because the invalid timesteps will be zeros # instead we manually extract the last hidden states for each sample # in the batch and use those to define the posterior hidden_fw = self.enc_cell_fw.get_output(states[0]) hidden_bw = self.enc_cell_bw.get_output(states[1]) hidden = tf.concat((hidden_fw, hidden_bw), axis=1) # output the parameters of a diagonal gaussian from which to sample # the z value self.z_mean = tf.contrib.layers.fully_connected( hidden, self.z_dim, activation_fn=None ) self.z_logvar = tf.contrib.layers.fully_connected( hidden, self.z_dim, activation_fn=None ) self.z_sigma = tf.exp(self.z_logvar / 2.) # sample z noise = tf.random_normal((self.batch_size, self.z_dim), 0.0, 1.0) self.z = self.z_mean + self.z_sigma * noise def _build_decoder(self): self.dec_cell = rnn_utils._build_recurrent_cell(self.dec_hidden_dim, self.dropout_keep_prob_ph) # the initial state of the rnn cells is a function of z as well # tanh because we want the values to be small self.initial_state = tf.nn.tanh(tf.contrib.layers.fully_connected( self.z, self.dec_cell.input_size * 2, activation_fn=None )) # we optionally tile the z value, concatenating to each timestep input # the reason for this is that it reduces the burden placed on the # decoder hidden state and further encourages usage of the latent var if self.tile_z: tile_z = tf.reshape(self.z, (self.batch_size, 1, self.z_dim)) tile_z = tf.tile(tile_z, (1, self.max_len, 1)) self.dec_inputs = tf.concat((self.dec_inputs, tile_z), axis=2) outputs, states = tf.nn.dynamic_rnn( self.dec_cell, inputs=self.dec_inputs, sequence_length=self.lengths, initial_state=self.initial_state, dtype=tf.float32, time_major=False ) # map the outputs to mean and logvar of gaussian over actions act_sequence_mask = tf.reshape(self.sequence_mask, (self.batch_size, self.max_len, 1)) epsilon = 1e-8 outputs = tf.reshape(outputs, (-1, self.dec_cell.output_size)) act_mean = tf.contrib.layers.fully_connected( outputs, self.act_dim, activation_fn=None ) self.act_mean = tf.reshape(act_mean, (self.batch_size, self.max_len, self.act_dim)) self.act_mean *= act_sequence_mask act_logvar = tf.contrib.layers.fully_connected( outputs, self.act_dim, activation_fn=None ) self.act_logvar = tf.reshape(act_logvar, (self.batch_size, self.max_len, self.act_dim)) self.act_logvar *= act_sequence_mask + epsilon self.act_sigma = tf.exp(self.act_logvar / 2.) self.act_sigma *= act_sequence_mask + epsilon def _build_loss(self): # kl loss # this measures the kl between the posterior distribution output from # the encoder over z, and the prior of z which we choose as a unit gaussian self.kl_loss = -0.5 * tf.reduce_mean( (1 + self.z_logvar - tf.square(self.z_mean) - tf.exp(self.z_logvar))) self.kl_loss = tf.maximum(self.kl_loss, self.kl_loss_min) # gradually increase the weight of the kl loss with a coefficient # we do this because there's no explicit reason why the model should # use the z value (i.e., nothing in the objective encourages this) # so by starting with a small loss value for "using" the z (i.e, outputting # a posterior distribution over z quite different from a unit gaussian) # the network basically becomes reliant on the z value, and then due to # the optimization being locally optimal and other factors the network # continues to use the z values in informing outputs self.kl_weight = tf.train.polynomial_decay( self.kl_initial, self.global_step, self.kl_steps, end_learning_rate=self.kl_final, power=2.0, name='kl_weight' ) # reconstruction loss # output mean and sigma of a gaussian for the actions # and compute reconstruction loss as the -log prob of true values dist = tf.contrib.distributions.MultivariateNormalDiag(self.act_mean, self.act_sigma) data_loss = -dist.log_prob(self.act) # can't remember how many times I've messed this part up # at this point, the data_loss has shape (batch_size, max_len) # a lot of the values of this array are invalid, though, because they # correspond to padded values, so we have to mask them out data_loss = self.sequence_mask * data_loss # then we want to average over the timesteps of each sample # since values are invalid, we can't just take the mean # we have to sum in order to ignore the zeros, and then divide by the # lengths to get the correct average data_loss = tf.reduce_sum(data_loss, axis=1) / tf.cast(self.lengths, tf.float32) # then finally average over the batch self.data_loss = tf.reduce_mean(data_loss) self.loss = self.data_loss + self.kl_weight * self.kl_loss # summaries tf.summary.scalar('loss', self.loss) tf.summary.scalar('data_loss', self.data_loss) tf.summary.scalar('kl_loss', self.kl_loss) tf.summary.scalar('kl_weight', self.kl_weight) def _build_train_op(self): self.var_list = tf.trainable_variables() optimizer = tf.train.AdamOptimizer(self.learning_rate) # compute gradients, then clip them because otherwise they'll tend # to explode grads_vars = optimizer.compute_gradients(self.loss, self.var_list) clipped_grads_vars = [(tf.clip_by_value(g, -self.grad_clip, self.grad_clip), v) for (g,v) in grads_vars] self.train_op = optimizer.apply_gradients(clipped_grads_vars, global_step=self.global_step) # summaries tf.summary.scalar('grads_global_norm', tf.global_norm([g for (g,_) in grads_vars])) tf.summary.scalar('clipped_grads_global_norm', tf.global_norm([g for (g,_) in clipped_grads_vars])) tf.summary.scalar('vars_global_norm', tf.global_norm(self.var_list)) tf.summary.scalar('learning_rate', self.learning_rate) def _build_summary_op(self): self.summary_op = tf.summary.merge_all() # embeddings variable used for visualization in tensorboard n_samples = self.batch_size * self.n_encoding_batches self.encoding_ph = tf.placeholder(tf.float32, (n_samples, self.z_dim), 'encodings') self.encoding = tf.Variable( tf.zeros((n_samples, self.z_dim), dtype=tf.float32), trainable=False, dtype=tf.float32, name='encoding' ) self.assign_encoding = tf.assign(self.encoding, self.encoding_ph) def _train_batch(self, batch, info, writer=None, train=True): outputs = [self.global_step, self.summary_op, self.data_loss, self.kl_loss] if train: outputs += [self.train_op] feed = { self.obs: batch['obs'], self.act: batch['act'], self.lengths: batch['lengths'], self.dropout_keep_prob_ph: self.dropout_keep_prob if train else 1. } sess = tf.get_default_session() fetched = sess.run(outputs, feed_dict=feed) if train: step, summary, data_loss, kl_loss, _ = fetched else: step, summary, data_loss, kl_loss = fetched if writer is not None: writer.add_summary(summary, step) info['data_loss'] += data_loss info['kl_loss'] += kl_loss info['itr'] += 1 def _report(self, info, name, epoch, n_epochs, batch, n_batches): msg = '\r{} epoch: {} / {} batch: {} / {}'.format( name, epoch+1, n_epochs, batch+1, n_batches) keys = sorted(info.keys()) for k in keys: if k != 'itr': msg += ' {}: {:.5f} '.format(k, info[k] / info['itr']) sys.stdout.write(msg) def _validate(self, dataset, writer, epoch, name): if writer is None: return batch = dataset.sample(self.batch_size * self.n_encoding_batches) info = self.reconstruct(batch['obs'], batch['act'], batch['lengths']) summary = tf_utils.scatter_encodings_summary(info['mean'], name) writer.add_summary(summary, epoch) # encodings only for training if name == 'val': return # assign encodings as well # this does only one of training or validation, whichever comes last # before saving, which is validation, provided validation is performed sess = tf.get_default_session() sess.run(self.assign_encoding, feed_dict={self.encoding_ph: info['mean']}) # write the metadata file as well logdir = writer.get_logdir() filepath = os.path.join(logdir, 'metadata.tsv') utils.write_metadata(filepath, batch['metadata'], batch['meta_labels']) config = projector.ProjectorConfig() embed = config.embeddings.add() embed.tensor_name = self.encoding.name embed.metadata_path = 'metadata.tsv' projector.visualize_embeddings(writer, config) def _save(self, saver, writer, epoch): if saver is not None and writer is not None: save_dir = writer.get_logdir() sess = tf.get_default_session() filepath = os.path.join(save_dir, 'chkpt_{}'.format(epoch)) saver.save(sess, filepath) def train( self, dataset, val_dataset=None, n_epochs=100, writer=None, val_writer=None, verbose=True, saver=None): for epoch in range(n_epochs): train_info = collections.defaultdict(float) for bidx, batch in enumerate(dataset.batches()): self._train_batch(batch, train_info, writer) self._report(train_info, 'train', epoch, n_epochs, bidx, dataset.n_batches) self._validate(dataset, writer, epoch, 'train') if val_dataset is not None: val_info = collections.defaultdict(float) for bidx, batch in enumerate(val_dataset.batches()): self._train_batch(batch, val_info, val_writer, train=False) self._report(val_info, 'val', epoch, n_epochs, bidx, val_dataset.n_batches) self._validate(val_dataset, val_writer, epoch, 'val') self._save(saver, writer, epoch) def reconstruct(self, obs, act, lengths): # setup sess = tf.get_default_session() bs = self.batch_size n_samples = len(obs) n_batches = utils.compute_n_batches(n_samples, bs) # allocate return containers z = np.zeros((n_samples, self.z_dim)) mean = np.zeros((n_samples, self.z_dim)) sigma = np.zeros((n_samples, self.z_dim)) act_mean = np.zeros((n_samples, self.max_len, self.act_dim)) act_sigma = np.zeros((n_samples, self.max_len, self.act_dim)) data_loss = 0 kl_loss = 0 # formulate outputs outputs = [ self.z, self.z_mean, self.z_sigma, self.act_mean, self.act_sigma, self.data_loss, self.kl_loss ] # run the batches for bidx in range(n_batches): idxs = utils.compute_batch_idxs(bidx * bs, bs, n_samples) feed = { self.obs: obs[idxs], self.act: act[idxs], self.lengths: lengths[idxs] } fetched = sess.run(outputs, feed_dict=feed) # unpack z[idxs] = fetched[0] mean[idxs] = fetched[1] sigma[idxs] = fetched[2] act_mean[idxs] = fetched[3] act_sigma[idxs] = fetched[4] data_loss += fetched[5] kl_loss += fetched[6] # return the relevant info return dict( z=z, mean=mean, sigma=sigma, act_mean=act_mean, act_sigma=act_sigma, data_loss=data_loss, kl_loss=kl_loss ) def get_param_values(self): sess = tf.get_default_session() return [sess.run(v) for v in self.var_list] def set_param_values(self, values): assign = tf.group(*[tf.assign(var, val) for (var, val) in zip(self.var_list, values)]) sess = tf.get_default_session() sess.run(assign) def save_params(self, filepath): values = self.get_param_values() np.save(filepath, values) def load_params(self, filepath): values = np.load(filepath).item() self.set_param_values(values)
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,851
wulfebw/automotive_behavior_inference
refs/heads/master
/abi/core/rnn_utils.py
import abi.core.rnn_cells as rnn_cells def _build_recurrent_cell(hidden_dim, dropout_keep_prob): return rnn_cells.LayerNormLSTMCell( hidden_dim, use_recurrent_dropout=True, dropout_keep_prob=dropout_keep_prob )
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,852
wulfebw/automotive_behavior_inference
refs/heads/master
/abi/misc/dataset.py
import numpy as np from abi.misc.utils import compute_n_batches, compute_batch_idxs class Dataset(object): def __init__( self, obs, act, lengths, batch_size=100, shuffle=True, metadata=None, meta_labels=None): self.obs = obs self.act = act self.lengths = lengths self.batch_size = batch_size self.shuffle = shuffle self.metadata = metadata self.meta_labels = meta_labels self.n_samples = len(obs) self.n_batches = compute_n_batches(self.n_samples, self.batch_size) def sample(self, n_samples=None): n_samples = self.batch_size if n_samples is None else n_samples idxs = np.random.randint(0, self.n_samples, n_samples) if self.metadata is not None: metadata = self.metadata[idxs] else: metadata = None return dict( obs=self.obs[idxs], act=self.act[idxs], lengths=self.lengths[idxs], metadata=metadata, meta_labels=self.meta_labels ) def _shuffle(self): if self.shuffle: idxs = np.random.permutation(self.n_samples) self.obs = self.obs[idxs] self.act = self.act[idxs] self.lengths = self.lengths[idxs] if self.metadata is not None: self.metadata = self.metadata[idxs] def batches(self): self._shuffle() for bidx in range(self.n_batches): start = bidx * self.batch_size idxs = compute_batch_idxs(start, self.batch_size, self.n_samples) yield dict( obs=self.obs[idxs], act=self.act[idxs], lengths=self.lengths[idxs] )
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,853
wulfebw/automotive_behavior_inference
refs/heads/master
/abi/misc/utils.py
import csv import h5py import numpy as np def compute_n_batches(n_samples, batch_size): n_batches = n_samples // batch_size if n_samples % batch_size != 0: n_batches += 1 return n_batches def compute_batch_idxs(start, batch_size, size, fill='random'): if start >= size: return list(np.random.randint(low=0, high=size, size=batch_size)) end = start + batch_size if end <= size: return list(range(start, end)) else: base_idxs = list(range(start, size)) if fill == 'none': return base_idxs elif fill == 'random': remainder = end - size idxs = list(np.random.randint(low=0, high=size, size=remainder)) return base_idxs + idxs else: raise ValueError('invalid fill: {}'.format(fill)) def compute_lengths(arr): sums = np.sum(np.array(arr), axis=2) lengths = [] for sample in sums: zero_idxs = np.where(sample == 0.)[0] if len(zero_idxs) == 0: lengths.append(len(sample)) else: lengths.append(zero_idxs[0]) return np.array(lengths) def write_metadata(filepath, data, labels): with open(filepath, 'w') as outfile: writer = csv.writer(outfile, delimiter='\t') writer.writerow(labels) writer.writerows(data) def normalize(x, lengths): # bit complicated due to variables lengths # compute mean by summing over length and dividing by length # then mean over samples mean = np.mean(np.sum(x, 1) / lengths.reshape(-1,1), 0) x = x - mean # at this point the mean of each feature is 0 # so the variance is just E[X^2], std = sqrt of that std = np.sqrt(np.mean(np.sum(x ** 2, 1) / lengths.reshape(-1,1), 0)) + 1e-8 x = x / std # set everything after the length of the value back to zero for i, l in enumerate(lengths): x[i, l:] = 0 return dict(x=x, mean=mean, std=std) def apply_normalize(x, mean, std, lengths): x = (x - mean) / std for (i, l) in enumerate(lengths): x[i, l:] = 0 return x def prepend_timeseries_zero(x): return np.concatenate((np.zeros((x.shape[0], 1, x.shape[2])), x), axis=1) def load_x_feature_names(filepath, mode='artificial'): f = h5py.File(filepath, 'r') if mode == 'artificial': x = f['risk/features'] feature_names = f['risk'].attrs['feature_names'] elif mode == 'ngsim': x = np.concatenate([f['{}'.format(i)] for i in range(1,6+1)]) feature_names = f.attrs['feature_names'] return x, feature_names def load_metadata(filepath, mode='ngsim', obs_keys=None): f = h5py.File(filepath, 'r') metadata, meta_labels = None, None if mode == 'ngsim': traj = [] for i in range(1, 6+1): traj.extend([i] * len(f['{}'.format(i)])) feature_names = f.attrs['feature_names'] idxs = [i for (i,n) in enumerate(feature_names) if n in obs_keys] obs_keys = feature_names[idxs] x = np.concatenate([f['{}'.format(i)] for i in range(1,6+1)]) x = x[:,:,idxs] lengths = compute_lengths(x) feature_means = [] for i, l in enumerate(lengths): sample_features = x[i,:l] feature_means.append(x[i,:l].mean(0)) n_meta = len(obs_keys) + 2 metadata = np.zeros((len(traj), n_meta)) metadata[:,0] = traj metadata[:,1] = lengths metadata[:,2:] = feature_means meta_labels = ['traj', 'traj_length'] + list(obs_keys) return metadata, meta_labels def load_data( filepath, obs_keys=[ 'velocity', 'jerk', 'timegap', 'time_to_collision', 'lidar_1', 'lidar_2', 'rangerate_lidar_1', 'rangerate_lidar_2' ], act_keys=[ 'accel', ], debug_size=None, y_key='beh_lon_T', y_1_val=1., load_y=True, train_split=.8, mode='artificial', min_length=0, normalize_data=True, shuffle=False): # loading varies based on dataset type x, feature_names = load_x_feature_names(filepath, mode) # load metadata metadata, meta_labels = load_metadata(filepath, mode, obs_keys) # optionally keep it to a reasonable size if debug_size is not None: x = x[:debug_size] metadata = metadata[:debug_size] if shuffle: idxs = np.random.permutation(len(x)) x = x[idxs] metadata = metadata[idxs] # compute lengths of the samples before anything else b/c this is fragile lengths = compute_lengths(x) # only keep samples with length > min_length valid_idxs = np.where(lengths > min_length)[0] x = x[valid_idxs] lengths = lengths[valid_idxs] metadata = metadata[valid_idxs] # y might not exist, so only laod it optionally if load_y: y_idx = np.where(feature_names == y_key)[0] y = np.zeros(len(x)) one_idxs = np.where(x[:,-1,y_idx] == y_1_val)[0] y[one_idxs] = 1 else: y = None # subselect relevant keys obs_idxs = [i for (i,n) in enumerate(feature_names) if n in obs_keys] obs = x[:,:,obs_idxs] act_idxs = [i for (i,n) in enumerate(feature_names) if n in act_keys] act = x[:,:,act_idxs] # train val split tidx = int(train_split * len(obs)) # val val_obs = obs[tidx:] val_act = act[tidx:] val_lengths = lengths[tidx:] val_metadata = metadata[tidx:] # train obs = obs[:tidx] act = act[:tidx] lengths = lengths[:tidx] metadata = metadata[:tidx] # normalize if normalize_data: info = normalize(obs, lengths) obs = info['x'] val_obs = apply_normalize(val_obs, info['mean'], info['std'], val_lengths) info = normalize(act, lengths) act = info['x'] val_act = apply_normalize(val_act, info['mean'], info['std'], val_lengths) if load_y: val_y = y[tidx:] y = y[:tidx] else: val_y = None # extract some common useful quantities n_samples, max_len, obs_dim = obs.shape act_dim = act.shape[-1] return dict( obs=obs, act=act, y=y, obs_keys=obs_keys, act_keys=act_keys, lengths=lengths, val_obs=val_obs, val_act=val_act, val_lengths=val_lengths, val_y=val_y, max_len=max_len, obs_dim=obs_dim, act_dim=act_dim, metadata=metadata, val_metadata=val_metadata, meta_labels=meta_labels )
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,854
wulfebw/automotive_behavior_inference
refs/heads/master
/tests/test_cnnrnnvae.py
import numpy as np import tensorflow as tf import unittest from abi.misc.dataset import Dataset from abi.models.cnnrnnvae import CNNRNNVAE class TestCNNRNNVAE(unittest.TestCase): def setUp(self): # reset graph before each test case tf.reset_default_graph() def test_rnn_vae_simple(self): # build model max_len = 5 obs_h = 32 obs_w = 32 obs_c = 1 act_dim = 2 z_dim = 2 batch_size = 2 kl_final = 0.0 kl_initial = 0.0 model = CNNRNNVAE( max_len, obs_h, obs_w, obs_c, act_dim, batch_size, n_percept_layers=2, n_percept_filters=(16,16), z_dim=z_dim, kl_steps=100, kl_final=kl_final, kl_initial=kl_initial ) # generate some data n_samples = batch_size obs = np.zeros((n_samples, max_len, obs_h, obs_w, obs_c)) obs[:n_samples//2,:,:obs_h//2, :obs_w//2] = 1 obs[n_samples//2:,:,obs_h//2:, obs_w//2:] = 1 act = np.ones((n_samples, max_len, act_dim)) act[:n_samples//2] *= -1 lengths = np.array([max_len] * n_samples) dataset = Dataset(obs, act, lengths, batch_size, shuffle=False) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) model.train(dataset, n_epochs=500, verbose=True) info = model.reconstruct(obs, act, lengths) self.assertTrue(info['data_loss'] < -2) if __name__ == '__main__': unittest.main()
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,855
wulfebw/automotive_behavior_inference
refs/heads/master
/tests/test_dataset.py
import numpy as np import unittest from abi.misc.dataset import Dataset class TestDataset(unittest.TestCase): def test_batches(self): obs = np.arange(3*2*1).reshape((3,2,1)) act = np.arange(3*2*1).reshape((3,2,1)) lengths = np.arange(3) dataset = Dataset(obs, act, lengths, batch_size=2, shuffle=False) batches = list(dataset.batches()) np.testing.assert_array_equal(batches[0]['lengths'], lengths[:2]) np.testing.assert_array_equal(batches[0]['obs'], obs[:2]) np.testing.assert_array_equal(batches[0]['act'], act[:2]) np.testing.assert_array_equal(batches[1]['lengths'][0], lengths[2]) np.testing.assert_array_equal(batches[1]['obs'][0], obs[2]) np.testing.assert_array_equal(batches[1]['act'][0], act[2]) if __name__ == '__main__': unittest.main()
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,856
wulfebw/automotive_behavior_inference
refs/heads/master
/setup.py
from setuptools import setup setup(name='automotive_behavior_inference', version='0.1', description='inferring automotive driving behavior', author='Blake Wulfe', author_email='blake.w.wulfe@gmail.com', license='MIT', packages=['abi'], zip_safe=False, install_requires=[ 'numpy', 'tensorflow', ])
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,857
wulfebw/automotive_behavior_inference
refs/heads/master
/abi/models/cnnrnnvae.py
import tensorflow as tf from abi.models.rnnvae import RNNVAE class CNNRNNVAE(RNNVAE): def __init__( self, max_len, obs_h, obs_w, obs_c, act_dim, batch_size, n_percept_layers=4, n_percept_filters=(32,64,128,128), **kwargs): self.obs_h = obs_h self.obs_w = obs_w self.obs_c = obs_c self.n_percept_layers = n_percept_layers self.n_percept_filters = n_percept_filters obs_dim = 0 # not used super(CNNRNNVAE, self).__init__(max_len, obs_dim, act_dim, batch_size, **kwargs) def _build_perception(self): self.obs = tf.placeholder( tf.float32, (self.batch_size, self.max_len, self.obs_h, self.obs_w, self.obs_c), 'obs' ) hidden = tf.reshape(self.obs, (self.batch_size * self.max_len, self.obs_h, self.obs_w, self.obs_c)) for i in range(self.n_percept_layers): hidden = tf.layers.conv2d( hidden, filters=self.n_percept_filters[i], kernel_size=3, strides=(2,2), activation=tf.nn.relu, bias_initializer=tf.constant_initializer(0.1)) hidden = tf.nn.dropout(hidden, self.dropout_keep_prob_ph) self.dec_inputs = tf.reshape(hidden, (self.batch_size, self.max_len, -1)) self.enc_inputs = tf.concat((self.dec_inputs, self.act), axis=-1)
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,858
wulfebw/automotive_behavior_inference
refs/heads/master
/tests/test_rnnvae.py
import numpy as np import tensorflow as tf import unittest from abi.misc.dataset import Dataset from abi.models.rnnvae import RNNVAE class TestRNNVAE(unittest.TestCase): def setUp(self): # reset graph before each test case tf.reset_default_graph() def test_rnn_vae_simple(self): # build model max_len = 5 obs_dim = 1 act_dim = 2 z_dim = 2 batch_size = 2 kl_final = 0.0 kl_initial = 0.0 model = RNNVAE( max_len, obs_dim, act_dim, batch_size, z_dim=z_dim, kl_steps=100, kl_final=kl_final, kl_initial=kl_initial ) # generate some data # z is the latent variable # act is a deterministic function of z # obs is zeros # thus latent space has to be used n_samples = batch_size z = np.random.randn(n_samples, act_dim) obs = np.zeros((n_samples, max_len, obs_dim)) act = np.ones((n_samples, max_len, act_dim)) * z.reshape(n_samples, 1, act_dim) lengths = np.array([max_len, 3]) dataset = Dataset(obs, act, lengths, batch_size, shuffle=False) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) model.train(dataset, n_epochs=500, verbose=True) info = model.reconstruct(obs, act, lengths) self.assertTrue(info['data_loss'] < -2) def test_get_set_param_values(self): with tf.Session() as sess: model = RNNVAE(5, 2, 2, 10) sess.run(tf.global_variables_initializer()) params = model.get_param_values() init_sum = np.sum([np.sum(p) for p in params]) params = [p * 0 for p in params] model.set_param_values(params) new_params = model.get_param_values() new_sum = np.sum([np.sum(p) for p in new_params]) orig_shapes = [np.shape(p) for p in params] new_shapes = [np.shape(p) for p in new_params] np.testing.assert_array_equal(orig_shapes, new_shapes) self.assertNotEqual(init_sum, new_sum) self.assertEqual(new_sum, 0.) @unittest.skipIf(__name__ != '__main__', 'run this test directly') def test_rnn_vae_plot(self): # build model max_len = 5 obs_dim = 1 act_dim = 2 z_dim = 2 batch_size = 100 model = RNNVAE( max_len, obs_dim, act_dim, batch_size, z_dim=z_dim, kl_steps=100 ) # generate some data # z is the latent variable # act is a deterministic function of z # obs is zeros # thus latent space has to be used n_samples = 1000 z = np.random.randn(n_samples, act_dim) obs = np.zeros((n_samples, max_len, obs_dim)) act = np.ones((n_samples, max_len, act_dim)) * z.reshape(n_samples, 1, act_dim) lengths = np.random.randint(2, max_len, n_samples) dataset = Dataset(obs, act, lengths, batch_size, shuffle=False) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) model.train(dataset, n_epochs=20, verbose=True) info = model.reconstruct(obs, act, lengths) plot = True if plot: import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt plt.subplot(1,2,1) plt.scatter(act[:,-1,0], act[:,-1,1], c=z.sum(1) / act_dim) plt.subplot(1,2,2) plt.scatter(act[:,-1,0], act[:,-1,1], c=info['mean'].sum(1) / act_dim) plt.show() if __name__ == '__main__': unittest.main()
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,859
wulfebw/automotive_behavior_inference
refs/heads/master
/scripts/ngsim/train_rnnvae_ngsim.py
import h5py import numpy as np import tensorflow as tf from abi.misc.dataset import Dataset from abi.misc.utils import load_data from abi.models.rnnvae import RNNVAE if __name__ == '__main__': obs_keys = [ 'relative_offset', 'relative_heading', 'velocity', 'length', 'width', 'lane_curvature', 'markerdist_left', 'markerdist_right', 'jerk', 'angular_rate_frenet', 'timegap', 'time_to_collision', 'is_colliding', 'out_of_lane', 'negative_velocity' ] nbeams = 16 obs_keys += ['lidar_{}'.format(i) for i in range(1, nbeams+1)] obs_keys += ['rangerate_lidar_{}'.format(i) for i in range(1, nbeams+1)] act_keys = ['accel', 'turn_rate_frenet'] data = load_data( filepath='../../data/trajectories/ngsim.h5', debug_size=None, mode='ngsim', min_length=20, obs_keys=obs_keys, act_keys=act_keys, load_y=False, shuffle=True ) obs = data['obs'] act = data['act'] lengths = data['lengths'] obs_keys = data['obs_keys'] act_keys = data['act_keys'] max_len = data['max_len'] obs_dim = data['obs_dim'] act_dim = data['act_dim'] val_obs, val_act, val_lengths, val_y = data['val_obs'], data['val_act'], data['val_lengths'], data['val_y'] batch_size = 200 dataset = Dataset( np.copy(obs), np.copy(act), np.copy(lengths), batch_size, shuffle=True, metadata=data['metadata'], meta_labels=data['meta_labels'] ) val_dataset = Dataset( np.copy(val_obs), np.copy(val_act), np.copy(val_lengths), batch_size, shuffle=False, metadata=data['val_metadata'], meta_labels=data['meta_labels'] ) z_dim = 16 kl_final = 1. tf.reset_default_graph() sess = tf.InteractiveSession() model = RNNVAE( max_len, obs_dim, act_dim, batch_size, z_dim=z_dim, enc_hidden_dim=256, dec_hidden_dim=256, kl_steps=5000, kl_final=kl_final, learning_rate=5e-4, dropout_keep_prob=.9 ) sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(max_to_keep=2) writer = tf.summary.FileWriter('../../data/summaries/ngsim/train') val_writer = tf.summary.FileWriter('../../data/summaries/ngsim/val') model.train( dataset, val_dataset=val_dataset, writer=writer, val_writer=val_writer, n_epochs=1000, verbose=True, saver=saver )
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,860
wulfebw/automotive_behavior_inference
refs/heads/master
/abi/misc/tf_utils.py
import io import numpy as np import tensorflow as tf import sys import matplotlib backend = 'Agg' if sys.platform == 'linux' else 'TkAgg' matplotlib.use(backend) import matplotlib.pyplot as plt def scatter_encodings_summary(x, name): plt.scatter(x[:,0], x[:,1]) buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) img_sum = tf.Summary.Image(encoded_image_string=buf.getvalue()) summary = tf.Summary(value=[ tf.Summary.Value(tag='{}/encoding'.format(name), image=img_sum) ]) plt.close() return summary
{"/abi/models/rnnvae.py": ["/abi/core/rnn_utils.py", "/abi/misc/tf_utils.py", "/abi/misc/utils.py"], "/abi/misc/dataset.py": ["/abi/misc/utils.py"], "/tests/test_cnnrnnvae.py": ["/abi/misc/dataset.py", "/abi/models/cnnrnnvae.py"], "/tests/test_dataset.py": ["/abi/misc/dataset.py"], "/abi/models/cnnrnnvae.py": ["/abi/models/rnnvae.py"], "/tests/test_rnnvae.py": ["/abi/misc/dataset.py", "/abi/models/rnnvae.py"], "/scripts/ngsim/train_rnnvae_ngsim.py": ["/abi/misc/dataset.py", "/abi/misc/utils.py", "/abi/models/rnnvae.py"]}
50,864
binhvq/nms
refs/heads/master
/apps/transaction/migrations/0003_auto_20160608_0242.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-08 02:42 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('transaction', '0002_auto_20160607_0949'), ] operations = [ migrations.AddField( model_name='transaction', name='agent_ping_time', field=models.DateTimeField(blank=True, default=datetime.datetime(2016, 6, 8, 2, 42, 13, 873481, tzinfo=utc)), preserve_default=False, ), migrations.AlterField( model_name='transaction', name='time_avg', field=models.FloatField(blank=True, default=999), ), ]
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,865
binhvq/nms
refs/heads/master
/apps/user/models.py
from django.db import models from django.conf import settings from django.utils import timezone import uuid class UserProfile(models.Model): TRIAL_USER = 1 PREMIUM_USER = 2 USER_STATUS = ( (TRIAL_USER, 'Free User'), (PREMIUM_USER, 'Premium User'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', primary_key=True) subscription = models.IntegerField(choices=USER_STATUS, default=TRIAL_USER) expired_date = models.DateTimeField(auto_now_add=True) token = models.CharField(blank=True, max_length=255) class Meta: db_table = 'user_profile' def __str__(self): return self.user.email
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,866
binhvq/nms
refs/heads/master
/apps/landing/views.py
from django.core.urlresolvers import reverse_lazy from django.http import HttpResponse from django.views.generic import CreateView from apps.landing.models import Landing from apps.base.views import (BaseView, LoginRequiredMixin) # Create your views here. class LandingView(BaseView, CreateView): """docstring for LandingView""" model = Landing fields = ['email'] template_name = 'landing/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'NMS', }, } context.update(info) return context def form_valid(self, form): form.save() return HttpResponse('Email sent') def form_invalid(self, form): return HttpResponse("Email has been send!")
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,867
binhvq/nms
refs/heads/master
/apps/ip/views.py
from django.db import IntegrityError from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse_lazy from django.views.generic import (CreateView, ListView, DeleteView) from django.http import HttpResponse from django.core.validators import validate_email from django.core.exceptions import ValidationError from apps.ip.models import IP from apps.base.views import (BaseView, LoginRequiredMixin) from .utils import UtilsIP import json class IPAPIList(BaseView): def get(self, request, *args, **kwargs): util_ip = UtilsIP() result = util_ip.get_list_ip('') return HttpResponse(json.dumps(result)) class APIIPCreateView(BaseView): def post(self, request, *args, **kwargs): pass class IPListView(BaseView, LoginRequiredMixin, ListView): """docstring for IPListView""" model = IP template_name = 'ip/index.html' def get_queryset(self): return IP.objects.filter(user_profile=self.request.user.profile).order_by('-id') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'List Address - NMS', }, } context.update(info) return context class IPCreateView(BaseView, LoginRequiredMixin, CreateView): """docstring for IPCreateView""" model = IP fields = ['address', 'vhost'] template_name = 'ip/create.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'New IP Address - NMS', }, } context.update(info) return context def form_valid(self, form): # Save IP try: ip = form.save(commit=False) if self.validateEmail(ip.address): form._errors['address'] = form.error_class(['Please dont use your email. ' 'Please supply a different ip address.']) return super().form_invalid(form) if self.request.user.profile.subscription == 1 and ip.vhost: return super().form_invalid(form) ip.user_profile = self.request.user.profile ip.save() except IntegrityError: form._errors['address'] = form.error_class(['This address is already in use. ' 'Please supply a different ip address.']) return super().form_invalid(form) return super().form_valid(form) def get_success_url(self): return reverse_lazy('ip') def validateEmail(self, email): try: if email and 'http' in email: email = email.split('://')[1].lower() if '/' in email: email = email.split('/')[0] validate_email(email) return True except ValidationError: return False class IPDeleteView(BaseView, LoginRequiredMixin, DeleteView): """docstring for IPDeleteView""" model = IP def get(self, request, *args, **kwargs): obj = self.get_object() if obj.user_profile == self.request.user.profile: return self.post(request, *args, **kwargs) else: raise PermissionDenied def get_success_url(self): return reverse_lazy('ip')
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,868
binhvq/nms
refs/heads/master
/apps/core/core.py
#-------------------------------------------------- # @author: Tran Duc Loi # @email: loitranduc@gmail.com # @version: 1.0 # @project: NMS - Jetpjng.com # @community: Pythonvietnam #-------------------------------------------------- import pika import uuid import json import gevent from gevent import monkey, Greenlet monkey.patch_all() import mylog import logging from threading import current_thread from caller import Caller import time import coreconfig, importlib mylog.initialize_logger() logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(threadName)-10s] %(message)s') class AppServer(object): def __init__(self, usr='loitd', pwd='123456a@', host='localhost', port=5672, vhost='vh1'): logging.info("BEGIN INIT THE [AppServer] ----------------------------->") self.vhost = vhost creds = pika.PlainCredentials(username=usr, password=pwd) params = pika.ConnectionParameters(host=host, port=port, virtual_host=vhost, credentials=creds) # is in waiting state self.is_waiting = False # is initiate successfully self.is_init = False self.c = Caller() try: self.conn = pika.BlockingConnection(parameters=params) self.ch = self.conn.channel() except pika.exceptions.ProbableAccessDeniedError: logging.critical("[AppServer] Connection error. Check configuration.") return None except: return None # declare a queue to reply try: res = self.ch.queue_declare(exclusive=True, queue='reply') self.reply_queue = res.method.queue # get the queue name self.ch.basic_consume(queue=self.reply_queue, consumer_callback=self.on_feedback, no_ack=True) except pika.exceptions.ChannelClosed as e: logging.critical("[AppServer] The pika channel is closed. Error message: {0}".format(e)) return None except Exception as e: logging.critical("[AppServer] Unknown error while init app: {0}".format(e)) return None self.is_init = True logging.info("[AppServer] Done init ...") def on_feedback(self, ch, method, props, body): self.is_waiting = False logging.info("[AppServer] Received Corr_id: {0}".format(props.correlation_id)) # logging.info(body) if props.correlation_id == self.corr_id: # call a function to insert result to db # format data #self.vhost = self.vhost.decode('utf-8') body = body.decode('utf-8') body = json.loads(body) # begin inser toinsert = {'vhost': self.vhost, 'data': body} #c = Caller() self.c.insertIPS(coreconfig.CoreConfig.URL_POST_TRANSACTION, toinsert) #logging.info("The post data: {0}".format(toinsert)) self.res = body return False #return false to signal to consume that you're done. other wise it continues to block def push(self, msg): """ :param msg: list IP to ping msg = ['1.1.1.1', '2.2.2.2', '3.3.3.3', ] dumps -> encoder loads -> decoder :return: """ try: self.corr_id = str(uuid.uuid4()) self.res = None self._msg = json.dumps(msg) logging.info("[AppServer] Sending corr_id: {0}".format(self.corr_id)) #logging.info("[x] Processing: {0}".format(self._msg)) if not self.is_waiting and self.is_init: self.ch.basic_publish( exchange='', routing_key='default', properties=pika.BasicProperties( correlation_id=self.corr_id, content_type='text/plain', delivery_mode=2, reply_to=self.reply_queue, ), body=self._msg, ) logging.info("[AppServer] Done pushing ...") else: logging.info("[AppServer] Is waiting for the queue or is not init properly: {0}".format(self.is_waiting)) pass # waiting while (self.res is None): self.is_waiting = True self.conn.process_data_events(time_limit=0) return self.res except Exception as e: logging.critical("[AppServer] Exception while pushing message: \n{0}".format(e)) # raise e self.is_init = False #pushing fail then re-init the app return False class AppCore(Greenlet): def __init__(self, vhost_data): Greenlet.__init__(self) self.vhost_data = vhost_data self.app1 = AppServer(usr=self.vhost_data['user'], pwd=self.vhost_data['password'], host=self.vhost_data['host'], port=self.vhost_data['port'], vhost=self.vhost_data['name']) self.c = Caller() def _run(self): current_thread().name = self.vhost_data['name'] while 1: # reload config importlib.reload(coreconfig) # check if app is None logging.info("[AppCore] Current app is: {0}".format(self.app1)) if not self.app1.is_init: # re-initate logging.info("[AppCore] App isn't init properly. Re-initiate now ...") self.app1 = AppServer(usr=self.vhost_data['user'], pwd=self.vhost_data['password'], host=self.vhost_data['host'], port=self.vhost_data['port'], vhost=self.vhost_data['name']) logging.info("[AppCore] Now sleeping {0}s...".format(coreconfig.CoreConfig.PING_INTERVAL_SECONDS)) time.sleep(coreconfig.CoreConfig.PING_INTERVAL_SECONDS) # yes, ignore to continue continue # begin get vhosts & ips logging.info("[AppCore] Begin getting IPs ...") self.ips = self.c.getIPS(coreconfig.CoreConfig.URL_GET_LIST_IP, self.vhost_data['name']) # self.ips = ['192.168.1.1', '192.168.1.2', '192.168.1.3'] if self.app1.is_init and self.ips: self.app1.push(self.ips) else: logging.info("[AppCore] Nothing to push (app is None or get IPs failed)") logging.info("[AppCore] Now sleeping {0}s...".format(coreconfig.CoreConfig.PING_INTERVAL_SECONDS)) time.sleep(coreconfig.CoreConfig.PING_INTERVAL_SECONDS) if __name__ == '__main__': d = AppCore(coreconfig.CoreConfig.vhosts[0]) #v = AppCore({'user': 'loitd2', 'password': 'password', 'name': 'vh2'}) d.start() #v.start() d.join() #v.join()
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,869
binhvq/nms
refs/heads/master
/apps/core/mylog.py
#-------------------------------------------------- # @author: Tran Duc Loi # @email: loitranduc@gmail.com # @version: 1.0 # @project: NMS - Jetpjng.com # @community: Pythonvietnam #-------------------------------------------------- # mylog for nms # loitd import logging import os.path def initialize_logger(): output_dir = os.path.dirname(os.path.abspath(__file__)) #yes, get the current folder # disable pika log logging.getLogger("pika").propagate = False logger = logging.getLogger() # logger.setLevel(logging.DEBUG) # create console handler and set level to info # handler = logging.StreamHandler() # handler.setLevel(logging.INFO) # formatter = logging.Formatter("%(asctime)s [%(threadName)-10s] %(message)s") # handler.setFormatter(formatter) # logger.addHandler(handler) # create error file handler and set level to error handler = logging.FileHandler(os.path.join(output_dir, "error.log"),"w", encoding=None, delay="true") handler.setLevel(logging.CRITICAL) formatter = logging.Formatter("%(asctime)s [%(threadName)-10s] %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) # create debug file handler and set level to debug # handler = logging.FileHandler(os.path.join(output_dir, "all.log"),"w") # handler.setLevel(logging.DEBUG) # formatter = logging.Formatter("%(levelname)s - %(message)s") # handler.setFormatter(formatter) # logger.addHandler(handler) if __name__ == '__main__': pass
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,870
binhvq/nms
refs/heads/master
/apps/ip/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-02 08:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='IP', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_date', models.DateTimeField(auto_now_add=True)), ('modified_date', models.DateTimeField(auto_now=True)), ('address', models.URLField(max_length=255)), ('vhost', models.CharField(blank=True, default='default', max_length=255)), ], options={ 'db_table': 'ips', }, ), ]
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,871
binhvq/nms
refs/heads/master
/apps/landing/models.py
from django.db import models from apps.base.models import Timestampable # Create your models here. class Landing(Timestampable): email = models.EmailField(blank=False, max_length=255, unique=True) class Meta: db_table = 'landing' def __str__(self): return self.email
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,872
binhvq/nms
refs/heads/master
/apps/core/main.py
#-------------------------------------------------- # @author: Tran Duc Loi # @email: loitranduc@gmail.com # @version: 1.0 # @project: NMS - Jetpjng.com # @community: Pythonvietnam #-------------------------------------------------- import gevent from gevent import monkey, Greenlet from caller import Caller import coreconfig import importlib from core import AppCore import time, sys monkey.patch_all() import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(threadName)-10s] %(message)s') if __name__ == '__main__': try: # reload configs # print("Loading configuration ...") # importlib.reload(coreconfig) # get the ips from API # c = Caller('http://192.168.1.176:8000/api') # ret = c.getIPS() # ret = {'90': ['192.168.1.2'], 'vh2': ['192.168.1.1', '192.168.1.2', '192.168.1.3'], 'default': ['127.0.0.1']} # Start all available vhost tem = [] for config in coreconfig.CoreConfig.vhosts: d = AppCore(config) d.start() tem.append(d) gevent.joinall(tem) # time.sleep(10) except KeyboardInterrupt: print("Application is termincated by user") sys.exit(0)
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,873
binhvq/nms
refs/heads/master
/apps/user/views.py
from django.core.urlresolvers import reverse_lazy from django.views.generic import TemplateView from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import logout from apps.landing.models import Landing from apps.base.views import (BaseView, LoginRequiredMixin) class UserProfileView(BaseView, LoginRequiredMixin, TemplateView): """docstring for AboutView""" template_name = 'user/profile.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'User Profile - NMS', }, } context.update(info) return context
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,874
binhvq/nms
refs/heads/master
/apps/ip/models.py
from django.core.exceptions import ValidationError from django.db import models from apps.base.models import Timestampable from apps.user.models import UserProfile class IP(Timestampable): address = models.URLField(max_length=255) vhost = models.CharField(blank=True, max_length=255, default='default') user_profile = models.ForeignKey(UserProfile) class Meta: db_table = 'ips' unique_together = ('user_profile', 'address', 'vhost',) def save(self, *args, **kwargs): if self.address and 'http' in self.address: self.address = self.address.split('://')[1].lower() if '/' in self.address: self.address = self.address.split('/')[0] return super().save(*args, **kwargs) def __str__(self): return self.address
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,875
binhvq/nms
refs/heads/master
/apps/user/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-02 08:10 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='profile', serialize=False, to=settings.AUTH_USER_MODEL)), ('subscription', models.IntegerField(choices=[(1, 'Free User'), (2, 'Premium User')], default=1)), ('expired_date', models.DateTimeField(auto_now_add=True)), ('token', models.CharField(blank=True, max_length=500)), ], options={ 'db_table': 'user_profile', }, ), ]
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,876
binhvq/nms
refs/heads/master
/apps/agent/pingit.py
#-------------------------------------------------- # @author: Tran Duc Loi # @email: loitranduc@gmail.com # @version: 1.0 # @project: NMS - Jetpjng.com # @community: Pythonvietnam #-------------------------------------------------- from threading import Thread from queue import Queue import subprocess import gevent # from gevent import monkey, Greenlet # monkey.patch_all() import logging logging.basicConfig(level=logging.INFO, format='(%(threadName)-10s) %(message)s', ) import time from time import gmtime, strftime # from datetime import datetime # from pytz import timezone class PingIt(object): def __init__(self): pass def get_cur_time(self): # get the time based on local time of the server # return strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) # print(time.localtime(time.time())) # print(time.gmtime()) # print(datetime.utcnow()) return strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) # hn = timezone('Asia/Saigon') # localdt = hn.localize(datetime.now()) # return localdt.strftime('%Y-%m-%d %H:%M:%S %Z%z') def doping(self, target, numofpack=2, cmdtimeout=2, defaultdie=999): # logging.info("Ping check to: {0}".format(target)) self.command = "ping -c {0} -w {1} {2}".format(numofpack, cmdtimeout, target) self.target = target self.defaultdie = defaultdie # p = subprocess.check_output(self.theCommand(target), shell=True) p = subprocess.Popen(['ping', target, '-c', str(numofpack), '-w', str(cmdtimeout)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) rt = p.wait() self.msg = p.stdout.read().decode("utf-8") # print(msg) if rt == 1 or rt == 0: d = self.getResult() else: print(rt) print(self.msg) d = {"ip": self.target, "t": self.defaultdie, 'c': self.get_cur_time() } print(d) return d def getResult(self): # logging.info(self.msg) if (self.msg.find(r"rtt min/avg/max/mdev =") != -1): logging.info("good quality!!!") time = float(self.msg.split("rtt min/avg/max/mdev = ")[1].split("/")[1]) # constraint to 99 if time > self.defaultdie: time = self.defaultdie return {"ip": self.target, "t": time, "c": self.get_cur_time() } else: logging.info("unreachable or poor quality") return {"ip": self.target, "t": self.defaultdie, "c": self.get_cur_time() } class PingThem(): def __init__(self, targets, maxthreads=100): self.q1 = Queue(maxsize=0) self.q2 = Queue(maxsize=0) self.maxthreads = maxthreads if len(targets) >= maxthreads else len(targets) for target in targets: self.q1.put(target) logging.info("Done adding all targets") print(self.q1.qsize()) def worker(self): while 1: i = self.q1.get() # logging.info("Got value from queue: {0}".format(i)) # quit cond if i is None: break p = PingIt() r = p.doping(i) self.q2.put(r) self.q1.task_done() def run(self): print("Will start {0} threads for checking ...".format(self.maxthreads)) allts = [] for i in range(self.maxthreads): t = Thread(target=self.worker) t.start() allts.append(t) self.q1.join() for i in range(self.maxthreads): self.q1.put(None) for t in allts: t.join() # check q2 logging.info(self.q2.qsize()) ret = [] for j in range(self.q2.qsize()): i = self.q2.get() if i is None: break ret.append(i) return ret if __name__ == '__main__': targets = [ 'vnexpress.net', 'megacard.vn', 'shipantoan.vn', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', # '1.1.1.1', '2.2.2.2', '3.3.3.3', '8.8.8.8', '127.0.0.1', 'localhost', 'google.com', 'dantri.com.vn', ] # p = PingThem(targets, 300) # x = p.run() # print(x) p = PingIt() print(p.get_cur_time()) # p.doping('127.0.0.1')
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,877
binhvq/nms
refs/heads/master
/apps/base/__init__.py
default_app_config = 'apps.base.apps.UsersAppConfig'
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,878
binhvq/nms
refs/heads/master
/apps/ip/utils.py
from .models import IP class UtilsIP(object): def get_list_ip(self, vhost): obj_vhost = {} obj_vhost['default'] = [] if not vhost: list_ip = IP.objects.values_list('vhost', 'address').distinct() for ip in list_ip: key = ip[0] if key: if not key in obj_vhost: obj_vhost[key] = [] if ip[1] not in obj_vhost[key]: obj_vhost[key].append(ip[1]) else: obj_vhost['default'].append(ip[1]) return obj_vhost else: return IP.objects.values_list('address', 'vhost').distinct()
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,879
binhvq/nms
refs/heads/master
/apps/base/signals.py
from django.dispatch import receiver from django.db.models.signals import post_delete, post_save from django.contrib.auth.signals import user_logged_in from django.conf import settings from django.apps import apps from string import digits from random import choice from apps.user.models import UserProfile @receiver(post_save, sender=apps.get_model(settings.AUTH_USER_MODEL)) def create_user_profile(sender, instance, created, **kwargs): if not created: return token = ''.join(choice(digits) for i in range(6)) token = instance.email + ':' + token profile = UserProfile.objects.create(user=instance, token=token) profile.save()
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,880
binhvq/nms
refs/heads/master
/apps/core/coreconfig.py
#-------------------------------------------------- # @author: Tran Duc Loi # @email: loitranduc@gmail.com # @version: 1.0 # @project: NMS - Jetpjng.com # @community: Pythonvietnam #-------------------------------------------------- import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(threadName)-10s] %(message)s') class CoreConfig(object): vhosts = [ {'user': 'loitd', 'password': 'password', 'host': 'localhost', 'port': 5672, 'name': 'default'}, #{'user': 'loitd2', 'password': 'password', 'name': 'vh2'}, ] # reloadable PING_INTERVAL_SECONDS = 30 # reloadable URL_GET_LIST_IP = 'http://localhost/core/ip/' URL_POST_TRANSACTION = 'http://localhost/core/transaction/' def __init__(self): logging.info("Loading configuration ...") @staticmethod def isAvailable(vhost_name): for vhost in CoreConfig.vhosts: if vhost['name'] == vhost_name: return vhost return False
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,881
binhvq/nms
refs/heads/master
/apps/home/views.py
from django.core.urlresolvers import reverse_lazy from django.views.generic import TemplateView from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import logout from apps.landing.models import Landing from apps.base.views import (BaseView, LoginRequiredMixin) # Create your views here. class LoginView(BaseView, TemplateView): """docstring for LoginView""" template_name = 'home/login.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'Login Page - NMS', }, } context.update(info) return context class LogoutView(BaseView): """docstring for LogoutView""" def get(self, request, *args, **kwargs): logout(request) return HttpResponseRedirect(reverse_lazy('home')) class HomeView(BaseView, LoginRequiredMixin, TemplateView): """docstring for HomeView""" template_name = 'home/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'Home Page - NMS', }, } context.update(info) return context class HistoryView(BaseView, LoginRequiredMixin, TemplateView): """docstring for HistoryView""" template_name = 'home/history.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'History Page - NMS', }, } context.update(info) return context class AboutView(BaseView, TemplateView): """docstring for AboutView""" template_name = 'home/about.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'About Page - NMS', }, } context.update(info) return context class HelpView(BaseView, TemplateView): """docstring for HelperView""" template_name = 'home/help.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) info = { 'info': { 'title': 'Help Page - NMS', }, } context.update(info) return context
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,882
binhvq/nms
refs/heads/master
/apps/pusher/main.py
import requests TOKEN = '228606601:AAGltjoUHRr-wsk4vtFefI58dqs8WXImHfk' BASE_URL = 'https://api.telegram.org/bot' + TOKEN def sendMsg(msg = "fuck"): data = {'chat_id': '-128786812', 'text': msg} url = BASE_URL + '/sendMessage' r = requests.post(url, data) print(r.text) def getMe(): url = BASE_URL + '/getMe' print(url) r = requests.get(url) print(r.text) # {"ok":true,"result":[{"update_id":449110854, # "message":{"message_id":2,"from":{"id":183518555,"first_name":"Loi","last_name":"Tran Duc","username":"loitd"},"chat":{"id":-128786812,"title":"Massive group","type":"group"},"date":1463638841,"new_chat_participant":{"id":228606601,"first_name":"dollx","username":"dollx_bot"},"new_chat_member":{"id":228606601,"first_name":"dollx","username":"dollx_bot"}}},{"update_id":449110855, # "message":{"message_id":3,"from":{"id":183518555,"first_name":"Loi","last_name":"Tran Duc","username":"loitd"},"chat":{"id":183518555,"first_name":"Loi","last_name":"Tran Duc","username":"loitd","type":"private"},"date":1463638892,"text":"Fucj"}}]} def getUpdate(): url = BASE_URL + '/getUpdates' r = requests.get(url) print(r.text) if __name__ == '__main__': getMe() getUpdate() sendMsg("Yes, fuck")
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,883
binhvq/nms
refs/heads/master
/apps/agent/agent_vh1.py
#-------------------------------------------------- # @author: Tran Duc Loi # @email: loitranduc@gmail.com # @version: 1.0 # @project: NMS - Jetpjng.com # @community: Pythonvietnam #-------------------------------------------------- import pika import json import random from time import gmtime, strftime from pingit import PingThem import os, sys, time class AppAgent(object): def __init__(self, usr='loitd', pwd='password', host='localhost', port=5672, vhost='default'): self.is_init = False while not self.is_init: try: creds = pika.PlainCredentials(username=usr, password=pwd) params = pika.ConnectionParameters(host=host, port=port, virtual_host=vhost, credentials=creds) self.conn = pika.BlockingConnection(parameters=params) self.ch = self.conn.channel() print("[x] Done all init ...") # setup consume self.ch.queue_declare(queue='default', durable=False, exclusive=False) self.ch.basic_qos(prefetch_count=100) self.ch.basic_consume( consumer_callback=self.on_consume, queue='default', no_ack=False, ) print("[x] Waiting message ...") self.is_init = True # Begin consuming self.ch.start_consuming() except KeyboardInterrupt: self.conn.close() print("[x] Agent interrupted by users ...") sys.exit(0) except pika.exceptions.ConnectionClosed as e: self.conn.close() print("Exception while init: {0}".format(e)) time.sleep(5) except Exception as e: self.conn.close() print("Exception while init: {0}".format(e)) time.sleep(5) def on_consume(self, ch, method, props, body): print("[B] -------------------------------------------------- [B]") print("[x] Received corr_id: {0}".format(props.correlation_id)) # print(body) body = str(body.decode('utf-8')) if body is None or body == 'null': ch.basic_ack(delivery_tag=method.delivery_tag) print("[x] Done ack for None object") return True print("[x] Received content: {0}".format(body)) res = self.doping(body) # publish back to the reply queue ch.basic_publish( exchange='', routing_key=props.reply_to, properties=pika.BasicProperties( correlation_id=props.correlation_id, ), body=res, ) print("[x] Done response") # ack to mark the queue ch.basic_ack(delivery_tag=method.delivery_tag) print("[x] Done ack") def doping(self, msg): """ The ping method :param msg: :return: """ self._msg = json.loads(msg) # it shoulds be a list if ips # for demo # res = [] # for el in self._msg: # res.append({'i': el, 't': random.randint(0,100), 'c': strftime("%Y-%m-%d %H:%M:%S", gmtime()) }) # real p = PingThem(self._msg, 200) res = p.run() return json.dumps(res) if __name__ == '__main__': agent = AppAgent()
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,884
binhvq/nms
refs/heads/master
/nms/urls.py
"""nms URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib.staticfiles import views from django.conf import settings from django.contrib import admin from apps.landing.views import LandingView from apps.home.views import (HomeView, HistoryView, LoginView, LogoutView, AboutView, HelpView) from apps.ip.views import (IPListView, IPCreateView, IPDeleteView, IPAPIList) from apps.user.views import UserProfileView from apps.transaction.views import (TransactionAPI, TransactionStatusAPI) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^static/(?P<path>.*)$', views.static.serve, {'document_root': settings.STATIC_ROOT, 'show_indexes': settings.DEBUG}), url(r'^$', view=LoginView.as_view(), name='landing'), url(r'^login', view=LoginView.as_view(), name='login'), url(r'^logout', view=LogoutView.as_view(), name='logout'), url(r'^about', view=AboutView.as_view(), name='about'), url(r'^help', view=HelpView.as_view(), name='help'), url(r'^profile', view=UserProfileView.as_view(), name='profile'), url(r'^accounts/', include('allauth.urls')), url(r'^ping/$', view=HomeView.as_view(), name='home'), url(r'^history/$', view=HistoryView.as_view(), name='history'), url(r'^ip/$', view=IPListView.as_view(), name='ip'), url(r'^ip/create/$', view=IPCreateView.as_view(), name='ip_create'), url(r'^ip/delete/(?P<pk>[0-9]+)/$', view=IPDeleteView.as_view(), name='ip_delete'), url(r'^core/ip/$', view=IPAPIList.as_view()), url(r'^core/transaction/$', view=TransactionAPI.as_view()), url(r'^core/status/$', view=TransactionStatusAPI.as_view()), ]
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,885
binhvq/nms
refs/heads/master
/apps/ip/admin.py
from django.contrib import admin from .models import (IP) # Register your models here. admin.site.register(IP)
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,886
binhvq/nms
refs/heads/master
/apps/transaction/models.py
from django.db import models from apps.base.models import Timestampable class Transaction(Timestampable): address = models.CharField(max_length=255) vhost = models.CharField(max_length=255, default='default') agent_ping_time = models.DateTimeField(blank=True) time_avg = models.FloatField(default=999, blank=True) class Meta: db_table = 'transactions' def __str__(self): return self.address
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,887
binhvq/nms
refs/heads/master
/apps/transaction/views.py
from django.shortcuts import render from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from django.db.models import Avg, Count, Max, ExpressionWrapper, F, CharField import json import datetime from apps.base.views import (BaseView, LoginRequiredMixin) from apps.ip.models import IP from .models import Transaction class TransactionStatusAPI(BaseView): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, *args, **kwargs): result = { "data": [ ] } try: your_ip = IP.objects.values_list('address', flat=True).filter(user_profile=self.request.user.profile) your_id_transaction = Transaction.objects.filter(address__in=set(your_ip)).values('address').annotate(id=Max('id')).values_list("id", flat=True) your_transaction = Transaction.objects.filter(id__in=set(your_id_transaction)) #print("your_transaction: ", your_transaction) for transaction in your_transaction: arr_data = [] arr_data.append(transaction.address) arr_data.append(transaction.agent_ping_time.strftime('%m/%d/%Y %H:%M:%S')) if transaction.time_avg == 999: arr_data.append('Offline') else: arr_data.append(transaction.time_avg) result['data'].append(arr_data) except Exception as error: print("Something error: ", error) return HttpResponse(json.dumps(result)) class TransactionAPI(BaseView): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, *args, **kwargs): result = { "data": [ ] } try: your_ip = IP.objects.values_list('address', flat=True).filter(user_profile=self.request.user.profile) your_transaction = Transaction.objects.filter(address__in=set(your_ip)).order_by('-id') for transaction in your_transaction: arr_data = [] arr_data.append(transaction.address) arr_data.append(transaction.agent_ping_time.strftime('%m/%d/%Y %H:%M:%S')) arr_data.append(str(transaction.time_avg) + ' ms') result['data'].append(arr_data) except: print("Something error!") return HttpResponse(json.dumps(result)) def post(self, *args, **kwargs): js_data = self.request.body.decode('utf-8') if self._insert_data(js_data): result = {'status': True} else: result = {'status': False} return HttpResponse(json.dumps(result)) def _insert_data(self, receive): # { # "data": b '[{"i": "192.168.1.1", "t": 77, "c": "2016-05-17 07:32:42"}, {"i": "192.168.1.2", "t": 22, "c": "2016-05-17 07:32:42"}, {"i": "192.168.1.3", "t": 97, "c": "2016-05-17 07:32:42"}]', # 'vhost': 'default' # } try: receive = json.loads(receive) list_data = receive['data'] print("list_data: ", list_data) for item in list_data: print("item: ", item) transaction = Transaction() transaction.address = item['ip'] transaction.vhost = receive['vhost'] transaction.time_avg = float(str(item['t'])) transaction.agent_ping_time = datetime.datetime.strptime(item['c'], "%Y-%m-%d %H:%M:%S") transaction.save() return True except Exception as error: print("Loi me no roi ", error) return False
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,888
binhvq/nms
refs/heads/master
/apps/base/views.py
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.decorators.gzip import gzip_page from django.http import HttpResponse from django.views.generic import View import json class LoginRequiredMixin(View): """docstring for LoginRequiredMixin""" @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) class BaseView(View): """docstring for BaseView""" @method_decorator(gzip_page) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context
{"/apps/landing/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/views.py": ["/apps/ip/models.py", "/apps/base/views.py", "/apps/ip/utils.py"], "/apps/user/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/apps/ip/models.py": ["/apps/user/models.py"], "/apps/ip/utils.py": ["/apps/ip/models.py"], "/apps/base/signals.py": ["/apps/user/models.py"], "/apps/home/views.py": ["/apps/landing/models.py", "/apps/base/views.py"], "/nms/urls.py": ["/apps/landing/views.py", "/apps/home/views.py", "/apps/ip/views.py", "/apps/user/views.py", "/apps/transaction/views.py"], "/apps/ip/admin.py": ["/apps/ip/models.py"], "/apps/transaction/views.py": ["/apps/base/views.py", "/apps/ip/models.py", "/apps/transaction/models.py"]}
50,889
justin-ridge/music-data-api
refs/heads/master
/songs.py
import db import json import math PAGE_SIZE = 50 def get_songs(page): return get_songs_query('', page) def get_song(songid): query = db.query_db('SELECT * FROM songs WHERE songid=%s;' % songid) return json.dumps(query) def get_page_count(): count = int(get_count()) return str(math.ceil(count / PAGE_SIZE)) def get_count(): query = query = db.query_db('SELECT COUNT(*) FROM songs') return str(query[0].get('COUNT(*)')) def get_songs_features(page): return get_songs_query('JOIN features f ON s.songid=f.songid', page) def get_songs_minmax(page): return get_songs_query('JOIN minmax m ON s.songid=m.songid', page) def get_songs_query(join, page): offset = int(page) * PAGE_SIZE query = db.query_db( 'SELECT * FROM songs s %s ORDER BY artist, name LIMIT %d OFFSET %d;' % (join, PAGE_SIZE, offset)) return json.dumps(query) def get_search_query(val, table): if len(val) < 3: return '' return '%s LIKE \'%%%s%%\'' % (table, val) def get_where_clause(q1, q2, q3): query = 'WHERE ' queries = [] if len(q1) > 0: queries.append(q1) if len(q2) > 0: queries.append(q2) if len(q3) > 0: queries.append(q3) separator = ' AND ' return query + separator.join(queries) def search(name, artist, genre): name_query = get_search_query(name, 'name') artist_query = get_search_query(artist, 'artist') genre_query = get_search_query(genre, 'genre') where_clause = get_where_clause(name_query, artist_query, genre_query) if len(where_clause) == 0: return json.dumps([]) print(where_clause) query = db.query_db( 'SELECT * FROM SONGS s JOIN features f ON s.songid=f.songid %s ORDER BY artist, name LIMIT 200' % where_clause) return json.dumps(query)
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,890
justin-ridge/music-data-api
refs/heads/master
/test.py
import unittest import songs import datamanipulation import os import json THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class TestDataManipulation(unittest.TestCase): def test_random_forest(self): filename = os.path.join(THIS_DIR, 'sample_0.csv') data = '' with open(filename, encoding='utf8') as file1: data = file1.read() result = datamanipulation.random_forest(data) self.assertFalse(result is None) self.assertEqual('0.828', str(round(result['score'], 3))) self.assertEqual(17500, result['trainedFields']) self.assertEqual(7500, result['testedFields']) self.assertEqual(1289, result['mislabeled']) class TestSongs(unittest.TestCase): def test_get_songs(self): result = json.loads(songs.get_songs('0')) self.assertFalse(result is None) self.assertEqual(50, len(result)) def test_get_count(self): result = songs.get_count() self.assertEqual('232725', result) def test_get_page_count(self): result = songs.get_page_count() self.assertEqual('4655', result) def test_get_song(self): result = json.loads(songs.get_song('500')) song = result[0] self.assertEqual(500, song['songid']) self.assertEqual('Chorus', song['artist']) self.assertEqual('Goin Up', song['name']) self.assertEqual('Movie', song['genre']) self.assertEqual(0, song['target']) def test_get_songs_metadata(self): minmax = json.loads(songs.get_songs_minmax('0')) features = json.loads(songs.get_songs_features('0')) m1 = minmax[0] f1 = features[0] self.assertEqual(m1['artist'], f1['artist']) self.assertEqual(m1['name'], f1['name']) self.assertFalse('popularity' in m1.keys()) self.assertEqual(40, f1['popularity']) def test_search(self): artist = 'foO FighteRs' result = json.loads(songs.search('', artist, '')) self.assertEqual(138, len(result)) name = 'white limO' result = json.loads(songs.search(name, artist, '')) self.assertEqual(2, len(result)) if __name__ == '__main__': unittest.main()
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,891
justin-ridge/music-data-api
refs/heads/master
/compress.py
import gzip import shutil def compress_db(): with open('songs.db', 'rb') as f_in: with gzip.open('songs.db.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) def unzip_db(): with gzip.open('songs.db.gz', 'rb') as f_in: with open('songs.db', 'wb') as f_out: shutil.copyfileobj(f_in, f_out)
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,892
justin-ridge/music-data-api
refs/heads/master
/data_container.py
class DataContainer: def __init__(self, features, labels): self.features, self.labels = features, labels
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,893
justin-ridge/music-data-api
refs/heads/master
/app.py
import flask as fl from flask import abort, escape from flask_cors import CORS import http import songs import compress import probability import pickle import datamanipulation app = fl.Flask(__name__) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) compress.unzip_db() model = pickle.load(open('naive_bayes.sav', 'rb')) @app.route('/api/songs/health', methods=['GET']) def health(): if model is None: abort(500) return 'Hello! I am feeling healthy' @app.route('/api/songs/<songid>', methods=['GET']) def get_song(songid): try: return songs.get_song(songid) except Exception as e: print( 'There was an unhandled exception in get_song(). ' + str(e)) abort(500) @app.route('/api/songs', methods=['GET']) def get_songs(): try: page = escape(fl.request.args.get('page')) metadata = escape(fl.request.args.get('metadata')) if page is None or not page.isnumeric(): page = '0' if metadata == 'features': return songs.get_songs_features(page) elif metadata == 'minmax': return songs.get_songs_minmax(page) else: return songs.get_songs(page) except Exception as e: print( 'There was an unhandled exception in get_songs(). ' + str(e)) abort(500) @app.route('/api/songs/pagecount', methods=['GET']) def get_page_count(): try: return songs.get_page_count() except Exception as e: print( 'There was an unhandled exception in get_page_count(). ' + str(e)) abort(500) @app.route('/api/songs/count', methods=['GET']) def get_count(): try: return songs.get_count() except Exception as e: print( 'There was an unhandled exception in get_count(). ' + str(e)) abort(500) @app.route('/api/songs/search', methods=['GET']) def search_songs(): try: name = escape(fl.request.args.get('name')) artist = escape(fl.request.args.get('artist')) genre = escape(fl.request.args.get('genre')) if name is None: name = '' if artist is None: artist = '' if genre is None: genre = '' return songs.search(name, artist, genre) except Exception as e: print( 'The user most likely submitted invalid data to search_songs(). ' + str(e)) abort(400) @app.route('/api/songs/predict', methods=['POST']) def predict(): try: data = fl.request.json result = probability.predict(model, data) return fl.jsonify(result) except Exception as e: print( 'The user most likely submitted invalid data to predict(). ' + str(e)) abort(400) @app.route('/api/songs/prepdata', methods=['POST']) def prep_data(): try: posted_file = fl.request.json['data'] zipped_file = datamanipulation.prep_data(posted_file) return fl.send_file(zipped_file, attachment_filename='clean_data.zip', as_attachment=True) except Exception as e: print( 'The user most likely submitted invalid data to prep_data(). ' + str(e)) abort(400) @app.route('/api/songs/naivebayes', methods=['POST']) def naive_bayes(): try: posted_file = fl.request.json['data'] result = datamanipulation.naive_bayes(posted_file) return fl.jsonify(result) except Exception as e: print( 'The user most likely submitted invalid data to naive_bayes(). ' + str(e)) abort(400) @app.route('/api/songs/randomforest', methods=['POST']) def random_forest(): try: posted_file = fl.request.json['data'] result = datamanipulation.random_forest(posted_file) return fl.jsonify(result) except Exception as e: print( 'The user most likely submitted invalid data to random_forest(). ' + str(e)) abort(400) @app.errorhandler(500) def internal_error(error): return "An unknown error has occurred.", 500 @app.errorhandler(400) def bad_request(error): return "Bad request: please verify that your data is formatted correctly and try again.", 400 @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response if __name__ == '__main__': app.run(debug=True)
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,894
justin-ridge/music-data-api
refs/heads/master
/probability.py
import pandas as pd def get_genre(genre, name): compare = 'genre_' + genre if name == compare: return 1.0 return 0.0 def predict(model, data): d = pd.DataFrame(columns=('acousticness', 'danceability', 'duration_ms', 'energy', 'instrumentalness', 'liveness', 'loudness', 'speechiness', 'valence', 'genre_A Capella', 'genre_Alternative', 'genre_Anime', 'genre_Blues', 'genre_Childrens Music', 'genre_Classical', 'genre_Comedy', 'genre_Country', 'genre_Dance', 'genre_Electronic', 'genre_Folk', 'genre_Hip-Hop', 'genre_Indie', 'genre_Jazz', 'genre_Movie', 'genre_Opera', 'genre_Pop', 'genre_R&B', 'genre_Rap', 'genre_Reggae', 'genre_Reggaeton', 'genre_Rock', 'genre_Ska', 'genre_Soul', 'genre_Soundtrack', 'genre_World')) genre = data['genre'] genre_ACapella = get_genre(genre, 'genre_A Capella') genre_Alternative = get_genre(genre, 'genre_Alternative') genre_Anime = get_genre(genre, 'genre_Anime') genre_Blues = get_genre(genre, 'genre_Blues') genre_ChildrensMusic = get_genre(genre, 'genre_Childrens Music') genre_Classical = get_genre(genre, 'genre_Classical') genre_Comedy = get_genre(genre, 'genre_Comedy') genre_Country = get_genre(genre, 'genre_Country') genre_Dance = get_genre(genre, 'genre_Dance') genre_Electronic = get_genre(genre, 'genre_Electronic') genre_Folk = get_genre(genre, 'genre_Folk') genre_HipHop = get_genre(genre, 'genre_Hip-Hop') genre_Indie = get_genre(genre, 'genre_Indie') genre_Jazz = get_genre(genre, 'genre_Jazz') genre_Movie = get_genre(genre, 'genre_Movie') genre_Opera = get_genre(genre, 'genre_Opera') genre_Pop = get_genre(genre, 'genre_Pop') genre_RB = get_genre(genre, 'genre_R&B') genre_Rap = get_genre(genre, 'genre_Rap') genre_Reggae = get_genre(genre, 'genre_Reggae') genre_Reggaeton = get_genre(genre, 'genre_Reggaeton') genre_Rock = get_genre(genre, 'genre_Rock') genre_Ska = get_genre(genre, 'genre_Ska') genre_Soul = get_genre(genre, 'genre_Soul') genre_Soundtrack = get_genre(genre, 'genre_Soundtrack') genre_World = get_genre(genre, 'genre_World') d.loc[0] = [data['acousticness'], data['danceability'], data['duration_ms'], data['energy'], data['instrumentalness'], data['liveness'], data['loudness'], data['speechiness'], data['valence'], genre_ACapella, genre_Alternative, genre_Anime, genre_Blues, genre_ChildrensMusic, genre_Classical, genre_Comedy, genre_Country, genre_Dance, genre_Electronic, genre_Folk, genre_HipHop, genre_Indie, genre_Jazz, genre_Movie, genre_Opera, genre_Pop, genre_RB, genre_Rap, genre_Reggae, genre_Reggaeton, genre_Rock, genre_Ska, genre_Soul, genre_Soundtrack, genre_World] pred = model.predict_proba(d) val0 = pred[0][0] val1 = pred[0][1] predicted_val = '1' confidence = val1 if val1 < val0: predicted_val = '0' confidence = val0 return {'result': predicted_val, 'confidence': confidence}
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,895
justin-ridge/music-data-api
refs/heads/master
/datamanipulation.py
from matplotlib import pyplot as plt import pandas as pd import zipfile import io import base64 from sklearn.preprocessing import MinMaxScaler from data_container import DataContainer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier import matplotlib matplotlib.use('Agg') def clean_df(df): df = df.drop(['artist_name', 'track_name', 'track_id', 'key', 'mode', 'time_signature'], axis=1) dummies = pd.get_dummies(df['genre']).rename( columns=lambda x: 'genre_' + str(x)) df = pd.concat([df, dummies], axis=1) df = df.drop(['genre'], axis=1) return df def transform_min_max(df): df = df.drop(['popularity'], axis=1) features = list(df.columns) data = df[features] mms = MinMaxScaler() mms.fit(data) data_transformed = mms.transform(data) data_transformed = pd.DataFrame(data_transformed, columns=df.columns) return data_transformed def is_popular(item, popularity): if item['popularity'] >= popularity: return 1 return 0 def get_clean_dataframes(data): print('received data') io_data = io.StringIO(data) df = pd.read_csv(io_data, index_col=0) df = clean_df(df) print('cleaned data') labels = pd.DataFrame() labels['target'] = df.apply(lambda row: is_popular( row, df['popularity'].mean()), axis=1) print('label targets generated') features = transform_min_max(df) print('min-maxed features') return DataContainer(features, labels) def prep_data(data): data = get_clean_dataframes(data) io_f = io.StringIO() io_l = io.StringIO() data.features.to_csv(io_f) data.labels.to_csv(io_l) print('csv files created') zipped_file = io.BytesIO() with zipfile.ZipFile(zipped_file, 'w') as z: z.writestr('features.csv', io_f.getvalue()) z.writestr('labels.csv', io_l.getvalue()) zipped_file.seek(0) print('csv files zipped') return zipped_file def naive_bayes(data): data = get_clean_dataframes(data) x_train, x_test, y_train, y_test = train_test_split( data.features, data.labels.values, train_size=0.7, test_size=0.3, random_state=101) model = GaussianNB() y_train = y_train.ravel() model.fit(x_train, y_train) y_pred = model.predict(x_test) score = model.score(x_test, y_test) return { 'score': score, 'trainedFields': len(x_train), 'testedFields': len(x_test), 'mislabeled': str((y_test.ravel() != y_pred).sum()) } def get_importance(importance): buf = io.BytesIO() importance.nlargest(20).plot( kind='barh').get_figure().savefig(buf, format='png') plt.close() buf.seek(0) return base64.b64encode(buf.getvalue()).decode('utf-8') def get_mean_pie(features): mb = io.BytesIO() features.mean().plot(kind='pie', figsize=(20, 16), fontsize=26).get_figure().savefig(mb, format='png') plt.close() mb.seek(0) return base64.b64encode(mb.getvalue()).decode('utf-8') def get_target_count(labels): tb = io.BytesIO() labels['target'].value_counts().plot.bar( ).get_figure().savefig(tb, format='png') plt.close() tb.seek(0) return base64.b64encode(tb.getvalue()).decode('utf-8') def random_forest(data): data = get_clean_dataframes(data) print('splitting features') x_train, x_test, y_train, y_test = train_test_split( data.features, data.labels.values, train_size=0.7, test_size=0.3, random_state=101) forest = RandomForestClassifier( max_depth=10, min_samples_split=2, n_estimators=100, random_state=1) y_train = y_train.ravel() print('training model') model = forest.fit(x_train, y_train) y_pred = model.predict(x_test) print('evaluating model') score = model.score(x_test, y_test) importance = pd.Series(model.feature_importances_, index=data.features.columns) print('rendering feature importance') img_importance = get_importance(importance) print('rendering feature means') img_pie = get_mean_pie(data.features) print('rendering target count') img_labels = get_target_count(data.labels) mislabeled = int((y_test.ravel() != y_pred).sum()) return { 'score': score, 'trainedFields': len(x_train), 'testedFields': len(x_test), 'mislabeled': mislabeled, 'images': { 'importance': img_importance, 'mean': img_pie, 'labels': img_labels } }
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,896
justin-ridge/music-data-api
refs/heads/master
/analysis/kmeans.py
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.cluster import KMeans from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) def kmeans_cluster(features): clustering_kmeans = KMeans(n_clusters=5) features['cluster'] = clustering_kmeans.fit_predict(features) return features def pca_reduce(features): reduced_data = PCA(n_components=2).fit_transform(features) results = pd.DataFrame(reduced_data, columns=['pca1', 'pca2']) return results def plot_kmeans_cluster(features, results): sns_plot = sns.scatterplot( x="pca1", y="pca2", hue=features['cluster'], data=results).get_figure() sns_plot.savefig("kmeans_cluster.png") plt.title('K-means Clustering with 2 dimensions') plt.show() def plot_kmeans_target(labels, results): sns_plot = sns.scatterplot( x="pca1", y="pca2", hue=labels['target'], data=results).get_figure() sns_plot.savefig("kmeans_cluster_target.png") plt.title('K-means Clustering with 2 dimensions') plt.show() def plot_cluster(cluster, combined): c0 = combined[combined['cluster'] == cluster] c0 = c0.drop(['cluster'], axis=1) plot_cluster_mean(c0, cluster) plot_cluster_attributes(c0, cluster) plot_cluster_genre(c0, cluster) def plot_cluster_mean(c0, cluster): c0fig = c0.mean().plot(kind='barh', figsize=(20, 16), fontsize=26).get_figure() c0fig.savefig('c' + str(cluster) + '_bar.png') def plot_cluster_attributes(c0, cluster): c0f = c0.drop(['genre_A Capella', 'genre_Alternative', 'genre_Anime', 'genre_Blues', 'genre_Childrens Music', 'genre_Classical', 'genre_Comedy', 'genre_Country', 'genre_Dance', 'genre_Electronic', 'genre_Folk', 'genre_Hip-Hop', 'genre_Indie', 'genre_Jazz', 'genre_Movie', 'genre_Opera', 'genre_Pop', 'genre_R&B', 'genre_Rap', 'genre_Reggae', 'genre_Reggaeton', 'genre_Rock', 'genre_Ska', 'genre_Soul', 'genre_Soundtrack', 'genre_World', 'target', 'duration_ms'], axis=1) c0ffig = c0f.mean().plot(kind='pie', figsize=(20, 16), fontsize=26).get_figure() c0ffig.savefig('c' + str(cluster) + '_pie.png') def plot_cluster_genre(c0, cluster): c0g = c0.drop(['acousticness', 'danceability', 'duration_ms', 'energy', 'instrumentalness', 'liveness', 'loudness', 'speechiness', 'valence', 'target'], axis=1) c0gfig = c0g.mean().plot(kind='pie', figsize=(20, 16), fontsize=26).get_figure() c0gfig.savefig('c' + str(cluster) + '_pie_genre.png') def create_plots(): features = pd.read_csv('features.csv', index_col=0) labels = pd.read_csv('labels.csv', index_col=0) features = kmeans_cluster(features) results = pca_reduce(features) plot_kmeans_cluster(features, results) plot_kmeans_target(labels, results) combined = features combined['target'] = labels['target'] for i in range(5): plot_cluster(i, combined) create_plots()
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,897
justin-ridge/music-data-api
refs/heads/master
/db.py
import sqlite3 from sqlite3 import Error DB_FILE = 'songs.db' def get_connection(): conn = None try: conn = sqlite3.connect(DB_FILE) except Error as e: print(e) return conn def query_db(query, args=(), one=False): cur = get_connection().cursor() cur.execute(query, args) r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()] cur.connection.close() return (r[0] if r else None) if one else r
{"/songs.py": ["/db.py"], "/test.py": ["/songs.py", "/datamanipulation.py"], "/app.py": ["/songs.py", "/compress.py", "/probability.py", "/datamanipulation.py"], "/datamanipulation.py": ["/data_container.py"]}
50,899
colmassakian/ChessFen
refs/heads/master
/Interface.py
from ChessFEN import * from Tkinter import * import webbrowser def submit(): link = linkEntry.get() fen = getFEN(link) selection = "https://lichess.org/analysis/standard/" + fen + "_" + color.get() + "_KQkq_-_0_1" print(selection) resultLink.config(text = selection) resultLink.bind("<Button-1>", lambda event: webbrowser.open(selection, new = 1)) root = Tk() root.geometry("1000x400") color = StringVar(value="w") linkEntry = StringVar() L1 = Label(root, text="Enter link") E1 = Entry(root, textvariable = linkEntry) chooseLabel = Label(root) chooseLabel.config(text = "Which piece to move?") R1 = Radiobutton(root, text="White", variable=color, value="w") R2 = Radiobutton(root, text="Black", variable=color, value="b") # TODO: Bind to enter key submitButton = Button(root, text = 'Submit', command = submit) resultLink = Label(root) L1.grid(row=0,column=0) E1.grid(row=0,column=1) chooseLabel.grid(row=3,column=0) R1.grid(row=3,column=1) R2.grid(row=3,column=2) submitButton.grid(row=5,column=1) resultLink.grid(row=7,column=1) root.mainloop()
{"/Interface.py": ["/ChessFEN.py"]}
50,900
colmassakian/ChessFen
refs/heads/master
/ChessFEN.py
from selenium import webdriver class piece: def __init__(self, file, rank, pieceID): self.file = file self.rank = rank self.pieceID = pieceID # https://www.chess.com/puzzles/battle/2KDwKNvb8 def getFEN(link): activePieces = [] # TODO: Use chrome driver in headless form driver = webdriver.Firefox() driver.get(link) parent = driver.find_element_by_class_name('pieces') try: piecesList = parent.find_elements_by_tag_name('div') except: print("Error opening link") for currPiece in piecesList: # Find currPiece id in dom, if error, continue try: file = int(currPiece.get_attribute("class")[14]) except: continue rank = int(currPiece.get_attribute("class")[16]) # Split string to isolate the two characters that specify the color and type of each piece generalType = currPiece.get_attribute("style").split(".") pieceID = generalType[2].split("/")[-1] activePieces.append(piece(file, rank, pieceID)) result = "" currRank = [] for i in range(8, 0, -1): # Group pieces on the same rank for currPiece in activePieces: if currPiece.rank == i: currRank.append(currPiece) sortByFile = sorted(currRank, key=lambda x: x.file) # Go through sorted file and place pieces or gaps as necessary for FEN prev = 0 for pos in sortByFile: fileDiff = pos.file - prev - 1 if fileDiff != 0: result += str(fileDiff) if pos.pieceID[0] == 'w': result += (pos.pieceID[1]).upper() else: result += pos.pieceID[1] prev = pos.file # No slash after last rank if i != 1: result += '/' del currRank [:] return result
{"/Interface.py": ["/ChessFEN.py"]}
50,902
Ebenezer319/data_pull
refs/heads/main
/data_pull/tests/test.py
# -*- coding: utf-8 -*- """ Created on Wed Jul 28 11:57:23 2021 @author: ebenezer.an """ import unittest from data_pull.main import DataPull import pandas as pd import string class TestBasic(unittest.TestCase): def test_input(self): lowercase_letters = list(string.ascii_lowercase) self.assertEqual(len(lowercase_letters), 26) def test_create_file(self): user = [1,2,3,4,3] length = [4, 5, 6, 7, 2] path = ['/', '/check', '/','/test', '/test/room'] d_frame = pd.DataFrame(data={'user_id': user, 'length':length, 'path': path}) file_name = 'Test.csv' DataPull.create_csv(d_frame, file_name) test_file = pd.read_csv('Test.csv') self.assertEqual(test_file.shape[0], 5) def test_transform_data(self): user = [1,2,3,4,3] length = [4, 5, 6, 7, 2] path = ['/', '/check', '/','/test', '/test/room'] frame = pd.DataFrame(data={'user_id': user, 'length':length, 'path': path}) pivot = DataPull.transform_data(frame) self.assertEqual(pivot.shape[0], 4) if __name__ == '__main__': unittest.main()
{"/data_pull/tests/test.py": ["/data_pull/main.py"]}
50,903
Ebenezer319/data_pull
refs/heads/main
/setup.py
from setuptools import setup import pathlib def readme(): this_directory = pathlib.Path(__file__).parent.resolve() long_description = (this_directory / 'README.md').read_text(encoding='utf-8') return long_description setup(name='data_pull', version='1.0.0', description='Data Extract', long_description=readme(), long_description_content_type = 'text/markdown', classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 3', 'Topic :: CSV Extraction :: File Manipulation', ], url='https://github.com/Ebenezer319/data_pull', author='CSV Extractors', packages=['data_pull'], install_requires=[ 'numpy', 'pandas', 'setuptools', 'pathlib' ], test_suite='nose.collector', tests_require=['nose', 'nose-cover3'], entry_points={ 'console_scripts': ['data-pull=data_pull.data_pull:DataPull'], }, include_package_data=True, zip_safe=False)
{"/data_pull/tests/test.py": ["/data_pull/main.py"]}
50,904
Ebenezer319/data_pull
refs/heads/main
/data_pull/main.py
# -*- coding: utf-8 -*- """ Created on Mon Jul 26 21:33:09 2021 @author: ebenezer.an """ import requests import pandas as pd import string import numpy as np import sys # In[Class for Pulling Data] class DataPull: def __init__(self): self.lowercase_letters = list(string.ascii_lowercase) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type == TypeError: print(f"An exception occurred - {exc_val} line {exc_tb.tb_lineno}") print('You have entered a value that is not a string. Please use public root URL like "https://public.wiwdata.com/"') elif exc_type == FileNotFoundError: print(f"An exception occurred - {exc_val} line {exc_tb.tb_lineno}") print('Non existent public root URL provided. Please provide an accurate directory"') elif exc_type == IndexError or exc_type == NameError: print(f"An exception occurred {exc_val} line {exc_tb.tb_lineno}") print('Please provide a public root URL like "https://public.wiwdata.com/"') elif exc_type != None: print(f"An exception occurred - {exc_type}") print(f"{exc_val} at line {exc_tb.tb_lineno}") else: print("Program Successfully Finished!") return self def pull_files(self, path): dataframe = pd.DataFrame() for letter in self.lowercase_letters: data = pd.read_csv(path + letter + '.csv') dataframe = pd.concat([dataframe, data], sort = False, ignore_index=True) print('Pulling file: ' + letter + '.csv') return dataframe def transform_data(self, d_frame): data_pivot = pd.pivot_table(d_frame, values=['length'], index=['user_id'], columns=['path'], aggfunc=np.sum, fill_value=0) data_pivot.reset_index(level=data_pivot.index.names, inplace=True) data_pivot.columns = data_pivot.columns.map(lambda x: (x[1] + " " + x[0].replace('length', '')).strip() if x[1] != '' else (x[0].replace('length', '')).strip()) return data_pivot def create_csv(self, pivot, file_name): pivot.to_csv(file_name, index = False) # In[] try: path = sys.argv[1] except IndexError: pass with DataPull() as data_pull: user_data = data_pull.pull_files(path) user_pivot = data_pull.transform_data(user_data) data_pull.create_csv(user_pivot, 'User Journey.csv')
{"/data_pull/tests/test.py": ["/data_pull/main.py"]}
50,959
jac18281828/binance_power_toys
refs/heads/main
/cancel_order.py
from binance_order import binance_order import sys,time,json if __name__ == '__main__': if len(sys.argv) > 2: try: apikeyfile = sys.argv[1] orderId = sys.argv[2] with open(apikeyfile) as keyfile: apikey = json.load(keyfile) orderapi = binance_order(apikey) order_param = { 'symbol': 'BTCUSDT', 'orderId': orderId, 'timestamp': int(time.time()-86400) } orderinfo = orderapi.cancel(order_param) print("Order Result = %s" % orderinfo) except Exception as e: print("Failed. "+str(e)) else: print('apikey and orderid are required')
{"/cancel_order.py": ["/binance_order.py"], "/listen_key.py": ["/binance_order.py"], "/order.py": ["/binance_order.py"], "/binance_order.py": ["/binance_request.py"]}
50,960
jac18281828/binance_power_toys
refs/heads/main
/listen_key.py
from binance_order import binance_order import json,sys if __name__ == '__main__': if len(sys.argv) > 1: try: apikeyfile = sys.argv[1] with open(apikeyfile) as keyfile: apikey = json.load(keyfile) orderapi = binance_order(apikey) listen_key = orderapi.listen_key() print("Result = %s" % orderinfo) except Exception as e: print("Failed. "+repr(e)) else: print('apikey is required')
{"/cancel_order.py": ["/binance_order.py"], "/listen_key.py": ["/binance_order.py"], "/order.py": ["/binance_order.py"], "/binance_order.py": ["/binance_request.py"]}
50,961
jac18281828/binance_power_toys
refs/heads/main
/order.py
from binance_order import binance_order import json,sys if __name__ == '__main__': if len(sys.argv) > 1: try: apikeyfile = sys.argv[1] with open(apikeyfile) as keyfile: apikey = json.load(keyfile) orderapi = binance_order(apikey) order = { 'symbol': 'BTCUSDT', 'side': 'BUY', 'type': 'LIMIT', 'timeInForce': 'GTC', 'price': 9000, 'quantity': 0.01, 'recvWindow': 5000 } orderinfo = orderapi.submit(order) print("Order Result = %s" % orderinfo) except Exception as e: print("Failed. "+repr(e)) else: print('apikey is required')
{"/cancel_order.py": ["/binance_order.py"], "/listen_key.py": ["/binance_order.py"], "/order.py": ["/binance_order.py"], "/binance_order.py": ["/binance_request.py"]}
50,962
jac18281828/binance_power_toys
refs/heads/main
/binance_request.py
import time, base64, hashlib, hmac, urllib.request, urllib.parse, json, ssl, certifi class binance_request: API_URL = 'https://testnet.binance.vision/api' def __init__(self, apikey): self.apikey = apikey def build(self, params): otp = self.apikey['passphrase'] if len(otp) > 0: print('passphrase ignored') timestamp = int(time.time()*1000) binance_request = {} binance_request.update(params) binance_request['timestamp'] = timestamp return binance_request def sign(self, hash_block): secret = self.apikey['secret'] # using the encoded string as the password! Rather than the password! decoded_secret = secret.encode('utf-8') # base64.b64decode(secret) return hmac.new(decoded_secret, hash_block, hashlib.sha256).hexdigest() def delete(self, endpoint, params): binance_request = self.build(params) post_param = urllib.parse.urlencode(binance_request) hash_block = post_param.encode('utf-8') api_signature = self.sign(hash_block) resource = self.API_URL + endpoint post_data = post_param + '&' + ('signature=%s' % api_signature) api_request = urllib.request.Request(resource, data=post_data.encode('utf-8'), method='DELETE') apikey = self.apikey['key'] api_request.add_header('X-MBX-APIKEY', apikey) with urllib.request.urlopen(api_request, context=ssl.create_default_context(cafile=certifi.where())) as request_stream: return request_stream.read() raise RuntimeError("Request failed!") def post(self, endpoint, params): binance_request = self.build(params) post_param = urllib.parse.urlencode(binance_request) hash_block = post_param.encode('utf-8') api_signature = self.sign(hash_block) resource = self.API_URL + endpoint post_data = post_param + '&' + ('signature=%s' % api_signature) apikey = self.apikey['key'] api_request = urllib.request.Request(resource, data=post_data.encode('utf-8')) api_request.add_header('X-MBX-APIKEY', apikey) with urllib.request.urlopen(api_request, context=ssl.create_default_context(cafile=certifi.where())) as request_stream: return request_stream.read() raise RuntimeError("Request failed!") def fetch(self, endpoint, params): binance_request = self.build(params) request_param = urllib.parse.urlencode(binance_request) hash_block = request_param.encode('utf-8') api_signature = self.sign(hash_block) resource = self.API_URL + endpoint request_data = request_param + '&' + ('signature=%s' % api_signature) api_request = urllib.request.Request(resource + '?' + request_data) apikey = self.apikey['key'] api_request.add_header('X-MBX-APIKEY', apikey) with urllib.request.urlopen(api_request, context=ssl.create_default_context(cafile=certifi.where())) as request_stream: return request_stream.read() raise RuntimeError("Request failed!")
{"/cancel_order.py": ["/binance_order.py"], "/listen_key.py": ["/binance_order.py"], "/order.py": ["/binance_order.py"], "/binance_order.py": ["/binance_request.py"]}
50,963
jac18281828/binance_power_toys
refs/heads/main
/binance_order.py
from binance_request import binance_request import json class binance_order(binance_request): def test(self, order): result = self.post('/v3/order/test', order) return json.loads(result.decode()) def submit(self, order): result=self.post('/v3/order', order) return json.loads(result.decode()) def listen_key(self): result=self.post('/v3/userDataStream', {}) return json.loads(result.decode()) def list(self, order_param): return self.fetch('/v3/openOrders', order_param) def cancel(self, order_param): return self.delete('/v3/order', order_param) def cancel_open(self, order_param): return self.delete('/v3/openOrders', order_param)
{"/cancel_order.py": ["/binance_order.py"], "/listen_key.py": ["/binance_order.py"], "/order.py": ["/binance_order.py"], "/binance_order.py": ["/binance_request.py"]}
50,964
jac18281828/binance_power_toys
refs/heads/main
/binance.py
import asyncio import urllib.request import websockets import json import sys import time import traceback import ssl import certifi class BinanceWss: API_URL = 'https://testnet.binance.vision/api' WS_URL = 'wss://testnet.binance.vision/ws' PRODUCT_ID='BTCUSDT' is_running = True def __init__(self, listen_key): self.update_time = 0 self.requestId = 1 self.listen_key = listen_key async def send_json(self, websocket, event): event_payload = json.dumps(event) print(event_payload) await websocket.send(event_payload) async def ping(self, websocket): await websocket.ping() await asyncio.sleep(1) async def on_subscription(self, websocket, event): print(event) async def on_message(self, websocket, message): self.update_time = time.time() event_message = json.loads(message) print(message) async def send_subscription(self, websocket): event = { 'method': 'SUBSCRIBE', 'id': self.requestId, 'params': [ self.PRODUCT_ID.lower() + '@trade', '@balance' ] } self.requestId = self.requestId + 1 await self.send_json(websocket, event) async def on_open(self, websocket): await self.send_subscription(websocket) async def heartbeat(self, websocket): now = time.time() timedelta = now - self.update_time if timedelta > 10: await self.ping(websocket) await asyncio.sleep(1 - timedelta) async def receive_message(self, websocket): async for message in websocket: await self.on_message(websocket, message) def on_error(self, err): print('Error in websocket connection: {}'.format(err)) print(traceback.format_exc(err)) sys.exit(1) async def run_event_loop(self): try: resource = self.WS_URL + '/' + self.listen_key print('connect %s' % resource) async with websockets.connect(resource) as websocket: await self.on_open(websocket) while self.is_running: tasks = [ asyncio.ensure_future(self.heartbeat(websocket)), asyncio.ensure_future(self.receive_message(websocket)) ] done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) for task in pending: task.cancel() except Exception as e: self.on_error(e) def listen_key(apikey): api_url = BinanceWss.API_URL + '/v3/userDataStream' print(api_url) request = urllib.request.Request(api_url, method='POST') request.add_header('X-MBX-APIKEY', apikey) with urllib.request.urlopen(request, context=ssl.create_default_context(cafile=certifi.where())) as request_stream: listen_key = json.load(request_stream) return listen_key['listenKey'] raise RuntimeException('Unable to fetch listenKey') if __name__ == '__main__': if len(sys.argv) > 1: apikeyfile = sys.argv[1] with open(apikeyfile) as keystream: apikey = json.load(keystream) stream_key = listen_key(apikey['key']) print('listen key is %s' % stream_key) asioloop = asyncio.get_event_loop() try: bwss = BinanceWss(stream_key) asioloop.run_until_complete(bwss.run_event_loop()) finally: asioloop.close() else: print('apikeyfile is required.') sys.exit(1)
{"/cancel_order.py": ["/binance_order.py"], "/listen_key.py": ["/binance_order.py"], "/order.py": ["/binance_order.py"], "/binance_order.py": ["/binance_request.py"]}
50,965
zhch602/ZhiHuSpider
refs/heads/master
/main.py
# -*- coding: utf-8 -*- from PyQt4.QtGui import * from PyQt4.QtCore import * from operate import * QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8")) class MainDialog(QTabWidget): def __init__(self, parent=None): self.residence = 0 self.sex = 0 self.occupation = 0 self.education = 0 self.praise = 0 super(MainDialog, self).__init__(parent) self.setWindowTitle(self.tr("知乎通")) self.setMaximumSize(400, 300) self.setMinimumSize(400, 300) label0 = QLabel(self.tr("")) label1 = QLabel(self.tr("问题URL:")) label2 = QLabel(self.tr("问题URL:")) label3 = QLabel(self.tr("问题URL:")) label4 = QLabel(self.tr("性别:")) label5 = QLabel(self.tr("行业:")) label6 = QLabel(self.tr("居住地:")) label7 = QLabel(self.tr("教育水平:")) label8 = QLabel(self.tr("得赞比:")) self.questionEdit1 = QLineEdit() self.questionEdit2 = QLineEdit() self.questionEdit3 = QLineEdit() analysisrespondentPushButton = QPushButton(self.tr("分析答题者")) analysisfollowerPushButton = QPushButton(self.tr("分析关注者")) findanswerPushButton = QPushButton(self.tr("查找答案")) findquestionPushButton = QPushButton(self.tr("查找问题")) self.sexComboBox = QComboBox() self.occupationComboBox = QComboBox() self.sexComboBox.insertItem(0, self.tr("请选择")) self.sexComboBox.insertItem(1, self.tr("男")) self.sexComboBox.insertItem(2, self.tr("女")) self.occupationComboBox.insertItem(0, self.tr("请选择")) self.occupationComboBox.insertItem(1, self.tr("高新科技")) self.occupationComboBox.insertItem(2, self.tr("信息传媒")) self.occupationComboBox.insertItem(3, self.tr("服务业")) self.occupationComboBox.insertItem(4, self.tr("金融")) self.occupationComboBox.insertItem(5, self.tr("教育")) self.occupationComboBox.insertItem(6, self.tr("医疗服务")) self.occupationComboBox.insertItem(7, self.tr("艺术娱乐")) self.occupationComboBox.insertItem(8, self.tr("制造加工")) self.occupationComboBox.insertItem(9, self.tr("地产建筑")) self.occupationComboBox.insertItem(10, self.tr("贸易零售")) self.occupationComboBox.insertItem(11, self.tr("公共服务")) self.occupationComboBox.insertItem(12, self.tr("开采冶金")) self.occupationComboBox.insertItem(13, self.tr("交通仓储")) self.occupationComboBox.insertItem(14, self.tr("农林牧渔")) self.residenceCheckBox = QCheckBox() self.residenceCheckBox.setText(self.tr("比例最高")) self.educationCheckboBox = QCheckBox() self.educationCheckboBox.setText(self.tr("本科及以上")) self.praiseCheckboBox = QCheckBox() self.praiseCheckboBox.setText(self.tr("排名前5")) firstLayout = QGridLayout() firstLayout.addWidget(label1, 0, 0) firstLayout.addWidget(self.questionEdit1, 0, 1, 1, 3) firstLayout.addWidget(analysisrespondentPushButton, 1, 3) secondLayout = QGridLayout() secondLayout.addWidget(label2, 0, 0) secondLayout.addWidget(self.questionEdit2, 0, 1, 1, 3) secondLayout.addWidget(analysisfollowerPushButton, 1, 3) thirdLayout = QGridLayout() thirdLayout.addWidget(label3, 0, 0) thirdLayout.addWidget(self.questionEdit3, 0, 1, 1, 4) thirdLayout.addWidget(label4, 1, 0) thirdLayout.addWidget(self.sexComboBox, 1, 1) thirdLayout.addWidget(label5, 2, 0) thirdLayout.addWidget(self.occupationComboBox, 2, 1) thirdLayout.addWidget(label6, 3, 0) thirdLayout.addWidget(self.residenceCheckBox, 3, 1) thirdLayout.addWidget(label7, 1, 3) thirdLayout.addWidget(self.educationCheckboBox, 1, 4) thirdLayout.addWidget(label8, 2, 3) thirdLayout.addWidget(self.praiseCheckboBox, 2, 4) thirdLayout.addWidget(findanswerPushButton, 4, 4) forthLayout = QGridLayout() forthLayout.addWidget(label0, 0, 0) forthLayout.addWidget(label0, 0, 2) forthLayout.addWidget(findquestionPushButton, 0, 1) tab1 = QWidget() # tab2 = QWidget() tab3 = QWidget() tab4 = QWidget() self.addTab(tab1, self.tr("答题者分析")) # self.addTab(tab2,self.tr("关注者分析")) self.addTab(tab3, self.tr("答案查找")) self.addTab(tab4, self.tr("问题查找")) tab1.setLayout(firstLayout) # tab2.setLayout(secondLayout) tab3.setLayout(thirdLayout) tab4.setLayout(forthLayout) self.residenceCheckBox.stateChanged.connect(self.chageResidence) self.connect(analysisrespondentPushButton, SIGNAL("clicked()"), self.soltAnalysisrespondent) # self.connect(analysisfollowerPushButton, SIGNAL("clicked()"), self.soltAnalysisfollower) self.connect(findanswerPushButton, SIGNAL("clicked()"), self.soltFindanswer) self.connect(findquestionPushButton, SIGNAL("clicked()"), self.soltFindquestion) self.connect(self.occupationComboBox, SIGNAL("activated(int)"), self.changeOccupation) self.connect(self.sexComboBox, SIGNAL("activated(int)"), self.changeSex) def soltAnalysisrespondent(self): question = self.questionEdit1.text() ar = Analysisrespondent(question) ar.analysis() ar.display() analysisrespondentDialog = AnalysisrespondentDispaly() analysisrespondentDialog.exec_() # def soltAnalysisfollower(self): # question = self.questionEdit2.text() # af = Analysisfollower(question) # af.analysis() # analysisfollowerDialog =AnalysisfollowerDispaly() # analysisfollowerDialog.exec_() def soltFindanswer(self): question = self.questionEdit3.text() fa = Findanswer(self.sex, self.residence, self.occupation, self.education, self.praise, question) fa.find() findanswerDispaly = FindanswerDispaly() findanswerDispaly.exec_() def soltFindquestion(self): fq = Findquestion() fq.find() findquestionDispaly = FindquestionDispaly() findquestionDispaly.exec_() def changeSex(self): self.sex = self.sexComboBox.currentIndex() def changeOccupation(self): self.occupation = self.occupationComboBox.currentIndex() def chageResidence(self, state): if state == Qt.Checked: self.residence = 1 else: self.residence = 0 def changeEducation(self, state): if state == Qt.Checked: self.education = 1 else: self.education = 0 def changePraise(self, state): if state == Qt.Checked: self.praise = 1 else: self.praise = 0 class AnalysisrespondentDispaly(QDialog): def __init__(self, parent=None): super(AnalysisrespondentDispaly, self).__init__(parent) self.setWindowTitle(self.tr("分析结果")) self.setMaximumSize(400, 600) self.setMinimumSize(400, 600) class AnalysisfollowerDispaly(QDialog): def __init__(self, parent=None): super(AnalysisfollowerDispaly, self).__init__(parent) self.setWindowTitle(self.tr("分析结果")) self.setMaximumSize(400, 600) self.setMinimumSize(400, 600) class FindanswerDispaly(QDialog): def __init__(self, parent=None): super(FindanswerDispaly, self).__init__(parent) self.setWindowTitle(self.tr("查找结果")) self.setMaximumSize(400, 600) self.setMinimumSize(400, 600) class FindquestionDispaly(QDialog): def __init__(self, parent=None): super(FindquestionDispaly, self).__init__(parent) self.setWindowTitle(self.tr("查找结果")) self.setMaximumSize(400, 600) self.setMinimumSize(400, 600) def main(): app = QApplication(sys.argv) mainDialog = MainDialog() mainDialog.show() app.exec_() if __name__ == '__main__': main()
{"/main.py": ["/operate.py"]}
50,966
zhch602/ZhiHuSpider
refs/heads/master
/operate.py
# -*- coding: utf-8 -*- from __future__ import division from zhihu import * from collections import Counter import operator class Analysisrespondent(): url = "" residence = [] occupation1 = 0 occupation2 = 0 occupation3 = 0 occupation4 = 0 occupation5 = 0 occupation6 = 0 occupation7 = 0 occupation8 = 0 occupation9 = 0 occupation10 = 0 occupation11 = 0 occupation12 = 0 occupation13 = 0 occupation = [occupation1, occupation2, occupation3, occupation4, occupation5, occupation6, occupation7, occupation8, occupation9, occupation10, occupation11, occupation12, occupation13] undergraduate = 0 highschool = 0 education = [undergraduate, highschool] agree_num = 0 answers_num = 0 occupations_list = [] residence_list = [] unknown = 0 female = 0 male = 0 sex = [male,female,unknown] proportions_list = [] def __init__(self, url): self.url = url def display(self): print "female:"+str(self.female)+" "+"male:"+str(self.male) def analysis(self): question = Question(self.url) answers = question.get_all_answers() for answer in answers: author = answer.get_author() author_id = author.get_user_id() if (author_id.decode('GBK') == "匿名用户"): continue author_url = author.user_url sex = author.get_gender() agree_num = author.get_agree_num() answers_num = author.get_answers_num() agree_answers = agree_num/answers_num print agree_answers #proportion = [author.get_user_id(),author.user_url,agree_num/answers_num] #self.proportions_list.append(proportion) if (sex == 'unknown'): self.unknown += 1 elif (sex == 'female'): self.female += 1 else: self.male += 1 #occupation = author.get_occupation #if (occupation != 0): # self.occupations_list.append(occupation) #residence = author.get_residence() #if (residence != 0): # self.residence_list.append(residence) #education = author.get_education() #if (education != 0): # self.undergraduate += 1 #else: # self.highschool += 1 # class Analysisfollower(): # url = "" # def __init__(self,url): # self.url = url # def analysis(self): # question = Question(self.url) # followers_num = question.get_answers_num() # answers = question.get_all_answers() class Findanswer(): sex = 0 sex_text = "" residence = 0 residence_list = [] occupation = 0 occupations_list = [] education = 0 praise = 0 url = "" answers_list = [] undergraduate = 0 highschool = 0 def __init__(self, sex, residence, occupation, education, praise, url): self.sex = sex if (sex == 1): self.sex_text = 'male' else: self.sex_text = 'female' self.residence = residence self.occupation = occupation if (occupation == 1): self.occupations_list.append('高新科技') self.occupations_list.append('互联网') self.occupations_list.append('电子商务') self.occupations_list.append('电子游戏') self.occupations_list.append('计算机软件') self.occupations_list.append('计算机硬件') elif (occupation == 2): self.occupations_list.append('信息传媒') self.occupations_list.append('出版社') self.occupations_list.append('电影录音') self.occupations_list.append('广播电视') self.occupations_list.append('通信') elif (occupation == 3): self.occupations_list.append('金融') self.occupations_list.append('银行') self.occupations_list.append('资本投资') self.occupations_list.append('证券投资') self.occupations_list.append('保险') self.occupations_list.append('信贷') self.occupations_list.append('财务') self.occupations_list.append('审计') self.occupations_list.append('信息传媒') self.occupations_list.append('信息传媒') elif (occupation == 4): self.occupations_list.append('服务业') self.occupations_list.append('法律') self.occupations_list.append('餐饮') self.occupations_list.append('酒店') self.occupations_list.append('旅游') self.occupations_list.append('广告') self.occupations_list.append('公关') self.occupations_list.append('景观') self.occupations_list.append('咨询分析') self.occupations_list.append('市场推广') self.occupations_list.append('人力资源') self.occupations_list.append('社工服务') self.occupations_list.append('养老服务') elif (occupation == 5): self.occupations_list.append('教育') self.occupations_list.append('高等教育') self.occupations_list.append('基础教育') self.occupations_list.append('职业教育') self.occupations_list.append('幼儿教育') self.occupations_list.append('特殊教育') self.occupations_list.append('培训') elif (occupation == 6): self.occupations_list.append('医疗服务') self.occupations_list.append('临床医疗') self.occupations_list.append('制药') self.occupations_list.append('保健') self.occupations_list.append('美容') self.occupations_list.append('医疗器材') self.occupations_list.append('生物工程') self.occupations_list.append('疗养服务') self.occupations_list.append('护理服务') elif (occupation == 7): self.occupations_list.append('艺术娱乐') self.occupations_list.append('创意艺术') self.occupations_list.append('体育健身') self.occupations_list.append('娱乐休闲') self.occupations_list.append('图书馆') self.occupations_list.append('博物馆') self.occupations_list.append('策展') self.occupations_list.append('博彩') elif (occupation == 8): self.occupations_list.append('制造加工') self.occupations_list.append('食品饮料业') self.occupations_list.append('纺织皮革业') self.occupations_list.append('服装业') self.occupations_list.append('烟草业') self.occupations_list.append('造纸业') self.occupations_list.append('印刷业') self.occupations_list.append('化工业') self.occupations_list.append('汽车') self.occupations_list.append('家具') self.occupations_list.append('电子电器') self.occupations_list.append('机械设备') self.occupations_list.append('塑料工业') self.occupations_list.append('金属加工') self.occupations_list.append('军火') elif (occupation == 9): self.occupations_list.append('地产建筑') self.occupations_list.append('房地产') self.occupations_list.append('装饰装潢') self.occupations_list.append('物业服务') self.occupations_list.append('特殊建造') self.occupations_list.append('建筑设备') elif (occupation == 10): self.occupations_list.append('贸易零售') self.occupations_list.append('零售') self.occupations_list.append('大宗交易') self.occupations_list.append('进出口贸易') elif (occupation == 11): self.occupations_list.append('公共服务') self.occupations_list.append('政府') self.occupations_list.append('国防军事') self.occupations_list.append('航天') self.occupations_list.append('科研') self.occupations_list.append('给排水') self.occupations_list.append('水利能源') self.occupations_list.append('电力电网') self.occupations_list.append('公共管理') self.occupations_list.append('环境保护') self.occupations_list.append('非营利组织') elif (occupation == 12): self.occupations_list.append('开采冶金') self.occupations_list.append('煤炭工业') self.occupations_list.append('石油工业') self.occupations_list.append('黑色金属') self.occupations_list.append('有色金属') self.occupations_list.append('土砂石开采') self.occupations_list.append('地热开采') elif (occupation == 13): self.occupations_list.append('交通仓储') self.occupations_list.append('邮政') self.occupations_list.append('物流递送') self.occupations_list.append('地面运输') self.occupations_list.append('铁路运输') self.occupations_list.append('管线运输') self.occupations_list.append('航运业') self.occupations_list.append('民用航空业') else: self.occupations_list.append('农林牧渔') self.occupations_list.append('种植业') self.occupations_list.append('畜牧养殖业') self.occupations_list.append('林业') self.occupations_list.append('渔业') self.education = education self.praise = praise self.url = url def find(self): question = Question(self.url) answers = question.get_all_answers() for answer in answers: author = answer.get_author() if (self.sex != 0): if (self.sex_text == author.get_gender()): self.answers_list.append(author) else: continue if (self.occupation != 0): for occupation in self.occupations_list: if (occupation == author.get_reoccupation()): break self.answers_list.pop() if (self.residence == 1): self.residence_list.append(author.get_residence()) if (self.education == 1): education = author.get_education() if (education != 0): self.undergraduate += 1 else: self.highschool += 1 if (self.praise == 1): agree_num = author.get_agree_num() answers_num = author.get_answers_num() residence_count = Counter(self.residence_list) sorted_residence = sorted(residence_count.iteritems(), key=operator.itemgetter(1), reverse=True) print sorted_residence[0][0] class Findquestion(): def find(self): print 1
{"/main.py": ["/operate.py"]}
50,972
KozhevnikovM/devman-the-event
refs/heads/master
/enrollment/models.py
from django.db import models class Application(models.Model): contact_phone = models.CharField(max_length=20) ticket_type = models.CharField(max_length=20, db_index=True, choices=( ('standard-access', 'Standard Access'), ('pro-access', 'Pro Access'), ('premium-access', 'Premium Access'), )) confirmed = models.BooleanField(default=False, db_index=True) class Participant(models.Model): application = models.ForeignKey(Application, related_name='participants', on_delete=models.CASCADE) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField()
{"/enrollment/views.py": ["/enrollment/models.py"]}
50,973
KozhevnikovM/devman-the-event
refs/heads/master
/enrollment/views.py
from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Application, Participant @api_view(['POST']) def enroll(request): if 'contact_phone' not in request.data: return Response(['Contact phone field is required.'], status=400) if 'ticket_type' not in request.data: return Response(['Ticket type field is required.'], status=400) # TODO check if ticket_type is one of available choices participants = request.data.get('participants', []) # TODO validate data! application = Application.objects.create( contact_phone=str(request.data['contact_phone']), ticket_type=str(request.data['ticket_type']), ) participants = [Participant(application=application, **fields) for fields in participants] Participant.objects.bulk_create(participants) return Response({ 'application_id': application.id, })
{"/enrollment/views.py": ["/enrollment/models.py"]}
50,974
KozhevnikovM/devman-the-event
refs/heads/master
/enrollment/migrations/0001_initial.py
# Generated by Django 3.0.8 on 2020-07-13 15:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Application', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('contact_phone', models.CharField(max_length=20)), ('ticket_type', models.CharField(choices=[('standard-access', 'Standard Access'), ('pro-access', 'Pro Access'), ('premium-access', 'Premium Access')], db_index=True, max_length=20)), ('confirmed', models.BooleanField(db_index=True, default=False)), ], ), migrations.CreateModel( name='Participant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=30)), ('last_name', models.CharField(max_length=30)), ('email', models.EmailField(max_length=254)), ('application', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='participants', to='enrollment.Application')), ], ), ]
{"/enrollment/views.py": ["/enrollment/models.py"]}
50,975
KozhevnikovM/devman-the-event
refs/heads/master
/enrollment/admin.py
from django.contrib import admin from . import models class ParticipantInline(admin.TabularInline): model = models.Participant @admin.register(models.Application) class ApplicationAdmin(admin.ModelAdmin): list_display = ['contact_phone', 'ticket_type', 'confirmed'] list_filter = [ 'ticket_type', 'confirmed', ] search_fields = ['contact_phone'] inlines = [ ParticipantInline, ]
{"/enrollment/views.py": ["/enrollment/models.py"]}
50,979
HeylonNHP/RIFE-Colab
refs/heads/main
/install_dependencies.py
import os import subprocess import sys import addInstalldirToPath from addInstalldirToPath import * from Globals.BuildConfig import BuildConfig REQUIRED_PACKAGES = ['numpy>=1.16', 'tqdm>=4.35.0', 'opencv-python>=4.1.2', 'pyqt5', 'requests'] def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) def download_file(url, out_file): import requests r = requests.get(url, allow_redirects=True) open(out_file, 'wb').write(r.content) def extract_archive(archive_file, exclusions: list = []): seven_zip = "7z" if os.name == 'nt': seven_zip = r"C:\Program Files\7-Zip\7z.exe" # TODO: Use prependArray() seven_zip_exclusions = [] for exclusion in exclusions: seven_zip_exclusions.append('-xr!' + exclusion) success = False while not success: try: subprocess.run([seven_zip, 'e', archive_file, '-aoa'] + seven_zip_exclusions) success = True except: print('Cannot execute 7-zip to extract archive. Do you have x64 7-zip installed?') print('If not, please do so now before hitting enter: https://www.7-zip.org/a/7z1900-x64.exe') input('...') def prepend_array(arr: list, prepend_string: str): arr = arr.copy() for i in range(0, len(arr)): arr[i] = prepend_string + arr[i] return arr def main_install(): path_cwd = os.path.realpath(__file__) path_cwd = path_cwd[:path_cwd.rindex(os.path.sep)] path_cwd_rife_model = path_cwd + os.path.sep + 'arXiv2020RIFE' + os.path.sep + 'model' + os.path.sep path_cwd_rife_train_log = path_cwd + os.path.sep + 'arXiv2020RIFE' + os.path.sep + 'train_log' + os.path.sep print(path_cwd_rife_model) if not os.path.exists(path_cwd_rife_model): os.mkdir(path_cwd_rife_model) if not os.path.exists(path_cwd_rife_train_log): os.mkdir(path_cwd_rife_train_log) rife_code_files = prepend_array(os.listdir(path_cwd_rife_model), path_cwd_rife_model) rife_code_files += prepend_array(os.listdir(path_cwd_rife_train_log), path_cwd_rife_train_log) for file in rife_code_files: if not os.path.isfile(file): continue if '.pkl' in file: continue print(file) file_obj = open(file, 'r') file_str = file_obj.read() file_obj.close() file_str = file_str.replace('from model.', 'from arXiv2020RIFE.model.') file_str = file_str.replace('from train_log.', 'from arXiv2020RIFE.train_log.') out_file_obj = open(file, 'w') out_file_obj.write(file_str) out_file_obj.close() if BuildConfig().isPyInstallerBuild(): return for package in REQUIRED_PACKAGES: install(package) # Get torch try: import torch version_string = torch.__version__ subversions = version_string.split('.') if int(subversions[0]) < 1: # Torch less than 1.0.0 raise Exception if '+cpu' in subversions[2]: # Torch CPU only version raise Exception print('Found torch', torch.__version__) except: # Install torch print("Pytorch not found, getting 1.7.1 CUDA 11") if os.name == 'nt': # On windows subprocess.check_call( [sys.executable, '-m', 'pip', 'install', 'torch===1.7.1+cu110', 'torchvision===0.8.2+cu110', 'torchaudio===0.7.2', '-f', 'https://download.pytorch.org/whl/torch_stable.html']) else: # On linux subprocess.check_call( [sys.executable, '-m', 'pip', 'install', 'torch==1.7.1+cu110', 'torchvision==0.8.2+cu110', 'torchaudio===0.7.2', '-f', 'https://download.pytorch.org/whl/torch_stable.html']) # Check ffmpeg ffmpeg_exists = False ffprobe_exists = False while not ffmpeg_exists or not ffprobe_exists: try: subprocess.run(['ffmpeg']) ffmpeg_exists = True subprocess.run(['ffprobe']) ffprobe_exists = True except: print("Can't find ffmpeg/ffprobe - Downloading") download_file( r'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n5.0-latest-win64-gpl-5.0.zip', 'ffmpeg.zip') extract_archive('ffmpeg.zip', ['doc']) print('----DEPENDENCY INSTALLATION COMPLETE----') main_install()
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,980
HeylonNHP/RIFE-Colab
refs/heads/main
/mainGuiUi.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\Shiwo\PycharmProjects\RIFE-Colab\main_gui.ui' # # Created by: PyQt5 UI code generator 5.15.6 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(709, 731) self.centralwidget = QtWidgets.QWidget(MainWindow) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth()) self.centralwidget.setSizePolicy(sizePolicy) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout.setContentsMargins(-1, -1, -1, 9) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setContentsMargins(-1, 0, -1, -1) self.horizontalLayout.setObjectName("horizontalLayout") self.label = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(26) self.label.setFont(font) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.verticalLayout.addLayout(self.horizontalLayout) self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setContentsMargins(0, -1, -1, -1) self.gridLayout.setSpacing(6) self.gridLayout.setObjectName("gridLayout") self.inputLabel = QtWidgets.QLabel(self.centralwidget) self.inputLabel.setObjectName("inputLabel") self.gridLayout.addWidget(self.inputLabel, 0, 1, 1, 1) self.inputFilePathText = FileEdit(self.centralwidget) self.inputFilePathText.setObjectName("inputFilePathText") self.gridLayout.addWidget(self.inputFilePathText, 0, 2, 1, 1) self.browseInputButton = QtWidgets.QPushButton(self.centralwidget) self.browseInputButton.setObjectName("browseInputButton") self.gridLayout.addWidget(self.browseInputButton, 0, 3, 1, 1) self.verticalLayout.addLayout(self.gridLayout) self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.tab) self.verticalLayout_2.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout_2.setObjectName("verticalLayout_2") self.groupBox_3 = QtWidgets.QGroupBox(self.tab) self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.groupBox_3.setObjectName("groupBox_3") self.gridLayout_4 = QtWidgets.QGridLayout(self.groupBox_3) self.gridLayout_4.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) self.gridLayout_4.setHorizontalSpacing(6) self.gridLayout_4.setObjectName("gridLayout_4") self.label_13 = QtWidgets.QLabel(self.groupBox_3) self.label_13.setObjectName("label_13") self.gridLayout_4.addWidget(self.label_13, 2, 0, 1, 1) self.clearpngsCheck = QtWidgets.QCheckBox(self.groupBox_3) self.clearpngsCheck.setChecked(True) self.clearpngsCheck.setObjectName("clearpngsCheck") self.gridLayout_4.addWidget(self.clearpngsCheck, 3, 1, 1, 1) self.label_14 = QtWidgets.QLabel(self.groupBox_3) self.label_14.setObjectName("label_14") self.gridLayout_4.addWidget(self.label_14, 3, 0, 1, 1) self.nonlocalpngsCheck = QtWidgets.QCheckBox(self.groupBox_3) self.nonlocalpngsCheck.setChecked(True) self.nonlocalpngsCheck.setObjectName("nonlocalpngsCheck") self.gridLayout_4.addWidget(self.nonlocalpngsCheck, 2, 1, 1, 1) self.horizontalLayout_8 = QtWidgets.QHBoxLayout() self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.label_12 = QtWidgets.QLabel(self.groupBox_3) self.label_12.setObjectName("label_12") self.horizontalLayout_8.addWidget(self.label_12) self.mpdecimateText = QtWidgets.QLineEdit(self.groupBox_3) self.mpdecimateText.setObjectName("mpdecimateText") self.horizontalLayout_8.addWidget(self.mpdecimateText) self.mpdecimateEnableCheck = QtWidgets.QCheckBox(self.groupBox_3) self.mpdecimateEnableCheck.setChecked(True) self.mpdecimateEnableCheck.setObjectName("mpdecimateEnableCheck") self.horizontalLayout_8.addWidget(self.mpdecimateEnableCheck) self.gridLayout_4.addLayout(self.horizontalLayout_8, 0, 0, 1, 2) self.verticalLayout_2.addWidget(self.groupBox_3) self.tabWidget.addTab(self.tab, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setMinimumSize(QtCore.QSize(0, 0)) self.tab_2.setBaseSize(QtCore.QSize(0, 0)) self.tab_2.setObjectName("tab_2") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tab_2) self.verticalLayout_3.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout_3.setObjectName("verticalLayout_3") self.groupBox_4 = QtWidgets.QGroupBox(self.tab_2) self.groupBox_4.setObjectName("groupBox_4") self.gridLayout_5 = QtWidgets.QGridLayout(self.groupBox_4) self.gridLayout_5.setObjectName("gridLayout_5") self.label_17 = QtWidgets.QLabel(self.groupBox_4) self.label_17.setObjectName("label_17") self.gridLayout_5.addWidget(self.label_17, 0, 1, 1, 1) self.VideostatsInputFPStext = QtWidgets.QLineEdit(self.groupBox_4) self.VideostatsInputFPStext.setEnabled(False) self.VideostatsInputFPStext.setObjectName("VideostatsInputFPStext") self.gridLayout_5.addWidget(self.VideostatsInputFPStext, 0, 2, 1, 1) self.label_16 = QtWidgets.QLabel(self.groupBox_4) self.label_16.setObjectName("label_16") self.gridLayout_5.addWidget(self.label_16, 0, 0, 1, 1) self.label_18 = QtWidgets.QLabel(self.groupBox_4) self.label_18.setObjectName("label_18") self.gridLayout_5.addWidget(self.label_18, 0, 3, 1, 1) self.VideostatsOutputFPStext = QtWidgets.QLineEdit(self.groupBox_4) self.VideostatsOutputFPStext.setEnabled(False) self.VideostatsOutputFPStext.setObjectName("VideostatsOutputFPStext") self.gridLayout_5.addWidget(self.VideostatsOutputFPStext, 0, 4, 1, 1) self.verticalLayout_3.addWidget(self.groupBox_4) self.groupBox = QtWidgets.QGroupBox(self.tab_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth()) self.groupBox.setSizePolicy(sizePolicy) self.groupBox.setMinimumSize(QtCore.QSize(0, 0)) self.groupBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.groupBox.setCheckable(False) self.groupBox.setObjectName("groupBox") self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox) self.gridLayout_2.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) self.gridLayout_2.setObjectName("gridLayout_2") self.line_3 = QtWidgets.QFrame(self.groupBox) self.line_3.setFrameShape(QtWidgets.QFrame.HLine) self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_3.setObjectName("line_3") self.gridLayout_2.addWidget(self.line_3, 8, 0, 1, 2) self.label_4 = QtWidgets.QLabel(self.groupBox) self.label_4.setObjectName("label_4") self.gridLayout_2.addWidget(self.label_4, 6, 0, 1, 1) self.modeSelect = QtWidgets.QComboBox(self.groupBox) self.modeSelect.setObjectName("modeSelect") self.modeSelect.addItem("") self.modeSelect.addItem("") self.modeSelect.addItem("") self.gridLayout_2.addWidget(self.modeSelect, 6, 1, 1, 1) self.interpolationFactorSelect = QtWidgets.QComboBox(self.groupBox) self.interpolationFactorSelect.setEditable(True) self.interpolationFactorSelect.setObjectName("interpolationFactorSelect") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.interpolationFactorSelect.addItem("") self.gridLayout_2.addWidget(self.interpolationFactorSelect, 4, 1, 1, 1) self.label_3 = QtWidgets.QLabel(self.groupBox) self.label_3.setObjectName("label_3") self.gridLayout_2.addWidget(self.label_3, 4, 0, 1, 1) self.FPScalcHorizontalLayout = QtWidgets.QHBoxLayout() self.FPScalcHorizontalLayout.setObjectName("FPScalcHorizontalLayout") self.label_2 = QtWidgets.QLabel(self.groupBox) self.label_2.setObjectName("label_2") self.FPScalcHorizontalLayout.addWidget(self.label_2) self.useAccurateFPSCheckbox = QtWidgets.QCheckBox(self.groupBox) self.useAccurateFPSCheckbox.setChecked(True) self.useAccurateFPSCheckbox.setObjectName("useAccurateFPSCheckbox") self.FPScalcHorizontalLayout.addWidget(self.useAccurateFPSCheckbox) self.label_21 = QtWidgets.QLabel(self.groupBox) self.label_21.setObjectName("label_21") self.FPScalcHorizontalLayout.addWidget(self.label_21) self.accountForDuplicateFramesCheckbox = QtWidgets.QCheckBox(self.groupBox) self.accountForDuplicateFramesCheckbox.setChecked(True) self.accountForDuplicateFramesCheckbox.setObjectName("accountForDuplicateFramesCheckbox") self.FPScalcHorizontalLayout.addWidget(self.accountForDuplicateFramesCheckbox) self.gridLayout_2.addLayout(self.FPScalcHorizontalLayout, 2, 0, 1, 2) self.line = QtWidgets.QFrame(self.groupBox) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.gridLayout_2.addWidget(self.line, 3, 0, 1, 2) self.gridLayout_10 = QtWidgets.QGridLayout() self.gridLayout_10.setObjectName("gridLayout_10") self.batchthreadsNumber = QtWidgets.QSpinBox(self.groupBox) self.batchthreadsNumber.setMinimum(1) self.batchthreadsNumber.setMaximum(999999999) self.batchthreadsNumber.setProperty("value", 2) self.batchthreadsNumber.setObjectName("batchthreadsNumber") self.gridLayout_10.addWidget(self.batchthreadsNumber, 2, 1, 1, 1) self.label_7 = QtWidgets.QLabel(self.groupBox) self.label_7.setObjectName("label_7") self.gridLayout_10.addWidget(self.label_7, 2, 0, 1, 1) self.gpuidsSelect = QtWidgets.QComboBox(self.groupBox) self.gpuidsSelect.setEditable(True) self.gpuidsSelect.setObjectName("gpuidsSelect") self.gpuidsSelect.addItem("") self.gpuidsSelect.addItem("") self.gpuidsSelect.addItem("") self.gridLayout_10.addWidget(self.gpuidsSelect, 0, 3, 1, 1) self.enableHalfPrecisionFloatsCheck = QtWidgets.QCheckBox(self.groupBox) self.enableHalfPrecisionFloatsCheck.setChecked(False) self.enableHalfPrecisionFloatsCheck.setObjectName("enableHalfPrecisionFloatsCheck") self.gridLayout_10.addWidget(self.enableHalfPrecisionFloatsCheck, 2, 3, 1, 1) self.label_26 = QtWidgets.QLabel(self.groupBox) self.label_26.setObjectName("label_26") self.gridLayout_10.addWidget(self.label_26, 2, 2, 1, 1) self.UHDscaleNumber = QtWidgets.QDoubleSpinBox(self.groupBox) self.UHDscaleNumber.setMaximum(100.0) self.UHDscaleNumber.setSingleStep(0.01) self.UHDscaleNumber.setProperty("value", 1.0) self.UHDscaleNumber.setObjectName("UHDscaleNumber") self.gridLayout_10.addWidget(self.UHDscaleNumber, 4, 1, 1, 1) self.scenechangeSensitivityNumber = QtWidgets.QDoubleSpinBox(self.groupBox) self.scenechangeSensitivityNumber.setMaximum(1.0) self.scenechangeSensitivityNumber.setSingleStep(0.01) self.scenechangeSensitivityNumber.setProperty("value", 0.2) self.scenechangeSensitivityNumber.setObjectName("scenechangeSensitivityNumber") self.gridLayout_10.addWidget(self.scenechangeSensitivityNumber, 0, 1, 1, 1) self.line_5 = QtWidgets.QFrame(self.groupBox) self.line_5.setFrameShape(QtWidgets.QFrame.HLine) self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_5.setObjectName("line_5") self.gridLayout_10.addWidget(self.line_5, 3, 0, 1, 4) self.label_6 = QtWidgets.QLabel(self.groupBox) self.label_6.setObjectName("label_6") self.gridLayout_10.addWidget(self.label_6, 0, 2, 1, 1) self.line_4 = QtWidgets.QFrame(self.groupBox) self.line_4.setFrameShape(QtWidgets.QFrame.HLine) self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_4.setObjectName("line_4") self.gridLayout_10.addWidget(self.line_4, 1, 0, 1, 4) self.label_29 = QtWidgets.QLabel(self.groupBox) self.label_29.setObjectName("label_29") self.gridLayout_10.addWidget(self.label_29, 4, 0, 1, 1) self.label_5 = QtWidgets.QLabel(self.groupBox) self.label_5.setObjectName("label_5") self.gridLayout_10.addWidget(self.label_5, 0, 0, 1, 1) self.label_31 = QtWidgets.QLabel(self.groupBox) self.label_31.setObjectName("label_31") self.gridLayout_10.addWidget(self.label_31, 4, 2, 1, 1) self.InterpolationAIComboBox = QtWidgets.QComboBox(self.groupBox) self.InterpolationAIComboBox.setObjectName("InterpolationAIComboBox") self.InterpolationAIComboBox.addItem("") self.gridLayout_10.addWidget(self.InterpolationAIComboBox, 4, 3, 1, 1) self.gridLayout_2.addLayout(self.gridLayout_10, 9, 0, 1, 2) self.line_2 = QtWidgets.QFrame(self.groupBox) self.line_2.setFrameShape(QtWidgets.QFrame.HLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName("line_2") self.gridLayout_2.addWidget(self.line_2, 5, 0, 1, 2) self.mode3OptionsPanel = QtWidgets.QHBoxLayout() self.mode3OptionsPanel.setObjectName("mode3OptionsPanel") self.mode3UseInterpolationFactor = QtWidgets.QRadioButton(self.groupBox) self.mode3UseInterpolationFactor.setChecked(True) self.mode3UseInterpolationFactor.setObjectName("mode3UseInterpolationFactor") self.mode3OptionsPanel.addWidget(self.mode3UseInterpolationFactor) self.mode3UseTargetFPS = QtWidgets.QRadioButton(self.groupBox) self.mode3UseTargetFPS.setObjectName("mode3UseTargetFPS") self.mode3OptionsPanel.addWidget(self.mode3UseTargetFPS) self.mode3TargetFPS = QtWidgets.QDoubleSpinBox(self.groupBox) self.mode3TargetFPS.setDecimals(3) self.mode3TargetFPS.setMaximum(1e+25) self.mode3TargetFPS.setSingleStep(0.001) self.mode3TargetFPS.setProperty("value", 60.0) self.mode3TargetFPS.setObjectName("mode3TargetFPS") self.mode3OptionsPanel.addWidget(self.mode3TargetFPS) self.gridLayout_2.addLayout(self.mode3OptionsPanel, 7, 0, 1, 2) self.verticalLayout_3.addWidget(self.groupBox) self.tabWidget.addTab(self.tab_2, "") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.tab_3) self.verticalLayout_4.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout_4.setObjectName("verticalLayout_4") self.groupBox_2 = QtWidgets.QGroupBox(self.tab_3) self.groupBox_2.setObjectName("groupBox_2") self.gridLayout_3 = QtWidgets.QGridLayout(self.groupBox_2) self.gridLayout_3.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) self.gridLayout_3.setObjectName("gridLayout_3") self.label_10 = QtWidgets.QLabel(self.groupBox_2) self.label_10.setObjectName("label_10") self.gridLayout_3.addWidget(self.label_10, 8, 0, 1, 1) self.nvencCheck = QtWidgets.QCheckBox(self.groupBox_2) self.nvencCheck.setChecked(True) self.nvencCheck.setObjectName("nvencCheck") self.gridLayout_3.addWidget(self.nvencCheck, 2, 1, 1, 1) self.label_8 = QtWidgets.QLabel(self.groupBox_2) self.label_8.setObjectName("label_8") self.gridLayout_3.addWidget(self.label_8, 2, 0, 1, 1) self.autoencodeCheck = QtWidgets.QCheckBox(self.groupBox_2) self.autoencodeCheck.setObjectName("autoencodeCheck") self.gridLayout_3.addWidget(self.autoencodeCheck, 8, 1, 1, 1) self.colourspaceSelectionComboBox = QtWidgets.QComboBox(self.groupBox_2) self.colourspaceSelectionComboBox.setObjectName("colourspaceSelectionComboBox") self.colourspaceSelectionComboBox.addItem("") self.colourspaceSelectionComboBox.addItem("") self.colourspaceSelectionComboBox.addItem("") self.gridLayout_3.addWidget(self.colourspaceSelectionComboBox, 4, 1, 1, 1) self.outputEncoderSelectComboBox = QtWidgets.QComboBox(self.groupBox_2) self.outputEncoderSelectComboBox.setObjectName("outputEncoderSelectComboBox") self.outputEncoderSelectComboBox.addItem("") self.outputEncoderSelectComboBox.addItem("") self.gridLayout_3.addWidget(self.outputEncoderSelectComboBox, 3, 1, 1, 1) self.label_28 = QtWidgets.QLabel(self.groupBox_2) self.label_28.setObjectName("label_28") self.gridLayout_3.addWidget(self.label_28, 4, 0, 1, 1) self.label_11 = QtWidgets.QLabel(self.groupBox_2) self.label_11.setObjectName("label_11") self.gridLayout_3.addWidget(self.label_11, 9, 0, 1, 1) self.autoencodeBlocksizeNumber = QtWidgets.QSpinBox(self.groupBox_2) self.autoencodeBlocksizeNumber.setMinimum(1) self.autoencodeBlocksizeNumber.setMaximum(999999999) self.autoencodeBlocksizeNumber.setProperty("value", 3000) self.autoencodeBlocksizeNumber.setObjectName("autoencodeBlocksizeNumber") self.gridLayout_3.addWidget(self.autoencodeBlocksizeNumber, 9, 1, 1, 1) self.label_27 = QtWidgets.QLabel(self.groupBox_2) self.label_27.setObjectName("label_27") self.gridLayout_3.addWidget(self.label_27, 3, 0, 1, 1) self.horizontalLayout_7 = QtWidgets.QHBoxLayout() self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.label_30 = QtWidgets.QLabel(self.groupBox_2) self.label_30.setObjectName("label_30") self.horizontalLayout_7.addWidget(self.label_30) self.enableLimitFPScheck = QtWidgets.QCheckBox(self.groupBox_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.enableLimitFPScheck.sizePolicy().hasHeightForWidth()) self.enableLimitFPScheck.setSizePolicy(sizePolicy) self.enableLimitFPScheck.setObjectName("enableLimitFPScheck") self.horizontalLayout_7.addWidget(self.enableLimitFPScheck) self.limitFPSnumber = QtWidgets.QDoubleSpinBox(self.groupBox_2) self.limitFPSnumber.setDecimals(3) self.limitFPSnumber.setMaximum(1e+19) self.limitFPSnumber.setSingleStep(0.001) self.limitFPSnumber.setProperty("value", 60.0) self.limitFPSnumber.setObjectName("limitFPSnumber") self.horizontalLayout_7.addWidget(self.limitFPSnumber) self.gridLayout_3.addLayout(self.horizontalLayout_7, 7, 0, 1, 2) self.horizontalLayout_9 = QtWidgets.QHBoxLayout() self.horizontalLayout_9.setObjectName("horizontalLayout_9") self.label_15 = QtWidgets.QLabel(self.groupBox_2) self.label_15.setObjectName("label_15") self.horizontalLayout_9.addWidget(self.label_15) self.loopoutputCheck = QtWidgets.QCheckBox(self.groupBox_2) self.loopoutputCheck.setObjectName("loopoutputCheck") self.horizontalLayout_9.addWidget(self.loopoutputCheck) self.label_32 = QtWidgets.QLabel(self.groupBox_2) self.label_32.setObjectName("label_32") self.horizontalLayout_9.addWidget(self.label_32) self.loopOutputPreferredLengthNumber = QtWidgets.QDoubleSpinBox(self.groupBox_2) self.loopOutputPreferredLengthNumber.setDecimals(0) self.loopOutputPreferredLengthNumber.setMaximum(999999999999.0) self.loopOutputPreferredLengthNumber.setProperty("value", 10.0) self.loopOutputPreferredLengthNumber.setObjectName("loopOutputPreferredLengthNumber") self.horizontalLayout_9.addWidget(self.loopOutputPreferredLengthNumber) self.label_33 = QtWidgets.QLabel(self.groupBox_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label_33.sizePolicy().hasHeightForWidth()) self.label_33.setSizePolicy(sizePolicy) self.label_33.setObjectName("label_33") self.horizontalLayout_9.addWidget(self.label_33) self.loopOutputMaxLengthNumber = QtWidgets.QDoubleSpinBox(self.groupBox_2) self.loopOutputMaxLengthNumber.setDecimals(0) self.loopOutputMaxLengthNumber.setMaximum(999999999999.0) self.loopOutputMaxLengthNumber.setProperty("value", 15.0) self.loopOutputMaxLengthNumber.setObjectName("loopOutputMaxLengthNumber") self.horizontalLayout_9.addWidget(self.loopOutputMaxLengthNumber) self.loopOutputRepeatedLoopsCheck = QtWidgets.QCheckBox(self.groupBox_2) self.loopOutputRepeatedLoopsCheck.setChecked(True) self.loopOutputRepeatedLoopsCheck.setObjectName("loopOutputRepeatedLoopsCheck") self.horizontalLayout_9.addWidget(self.loopOutputRepeatedLoopsCheck) self.gridLayout_3.addLayout(self.horizontalLayout_9, 1, 0, 1, 2) self.horizontalLayout_10 = QtWidgets.QHBoxLayout() self.horizontalLayout_10.setObjectName("horizontalLayout_10") self.label_9 = QtWidgets.QLabel(self.groupBox_2) self.label_9.setObjectName("label_9") self.horizontalLayout_10.addWidget(self.label_9) self.enableLosslessEncodingCheck = QtWidgets.QCheckBox(self.groupBox_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.enableLosslessEncodingCheck.sizePolicy().hasHeightForWidth()) self.enableLosslessEncodingCheck.setSizePolicy(sizePolicy) self.enableLosslessEncodingCheck.setObjectName("enableLosslessEncodingCheck") self.horizontalLayout_10.addWidget(self.enableLosslessEncodingCheck) self.crfoutNumber = QtWidgets.QDoubleSpinBox(self.groupBox_2) self.crfoutNumber.setMinimum(-10.0) self.crfoutNumber.setMaximum(100.0) self.crfoutNumber.setSingleStep(0.25) self.crfoutNumber.setProperty("value", 20.0) self.crfoutNumber.setObjectName("crfoutNumber") self.horizontalLayout_10.addWidget(self.crfoutNumber) self.gridLayout_3.addLayout(self.horizontalLayout_10, 5, 0, 1, 2) self.verticalLayout_4.addWidget(self.groupBox_2) self.tabWidget.addTab(self.tab_3, "") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.tab_4) self.verticalLayout_5.setObjectName("verticalLayout_5") self.groupBox_5 = QtWidgets.QGroupBox(self.tab_4) self.groupBox_5.setObjectName("groupBox_5") self.gridLayout_6 = QtWidgets.QGridLayout(self.groupBox_5) self.gridLayout_6.setObjectName("gridLayout_6") self.label_19 = QtWidgets.QLabel(self.groupBox_5) self.label_19.setObjectName("label_19") self.gridLayout_6.addWidget(self.label_19, 1, 0, 1, 1) self.targetFPSnumber = QtWidgets.QDoubleSpinBox(self.groupBox_5) self.targetFPSnumber.setDecimals(3) self.targetFPSnumber.setMaximum(9999999999999.0) self.targetFPSnumber.setSingleStep(0.001) self.targetFPSnumber.setProperty("value", 59.0) self.targetFPSnumber.setObjectName("targetFPSnumber") self.gridLayout_6.addWidget(self.targetFPSnumber, 1, 1, 1, 1) self.label_20 = QtWidgets.QLabel(self.groupBox_5) self.label_20.setObjectName("label_20") self.gridLayout_6.addWidget(self.label_20, 0, 0, 1, 2) self.verticalLayout_5.addWidget(self.groupBox_5) self.tabWidget.addTab(self.tab_4, "") self.tab_5 = QtWidgets.QWidget() self.tab_5.setObjectName("tab_5") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.tab_5) self.verticalLayout_6.setObjectName("verticalLayout_6") self.groupBox_6 = QtWidgets.QGroupBox(self.tab_5) self.groupBox_6.setObjectName("groupBox_6") self.gridLayout_7 = QtWidgets.QGridLayout(self.groupBox_6) self.gridLayout_7.setObjectName("gridLayout_7") self.label_22 = QtWidgets.QLabel(self.groupBox_6) self.label_22.setObjectName("label_22") self.gridLayout_7.addWidget(self.label_22, 0, 0, 1, 1) self.updateRifeModelButton = QtWidgets.QPushButton(self.groupBox_6) self.updateRifeModelButton.setObjectName("updateRifeModelButton") self.gridLayout_7.addWidget(self.updateRifeModelButton, 0, 1, 1, 1) self.verticalLayout_6.addWidget(self.groupBox_6) self.groupBox_7 = QtWidgets.QGroupBox(self.tab_5) self.groupBox_7.setObjectName("groupBox_7") self.gridLayout_8 = QtWidgets.QGridLayout(self.groupBox_7) self.gridLayout_8.setObjectName("gridLayout_8") self.label_23 = QtWidgets.QLabel(self.groupBox_7) self.label_23.setObjectName("label_23") self.gridLayout_8.addWidget(self.label_23, 0, 0, 1, 1) self.saveGUIstateCheck = QtWidgets.QCheckBox(self.groupBox_7) self.saveGUIstateCheck.setChecked(True) self.saveGUIstateCheck.setObjectName("saveGUIstateCheck") self.gridLayout_8.addWidget(self.saveGUIstateCheck, 0, 1, 1, 1) self.verticalLayout_6.addWidget(self.groupBox_7) self.groupBox_8 = QtWidgets.QGroupBox(self.tab_5) self.groupBox_8.setObjectName("groupBox_8") self.gridLayout_9 = QtWidgets.QGridLayout(self.groupBox_8) self.gridLayout_9.setObjectName("gridLayout_9") self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.label_24 = QtWidgets.QLabel(self.groupBox_8) self.label_24.setObjectName("label_24") self.horizontalLayout_4.addWidget(self.label_24) self.presetListComboBox = QtWidgets.QComboBox(self.groupBox_8) self.presetListComboBox.setObjectName("presetListComboBox") self.horizontalLayout_4.addWidget(self.presetListComboBox) self.gridLayout_9.addLayout(self.horizontalLayout_4, 0, 0, 1, 1) self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.createNewPresetButton = QtWidgets.QPushButton(self.groupBox_8) self.createNewPresetButton.setObjectName("createNewPresetButton") self.horizontalLayout_5.addWidget(self.createNewPresetButton) self.saveSelectedPresetButton = QtWidgets.QPushButton(self.groupBox_8) self.saveSelectedPresetButton.setObjectName("saveSelectedPresetButton") self.horizontalLayout_5.addWidget(self.saveSelectedPresetButton) self.loadSelectedPresetButton = QtWidgets.QPushButton(self.groupBox_8) self.loadSelectedPresetButton.setObjectName("loadSelectedPresetButton") self.horizontalLayout_5.addWidget(self.loadSelectedPresetButton) self.deleteSelectedPresetButton = QtWidgets.QPushButton(self.groupBox_8) self.deleteSelectedPresetButton.setObjectName("deleteSelectedPresetButton") self.horizontalLayout_5.addWidget(self.deleteSelectedPresetButton) self.gridLayout_9.addLayout(self.horizontalLayout_5, 1, 0, 1, 1) self.verticalLayout_6.addWidget(self.groupBox_8) self.groupBox_10 = QtWidgets.QGroupBox(self.tab_5) self.groupBox_10.setObjectName("groupBox_10") self.gridLayout_11 = QtWidgets.QGridLayout(self.groupBox_10) self.gridLayout_11.setObjectName("gridLayout_11") self.threadRestartsMaxCheckbox = QtWidgets.QCheckBox(self.groupBox_10) self.threadRestartsMaxCheckbox.setObjectName("threadRestartsMaxCheckbox") self.gridLayout_11.addWidget(self.threadRestartsMaxCheckbox, 0, 0, 1, 1) self.threadRestartsMaxSpinBox = QtWidgets.QSpinBox(self.groupBox_10) self.threadRestartsMaxSpinBox.setMaximum(999999999) self.threadRestartsMaxSpinBox.setProperty("value", 10) self.threadRestartsMaxSpinBox.setObjectName("threadRestartsMaxSpinBox") self.gridLayout_11.addWidget(self.threadRestartsMaxSpinBox, 0, 1, 1, 1) self.verticalLayout_6.addWidget(self.groupBox_10) self.groupBox_9 = QtWidgets.QGroupBox(self.tab_5) self.groupBox_9.setObjectName("groupBox_9") self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.groupBox_9) self.verticalLayout_7.setObjectName("verticalLayout_7") self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.label_25 = QtWidgets.QLabel(self.groupBox_9) self.label_25.setObjectName("label_25") self.horizontalLayout_6.addWidget(self.label_25) self.systemPowerOptionsComboBox = QtWidgets.QComboBox(self.groupBox_9) self.systemPowerOptionsComboBox.setObjectName("systemPowerOptionsComboBox") self.systemPowerOptionsComboBox.addItem("") self.systemPowerOptionsComboBox.addItem("") self.systemPowerOptionsComboBox.addItem("") self.horizontalLayout_6.addWidget(self.systemPowerOptionsComboBox) self.verticalLayout_7.addLayout(self.horizontalLayout_6) self.verticalLayout_6.addWidget(self.groupBox_9) self.tabWidget.addTab(self.tab_5, "") self.verticalLayout.addWidget(self.tabWidget) self.interpolationProgressBar = QtWidgets.QProgressBar(self.centralwidget) self.interpolationProgressBar.setProperty("value", 0) self.interpolationProgressBar.setObjectName("interpolationProgressBar") self.verticalLayout.addWidget(self.interpolationProgressBar) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.extractFramesButton = QtWidgets.QPushButton(self.centralwidget) self.extractFramesButton.setObjectName("extractFramesButton") self.horizontalLayout_3.addWidget(self.extractFramesButton) self.interpolateFramesButton = QtWidgets.QPushButton(self.centralwidget) self.interpolateFramesButton.setObjectName("interpolateFramesButton") self.horizontalLayout_3.addWidget(self.interpolateFramesButton) self.encodeOutputButton = QtWidgets.QPushButton(self.centralwidget) self.encodeOutputButton.setObjectName("encodeOutputButton") self.horizontalLayout_3.addWidget(self.encodeOutputButton) self.verticalLayout.addLayout(self.horizontalLayout_3) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.runAllStepsButton = QtWidgets.QPushButton(self.centralwidget) self.runAllStepsButton.setObjectName("runAllStepsButton") self.horizontalLayout_2.addWidget(self.runAllStepsButton) self.verticalLayout.addLayout(self.horizontalLayout_2) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 709, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "RIFE Colab GUI")) self.label.setText(_translate("MainWindow", "<html><head/><body><p>RIFE Colab GUI 0.24.1</p></body></html>")) self.inputLabel.setText(_translate("MainWindow", "Input file")) self.browseInputButton.setText(_translate("MainWindow", "Browse")) self.groupBox_3.setTitle(_translate("MainWindow", "Frame extraction options")) self.label_13.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Non local PNGs - </span>(Store PNGs in a temp folder)</p></body></html>")) self.clearpngsCheck.setText(_translate("MainWindow", "Enable")) self.label_14.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Clear PNGs after interpolation finished -</span></p></body></html>")) self.nonlocalpngsCheck.setText(_translate("MainWindow", "Enable")) self.label_12.setText(_translate("MainWindow", "<html><head/><body><span style=\" font-weight:600;\">Mpdecimate (Mode 3/4) -</span>\n" "<br>Duplicate frame removal strength (high,low,frac)</body></html>")) self.mpdecimateText.setText(_translate("MainWindow", "64*12,64*8,0.33")) self.mpdecimateEnableCheck.setText(_translate("MainWindow", "Enable")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Extraction")) self.groupBox_4.setTitle(_translate("MainWindow", "Input video stats")) self.label_17.setText(_translate("MainWindow", "Input FPS")) self.label_16.setText(_translate("MainWindow", "Video FPS")) self.label_18.setText(_translate("MainWindow", "Output FPS")) self.groupBox.setTitle(_translate("MainWindow", "Interpolation options")) self.label_4.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Frame handling mode -</span></p>\n" "<p>Mode 1 - no duplicate frame handling (Fastest)<br>\n" "Mode 3 - duplicate frame handling with adaptive interpolation factor (Slowest, works best)<br>\n" "Mode 4 - duplicate frame handling with fixed interpolation factor (Slow, works well)\n" "</body></html>")) self.modeSelect.setCurrentText(_translate("MainWindow", "1")) self.modeSelect.setItemText(0, _translate("MainWindow", "1")) self.modeSelect.setItemText(1, _translate("MainWindow", "3")) self.modeSelect.setItemText(2, _translate("MainWindow", "4")) self.interpolationFactorSelect.setItemText(0, _translate("MainWindow", "2")) self.interpolationFactorSelect.setItemText(1, _translate("MainWindow", "4")) self.interpolationFactorSelect.setItemText(2, _translate("MainWindow", "8")) self.interpolationFactorSelect.setItemText(3, _translate("MainWindow", "16")) self.interpolationFactorSelect.setItemText(4, _translate("MainWindow", "32")) self.interpolationFactorSelect.setItemText(5, _translate("MainWindow", "64")) self.interpolationFactorSelect.setItemText(6, _translate("MainWindow", "128")) self.interpolationFactorSelect.setItemText(7, _translate("MainWindow", "256")) self.interpolationFactorSelect.setItemText(8, _translate("MainWindow", "512")) self.interpolationFactorSelect.setItemText(9, _translate("MainWindow", "1024")) self.label_3.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Interpolation factor -</span></p></body></html>")) self.label_2.setText(_translate("MainWindow", "<b>Get FPS from FFmpeg TBC -</b>")) self.useAccurateFPSCheckbox.setText(_translate("MainWindow", "Enable")) self.label_21.setText(_translate("MainWindow", "<b>Account for duplicate frames in FPS calculation -</b><br>\n" "Slow to calculate FPS when enabled")) self.accountForDuplicateFramesCheckbox.setText(_translate("MainWindow", "Enable")) self.label_7.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Batch processing threads -</span></p><p>If not seeing 100% CUDA use on GPU<br/>Increase batch threads<br/>If using too much VRAM<br/>Decrease batch threads</p></body></html>")) self.gpuidsSelect.setItemText(0, _translate("MainWindow", "0")) self.gpuidsSelect.setItemText(1, _translate("MainWindow", "1")) self.gpuidsSelect.setItemText(2, _translate("MainWindow", "1,0")) self.enableHalfPrecisionFloatsCheck.setText(_translate("MainWindow", "Enable")) self.label_26.setText(_translate("MainWindow", "<b>Enable half-precision floats -</b>\n" "<br>\n" "Significantly reduces VRAM use (Good for low VRAM GPUs)\n" "<br>\n" "May slightly affect quality in some scenarios")) self.label_6.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">GPU ID\'s -</span></p><p>Separate ID numbers using commas for multi-gpu processing</p></body></html>")) self.label_29.setText(_translate("MainWindow", "<b>UHD Scale -</b>")) self.label_5.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Scene change sensitivity -</span></p><p>Lower is more sensitivity<br/>Higher is less sensitivity</p></body></html>")) self.label_31.setText(_translate("MainWindow", "<b>Interpolation AI -</b>")) self.InterpolationAIComboBox.setItemText(0, _translate("MainWindow", "RIFE")) self.mode3UseInterpolationFactor.setText(_translate("MainWindow", "Use interpolation factor")) self.mode3UseTargetFPS.setText(_translate("MainWindow", "Use target FPS:")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Interpolation")) self.groupBox_2.setTitle(_translate("MainWindow", "Encoding options")) self.label_10.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Auto encoding -</span></p>\n" "<p>Begin encoding the output while interpolation is still running<br>\n" "Saves space for interpolated png frames (Good for low space disks)<br>\n" "May slightly lower encoding quality</body></html>")) self.nvencCheck.setText(_translate("MainWindow", "Enable NVENC")) self.label_8.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Use NVENC -</span></p>\n" "<p>Enabled - Use Nvidia\'s hardware video encoder (Fast, less quality)<br>\n" "Disabled - Use x264 (Slow, more quality)</p></body></html>")) self.autoencodeCheck.setText(_translate("MainWindow", "Enable auto encoding")) self.colourspaceSelectionComboBox.setItemText(0, _translate("MainWindow", "yuv420p")) self.colourspaceSelectionComboBox.setItemText(1, _translate("MainWindow", "yuv422p")) self.colourspaceSelectionComboBox.setItemText(2, _translate("MainWindow", "yuv444p")) self.outputEncoderSelectComboBox.setItemText(0, _translate("MainWindow", "H.264")) self.outputEncoderSelectComboBox.setItemText(1, _translate("MainWindow", "H.265")) self.label_28.setText(_translate("MainWindow", "<b>Output colourspace -</b>")) self.label_11.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Auto encoding block size -</span></p>\n" "<p>Higher block size saves less disk space<br>Lower block size potentially reduces encoding quality/compression</p></body></html>")) self.label_27.setText(_translate("MainWindow", "<b>Output encoder -</b>\n" "<br>\n" "H.264 - Faster, less quality/size, much better support, max res: 4K\n" "<br>\n" "H.265 - Slower, better quality/size, worse support, max res: 8K")) self.label_30.setText(_translate("MainWindow", "<b>Limit output FPS -</b>")) self.enableLimitFPScheck.setText(_translate("MainWindow", "Enable")) self.label_15.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Loop output -</span></p></body></html>")) self.loopoutputCheck.setText(_translate("MainWindow", "Enable")) self.label_32.setText(_translate("MainWindow", "<b>Duration range (seconds)-</b>")) self.label_33.setText(_translate("MainWindow", "<b>-</b>")) self.loopOutputRepeatedLoopsCheck.setText(_translate("MainWindow", "Enable repeated loops")) self.label_9.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Output quality level (CRF) -</span></p>\n" "<p>Less is higher quality<br>\n" "More is lower quality</p></body></html>")) self.enableLosslessEncodingCheck.setText(_translate("MainWindow", "Lossless")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Encoding")) self.groupBox_5.setTitle(_translate("MainWindow", "Batch processing")) self.label_19.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Target FPS -</span></p></body></html>")) self.label_20.setText(_translate("MainWindow", "<html><head/><body>From this page, select an input folder, and set a target FPS and then click Run batch<br>The target FPS sets the minimum output FPS. The interpolator will use a high enough interpolation factor to meet or exceed it.\n" "<br>\n" "For looped output, add [l] to the folder or filename of a batch input</body></html>")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "Batch processing")) self.groupBox_6.setTitle(_translate("MainWindow", "RIFE Model")) self.label_22.setText(_translate("MainWindow", "<b>Update RIFE Model -</b>\n" "<br>\n" "Requires 7-zip to be installed before updating")) self.updateRifeModelButton.setText(_translate("MainWindow", "Update")) self.groupBox_7.setTitle(_translate("MainWindow", "Save GUI state")) self.label_23.setText(_translate("MainWindow", "<b>Keep settings between GUI restarts -</b>")) self.saveGUIstateCheck.setText(_translate("MainWindow", "Enable")) self.groupBox_8.setTitle(_translate("MainWindow", "Settings presets")) self.label_24.setText(_translate("MainWindow", "<b>Preset:</b>")) self.createNewPresetButton.setText(_translate("MainWindow", "Create new")) self.saveSelectedPresetButton.setText(_translate("MainWindow", "Save over selected")) self.loadSelectedPresetButton.setText(_translate("MainWindow", "Load selected")) self.deleteSelectedPresetButton.setText(_translate("MainWindow", "Delete selected")) self.groupBox_10.setTitle(_translate("MainWindow", "Maximum interpolation thread restarts")) self.threadRestartsMaxCheckbox.setText(_translate("MainWindow", "Enable")) self.groupBox_9.setTitle(_translate("MainWindow", "After interpolation is complete")) self.label_25.setText(_translate("MainWindow", "<b>System power:</b>")) self.systemPowerOptionsComboBox.setItemText(0, _translate("MainWindow", "Do nothing")) self.systemPowerOptionsComboBox.setItemText(1, _translate("MainWindow", "Shutdown computer")) self.systemPowerOptionsComboBox.setItemText(2, _translate("MainWindow", "Suspend computer")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("MainWindow", "Settings")) self.extractFramesButton.setText(_translate("MainWindow", "Step 1: Extract frames")) self.interpolateFramesButton.setText(_translate("MainWindow", "Step 2: Interpolate")) self.encodeOutputButton.setText(_translate("MainWindow", "Step 3: Encode output")) self.runAllStepsButton.setText(_translate("MainWindow", "Run all steps")) from pyqtHeaders.FileEdit import FileEdit
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,981
HeylonNHP/RIFE-Colab
refs/heads/main
/QueuedFrames/SaveFramesList.py
from QueuedFrames.FrameFile import FrameFile class SaveFramesList: framesList:list = None startOutputFrame:str = None endOutputFrame:str = None def __init__(self, framesList,startOutputFrame,endOutputFrame): self.framesList = framesList self.startOutputFrame = startOutputFrame self.endOutputFrame = endOutputFrame def saveAllPNGsInList(self): for item in self.framesList: frameFile:FrameFile = item frameFile.saveImageData()
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,982
HeylonNHP/RIFE-Colab
refs/heads/main
/QueuedFrames/InterpolationProgress.py
class InterpolationProgress: progressMessage: str = None completedFrames: int = None totalFrames: int = None def __init__(self): pass
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,983
HeylonNHP/RIFE-Colab
refs/heads/main
/runInterpolationIndividualSteps.py
from str2bool import * import argparse import os import sys import addInstalldirToPath # Why should we need to add the submodule to the path, just for the RIFE import to work # Thanks for being consistently terrible, python sys.path.insert(0, os.getcwd() + os.path.sep + 'arXiv2020RIFE') from generalInterpolationProceedures import * parser = argparse.ArgumentParser(description='Interpolation for video input') parser.add_argument('-i', dest='inputFile', type=str, default=None) parser.add_argument('-if', dest='interpolationFactor', type=int, default=2) parser.add_argument('-loop', dest='loopable', type=str2bool, default=False) parser.add_argument('-mode', dest='mode', type=int, default=3) parser.add_argument('-crf', dest='crfout', type=int, default=20) parser.add_argument('-clearpngs', dest='clearpngs', type=str2bool, default=False) parser.add_argument('-nonlocalpngs', dest='nonlocalpngs', type=str2bool, default=False) parser.add_argument('-scenesens', dest='scenechangeSensitivity', type=float, default=0.2) parser.add_argument('-mpdecimate', dest='mpdecimateSensitivity', type=str, default="64*12,64*8,0.33") parser.add_argument('-usenvenc', dest='useNvenc', type=str2bool, default=False) parser.add_argument('-gpuids', dest='gpuid', type=str, default="0") parser.add_argument('-batch', dest='batchSize', type=int, default=1) parser.add_argument('-step1', dest='step1', action='store_true') parser.set_defaults(step1=False) parser.add_argument('-step2', dest='step2', action='store_true') parser.set_defaults(step2=False) parser.add_argument('-step3', dest='step3', action='store_true') parser.set_defaults(step3=False) args = parser.parse_args() selectedGPUs = str(args.gpuid).split(",") selectedGPUs = [int(i) for i in selectedGPUs] setGPUinterpolationOptions(args.batchSize, selectedGPUs) print('Step1', args.step1, 'Step2', args.step2, 'Step3', args.step3) projectFolder = args.inputFile[:args.inputFile.rindex(os.path.sep)] if args.nonlocalpngs: projectFolder = installPath + os.path.sep + "tempFrames" if not os.path.exists(projectFolder): os.mkdir(projectFolder) fpsDataFilePath = projectFolder + os.path.sep + 'fpsout.txt' encoderConfig = EncoderConfig() encoderConfig.set_encoding_crf(float(args.crfout)) if bool(args.useNvenc): encoderConfig.enable_nvenc(True) encoderConfig.set_encoding_preset('slow') encoderConfig.set_nvenc_gpu_id(selectedGPUs[0]) interpolatorConfig = InterpolatorConfig() interpolatorConfig.setMode(args.mode) interpolatorConfig.setClearPngs(args.clearpngs) interpolatorConfig.setLoopable(args.loopable) interpolatorConfig.setInterpolationFactor(args.interpolationFactor) interpolatorConfig.setMpdecimateSensitivity(args.mpdecimateSensitivity) interpolatorConfig.setNonlocalPngs(args.nonlocalpngs) interpolatorConfig.setScenechangeSensitivity(args.scenechangeSensitivity) if args.step1: performAllSteps(args.inputFile, interpolatorConfig, encoderConfig, step1=True, step2=False, step3=False) if args.step2: performAllSteps(args.inputFile, interpolatorConfig, encoderConfig, step1=False, step2=True, step3=False) if args.step3: performAllSteps(args.inputFile, interpolatorConfig, encoderConfig, step1=False, step2=False, step3=True)
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,984
HeylonNHP/RIFE-Colab
refs/heads/main
/generalInterpolationProceedures.py
import gc import importlib import math import os import shutil import sys import traceback from queue import Queue import collections import threading import time from QueuedFrames.SaveFramesList import SaveFramesList from QueuedFrames.queuedFrameList import * from QueuedFrames.queuedFrame import * from QueuedFrames.FrameFile import * import autoEncoding from runAndPrintOutput import run_and_print_output from FFmpegFunctions import * from frameChooser import choose_frames from Globals.GlobalValues import GlobalValues from Globals.EncoderConfig import EncoderConfig from Globals.InterpolatorConfig import InterpolatorConfig from EventHandling import Event from tqdm import tqdm import warnings warnings.filterwarnings("ignore") FFMPEG4 = GlobalValues().getFFmpegPath() GPUID = 0 nvencPreset = 'p7' installPath = os.getcwd() print('INSTALL:', installPath) # Check if running on Windows or not onWindows = None if os.name == 'nt': onWindows = True else: onWindows = False # Get and initialise RIFE from rifeFunctions import download_rife download_rife(installPath, onWindows) os.chdir(installPath) from rifeInterpolationFunctions import * gpuBatchSize = 2 gpuIDsList = [0] interpolationProgressUpdate = Event.Event() currentSavingPNGRanges: list = [] progressBar = None def subscribeTointerpolationProgressUpdate(function): interpolationProgressUpdate.append(function) def setFFmpeg4Path(path): global FFMPEG4 FFMPEG4 = path set_ffmpeg_location(FFMPEG4) def setNvencSettings(nvencGpuID, preset): global GPUID global nvencPreset GPUID = nvencGpuID nvencPreset = preset def setGPUinterpolationOptions(batchSize: int, _gpuIDsList: list): global gpuIDsList global gpuBatchSize gpuIDsList = _gpuIDsList gpuBatchSize = batchSize def extractFrames(inputFile, projectFolder, mode, interpolatorConfig: InterpolatorConfig, mpdecimateSensitivity="64*12,64*8,0.33"): ''' Equivalent to DAINAPP Step 1 :param interpolatorConfig: ''' os.chdir(projectFolder) if os.path.exists("original_frames"): shutil.rmtree("original_frames") if not os.path.exists("original_frames"): os.mkdir("original_frames") if mode == 1: run_and_print_output( [FFMPEG4, '-i', inputFile, '-map_metadata', '-1', '-pix_fmt', 'rgb24', 'original_frames/%15d.png']) elif mode == 3 or mode == 4: mpdecimateOptions = [] if interpolatorConfig.getMpdecimatedEnabled(): hi, lo, frac = mpdecimateSensitivity.split(",") mpdecimate = "mpdecimate=hi={}:lo={}:frac={}".format(hi, lo, frac) mpdecimateOptions += ['-vf'] mpdecimateOptions += [mpdecimate] run_and_print_output( [FFMPEG4, '-i', inputFile, '-map_metadata', '-1', '-pix_fmt', 'rgb24', '-copyts', '-r', str(GlobalValues.timebase), '-vsync', '0', '-frame_pts', 'true'] + mpdecimateOptions + ['-qscale:v', '1', 'original_frames/%15d.png']) def runInterpolator(projectFolder, interpolatorConfig: InterpolatorConfig, outputFPS): ''' Equivalent to DAINAPP Step 2 :param interpolatorConfig: :param outputFPS: ''' global progressBar global gpuIDsList global gpuBatchSize interpolationFactor = interpolatorConfig.getInterpolationFactor() loopable = interpolatorConfig.getLoopable() mode = interpolatorConfig.getMode() scenechangeSensitivity = interpolatorConfig.getScenechangeSensitivity() os.chdir(installPath + '/arXiv2020RIFE/') origFramesFolder = projectFolder + '/' + "original_frames" interpFramesFolder = projectFolder + '/' + "interpolated_frames" if not os.path.exists(interpFramesFolder): os.mkdir(interpFramesFolder) # Loopable if loopable: generateLoopContinuityFrame(origFramesFolder) files = os.listdir(origFramesFolder) files.sort() framesQueue: collections.deque = collections.deque() if mode == 1: count = 0 shutil.copy(origFramesFolder + '/' + files[0], interpFramesFolder + '/' + '{:015d}.png'.format(count)) for i in range(0, len(files) - 1): framesList: list = [] progressMessage = "Interpolating frame: {} Of {} {:.2f}%".format(i + 1, len(files), ((i + 1) / len(files)) * 100) queuedFrameList: QueuedFrameList = QueuedFrameList(framesList, origFramesFolder + '/' + files[i], interpFramesFolder + '/' + '{:015d}.png'.format(count), origFramesFolder + '/' + files[i + 1], interpFramesFolder + '/' + '{:015d}.png'.format( count + interpolationFactor)) interpolationProgress = InterpolationProgress() interpolationProgress.progressMessage = progressMessage interpolationProgress.completedFrames = i + 1 interpolationProgress.totalFrames = len(files) queuedFrameList.interpolationProgress = interpolationProgress currentFactor = interpolationFactor while currentFactor > 1: period = int(interpolationFactor / currentFactor) for j in range(0, period): offset = int(currentFactor * j) beginFrame = interpFramesFolder + '/' + '{:015d}.png'.format(count + offset) endFrame = interpFramesFolder + '/' + '{:015d}.png'.format(count + currentFactor + offset) middleFrame = interpFramesFolder + '/' + '{:015d}.png'.format( count + int(currentFactor / 2) + offset) framesList.append(QueuedFrame(beginFrame, endFrame, middleFrame, scenechangeSensitivity)) currentFactor = int(currentFactor / 2) count += interpolationFactor framesQueue.append(queuedFrameList) elif mode == 3 or mode == 4: count = 0 shutil.copy(origFramesFolder + '/' + files[0], interpFramesFolder + '/' + '{:015d}.png'.format(count)) # To ensure no duplicates on the output with the new VFR to CFR algorithm, double the interpolation factor. TODO: Investigate modeModOutputFPS = outputFPS interpolationFactor = interpolationFactor * 2 modeModOutputFPS = modeModOutputFPS * 2 for i in range(0, len(files) - 1): framesList: list = [] localInterpolationFactor = interpolationFactor # If mode 3, calculate interpolation factor on a per-frame basis to maintain desired FPS beginFrameTime = int(files[i][:-4]) endFrameTime = int(files[i + 1][:-4]) timeDiff = endFrameTime - beginFrameTime if mode == 3: localInterpolationFactor = 2 while 1 / ((( endFrameTime - beginFrameTime) / localInterpolationFactor) / GlobalValues.timebase) < modeModOutputFPS: localInterpolationFactor = int(localInterpolationFactor * 2) progressMessage = "Interpolating frame: {} Of {} {:.2f}% Frame interp. factor {}x".format(i + 1, len(files), ((i + 1) / len( files)) * 100, localInterpolationFactor) # Get timecodes of both working frames currentTimecode = int(files[i][:-4]) nextTimecode = int(files[i + 1][:-4]) queuedFrameList: QueuedFrameList = QueuedFrameList(framesList, origFramesFolder + '/' + files[i], interpFramesFolder + '/' + '{:015d}.png'.format( currentTimecode), origFramesFolder + '/' + files[i + 1], interpFramesFolder + '/' + '{:015d}.png'.format( nextTimecode)) interpolationProgress = InterpolationProgress() interpolationProgress.progressMessage = progressMessage interpolationProgress.completedFrames = i + 1 interpolationProgress.totalFrames = len(files) queuedFrameList.interpolationProgress = interpolationProgress currentFactor = localInterpolationFactor while currentFactor > 1: period = int(round(localInterpolationFactor / currentFactor)) for j in range(0, period): # Get offset from the first frame offset = (timeDiff / period) * j # print(currentTimecode,offset, "j ",j) # Time difference between 'begin' and 'end' frames relative to current interpolation factor (Block size) currentFactor2 = (currentFactor / localInterpolationFactor) * timeDiff beginFrameTime = int(currentTimecode + offset) endFrameTime = int(currentTimecode + currentFactor2 + offset) middleFrameTime = int(currentTimecode + (currentFactor2 / 2) + offset) beginFrame = interpFramesFolder + '/' + '{:015d}.png'.format(beginFrameTime) endFrame = interpFramesFolder + '/' + '{:015d}.png'.format(endFrameTime) middleFrame = interpFramesFolder + '/' + '{:015d}.png'.format(middleFrameTime) framesList.append(QueuedFrame(beginFrame, endFrame, middleFrame, scenechangeSensitivity)) currentFactor = int(currentFactor / 2) # count += interpolationFactor framesQueue.append(queuedFrameList) progressBar = tqdm(total=len(files)) inFramesList: list = [] loadPNGThread = threading.Thread(target=queueThreadLoadFrame, args=(origFramesFolder, inFramesList,)) loadPNGThread.start() outFramesQueue: Queue = Queue(maxsize=32) gpuList: list = gpuIDsList batchSize: int = gpuBatchSize threads: list = [] for i in range(0, batchSize): for gpuID in gpuList: rifeThread = threading.Thread(target=queueThreadInterpolator, args=(framesQueue, outFramesQueue, inFramesList, gpuID, interpolatorConfig,)) threads.append(rifeThread) rifeThread.start() time.sleep(5) saveThreads = [] for i in range(0, batchSize): saveThread = threading.Thread(target=queueThreadSaveFrame, args=(outFramesQueue,)) saveThreads.append(saveThread) saveThread.start() # Wait for interpolation threads to exit for rifeThread in threads: rifeThread.join() # If all threads crashed before the end of interpolation - TODO: Cycle through all GPUs backupThreadStartCount = 0 while not len(framesQueue) == 0 and ( interpolatorConfig.getBackupThreadStartLimit() == -1 or interpolatorConfig.getBackupThreadStartLimit() > backupThreadStartCount): print("Starting backup thread") rifeThread = threading.Thread(target=queueThreadInterpolator, args=(framesQueue, outFramesQueue, inFramesList, gpuID, interpolatorConfig,)) rifeThread.start() time.sleep(5) rifeThread.join() backupThreadStartCount += 1 if interpolatorConfig.getBackupThreadStartLimit() != -1 and interpolatorConfig.getBackupThreadStartLimit() <= backupThreadStartCount: if interpolatorConfig.getExitOnBackupThreadLimit(): sys.exit() return [-1] # Wait for loading thread to exit loadPNGThread.join() # Interpolation done, ask save threads to exit and wait for them print("Put none - ask save thread to quit") outFramesQueue.put(None) for saveThread in saveThreads: saveThread.join() # Loopable if loopable: removeLoopContinuityFrame(interpFramesFolder) # Raise event, interpolation finished interpolationProgress = InterpolationProgress() interpolationProgress.completedFrames = len(files) interpolationProgress.totalFrames = len(files) interpolationProgress.progressMessage = "Interpolation finished" interpolationProgressUpdate(interpolationProgress) # End progress bar progressBar.close() # Return output FPS return [outputFPS] inFrameGetLock = threading.Lock() def queueThreadInterpolator(framesQueue: collections.deque, outFramesQueue: Queue, inFramesList: list, gpuid, interpolatorConfig): ''' Loads frames from queue (Or from HDD if frame not in queue) to interpolate, based on frames specified in inFramesList Puts frameLists in output queue to save :param interpolatorConfig: ''' device, model = None, None if interpolatorConfig.getInterpolator() == "RIFE": device, model = setup_rife(installPath, gpuid) while True: listOfCompletedFrames = [] if len(framesQueue) == 0: freeVRAM(model, device) break currentQueuedFrameList: QueuedFrameList = framesQueue.popleft() # Comment out printing progress message - using TQDM now # print(currentQueuedFrameList.interpolationProgress.progressMessage) # Raise event interpolationProgressUpdate(currentQueuedFrameList.interpolationProgress) listOfAllFramesInterpolate: list = currentQueuedFrameList.frameList # Copy start and end files if not os.path.exists(currentQueuedFrameList.startFrameDest): shutil.copy(currentQueuedFrameList.startFrame, currentQueuedFrameList.startFrameDest) if not os.path.exists(currentQueuedFrameList.endFrameDest): shutil.copy(currentQueuedFrameList.endFrame, currentQueuedFrameList.endFrameDest) try: for frame in listOfAllFramesInterpolate: queuedFrame: QueuedFrame = frame success = False # Load begin frame from HDD or RAM beginFrame = None # If the current frame pair uses an original_frame - Then grab it from RAM if queuedFrame.beginFrame == currentQueuedFrameList.startFrameDest: with inFrameGetLock: for i in range(0, len(inFramesList)): if currentQueuedFrameList.startFrame == str(inFramesList[i]): beginFrame = inFramesList[i] break if beginFrame is None: for i in range(0, len(listOfCompletedFrames)): if str(listOfCompletedFrames[i]) == queuedFrame.beginFrame: beginFrame = listOfCompletedFrames[i] break if beginFrame is None: beginFrame = FrameFile(queuedFrame.beginFrame) beginFrame.loadImageData() # Load end frame from HDD or RAM endFrame = None # If the current frame pair uses an original_frame - Then grab it from RAM if queuedFrame.endFrame == currentQueuedFrameList.endFrameDest: with inFrameGetLock: for i in range(0, len(inFramesList)): if currentQueuedFrameList.endFrame == str(inFramesList[i]): endFrame = inFramesList[i] break if endFrame is None: for i in range(0, len(listOfCompletedFrames)): if str(listOfCompletedFrames[i]) == queuedFrame.endFrame: endFrame = listOfCompletedFrames[i] break if endFrame is None: endFrame = FrameFile(queuedFrame.endFrame) endFrame.loadImageData() # Initialise the mid frame with the output path midFrame = FrameFile(queuedFrame.middleFrame) if interpolatorConfig.getInterpolator() == "RIFE": midFrame = rife_interpolate(device, model, beginFrame, endFrame, midFrame, queuedFrame.scenechangeSensitivity, scale=interpolatorConfig.getUhdScale()) listOfCompletedFrames.append(midFrame) # outFramesQueue.put(midFrame) except Exception as e: # Put current frame back into queue for another batch thread to process framesQueue.appendleft(currentQueuedFrameList) if hasattr(e, 'message'): print(e.message) else: print(e) # Kill batch thread freeVRAM(model, device) print("Freed VRAM from dead thread") break # Add interpolated frames to png save queue outputFramesList: SaveFramesList = SaveFramesList(listOfCompletedFrames, currentQueuedFrameList.startFrameDest, currentQueuedFrameList.endFrameDest) '''for midFrame1 in listOfCompletedFrames: outFramesQueue.put(midFrame1)''' outFramesQueue.put(outputFramesList) # Start frame is no-longer needed, remove from RAM with inFrameGetLock: for i in range(0, len(inFramesList)): if str(inFramesList[i]) == currentQueuedFrameList.startFrame: inFramesList.pop(i) break # Update progress bar global progressBar progressBar.update(1) print("END") def freeVRAM(model, device): ''' Attempts to free the RIFE model and GPU device from memory ''' del model del device gc.collect() torch.cuda.empty_cache() def queueThreadSaveFrame(outFramesQueue: Queue): ''' Takes framelists from queue and saves each frame as a png to disk ''' while True: item: SaveFramesList = outFramesQueue.get() if item is None: print("Got none - save thread") outFramesQueue.put(None) break currentSavingPNGRange = [item.startOutputFrame, item.endOutputFrame] currentSavingPNGRanges.append(currentSavingPNGRange) total, used, free = shutil.disk_usage(os.getcwd()[:os.getcwd().index(os.path.sep) + 1]) freeSpaceInMB = free / (2 ** 20) while freeSpaceInMB < 100: print("Running out of space on device") time.sleep(5) total, used, free = shutil.disk_usage(os.getcwd()[:os.getcwd().index(os.path.sep) + 1]) freeSpaceInMB = free / (2 ** 20) item.saveAllPNGsInList() currentSavingPNGRanges.remove(currentSavingPNGRange) def queueThreadLoadFrame(origFramesFolder: str, inFramesList: list): ''' Loads png frames from disk and places them in a queue to be interpolated ''' maxListLength = 128 frameFilesList = os.listdir(origFramesFolder) frameFilesList.sort() for i in range(0, len(frameFilesList)): while len(inFramesList) > maxListLength: time.sleep(0.01) frameFile = FrameFile(origFramesFolder + '/' + frameFilesList[i]) frameFile.loadImageData() inFramesList.append(frameFile) print("LOADED ALL FRAMES - DONE") def create_output(input_file, project_folder, output_video, output_fps, loopable, mode, encoder_config: EncoderConfig): ''' Equivalent to DAINAPP Step 3 ''' print("---Encoding output---") os.chdir(project_folder) max_loop_length = encoder_config.get_looping_options()[1] preferred_loop_length = encoder_config.get_looping_options()[0] loopable = encoder_config.get_looping_options()[2] input_length = get_length(input_file) input_ffmpeg = "" encoder_preset = ['-pix_fmt', encoder_config.get_pixel_format(), '-c:v', encoder_config.get_encoder(), '-preset', encoder_config.get_encoding_preset(), '-crf', '{}'.format(encoder_config.get_encoding_crf())] ffmpeg_selected = FFMPEG4 if encoder_config.nvenc_enabled(): encoder_preset = ['-pix_fmt', encoder_config.get_pixel_format(), '-c:v', encoder_config.get_encoder(), '-gpu', str(encoder_config.get_nvenc_gpu_id()), '-preset', str(encoder_config.get_encoding_preset()), '-profile', encoder_config.get_encoding_profile(), '-rc', 'vbr', '-b:v', '0', '-cq', str(encoder_config.get_encoding_crf())] ffmpeg_selected = GlobalValues().getFFmpegPath() if encoder_config.ffmpeg_output_fps_enabled(): encoder_preset = encoder_preset + ['-r', str(encoder_config.ffmpeg_output_fps_value())] if mode == 1: input_ffmpeg = ['-r', str(output_fps), '-i', 'interpolated_frames/%15d.png'] if mode == 3 or mode == 4: # generateTimecodesFile(projectFolder) choose_frames(project_folder + os.path.sep + "interpolated_frames", output_fps) input_ffmpeg = ['-vsync', '1', '-r', str(output_fps), '-f', 'concat', '-safe', '0', '-i', 'interpolated_frames/framesCFR.txt'] # Audio codec if encoder_config.get_lossless_encoding(): encoder_preset = encoder_preset + ['-c:a', 'alac'] if not loopable or (max_loop_length / float(input_length) < 2): # Don't loop, too long input command = [ffmpeg_selected, '-hide_banner', '-stats', '-loglevel', 'error', '-y'] command = command + input_ffmpeg command = command + ['-i', str(input_file), '-map', '0', '-map', '1:a?', '-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2'] command = command + encoder_preset + [str(output_video)] run_and_print_output(command) else: loop_count = math.ceil(preferred_loop_length / float(input_length)) - 1 loop_count = str(loop_count) command = [FFMPEG4, '-y', '-stream_loop', str(loop_count), '-i', str(input_file), '-vn', 'loop.flac'] run_and_print_output(command) audio_input = [] if os.path.exists('loop.flac'): audio_input = ['-i', 'loop.flac', '-map', '0', '-map', '1'] # print("Looped audio exists") command = [FFMPEG4, '-hide_banner', '-stats', '-loglevel', 'error', '-y', '-stream_loop', str(loop_count)] command = command + input_ffmpeg command = command + ['-pix_fmt', encoder_config.get_pixel_format(), '-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2', '-f', 'yuv4mpegpipe', '-'] command2 = [ffmpeg_selected, '-y', '-i', '-'] command2 = command2 + audio_input + encoder_preset + [str(output_video)] # Looping pipe pipe1 = subprocess.Popen(command, stdout=subprocess.PIPE) output = "" try: output = subprocess.check_output(command2, shell=False, universal_newlines=True, stdin=pipe1.stdout, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: print(output) pipe1.wait() # ---END looping pipe--- if os.path.exists('loop.flac'): os.remove('loop.flac') print("---Finished Encoding---") def generateLoopContinuityFrame(framesFolder): ''' Copy first frame to last frame so the interpolator can properly create a looping output :param framesFolder: Path to folder with frames :return: ''' files = os.listdir(framesFolder) files.sort() # Find the distance between the first two and last two frames # Use this distance to calculate position for the loop continuity frame beginFirst = int(files[0][:-4]) endFirst = int(files[1][:-4]) beginLast = int(files[-2][:-4]) endLast = int(files[-1][:-4]) averageDistance = int(((endFirst - beginFirst) + (endLast - beginLast)) / 2) # Create frame shutil.copy(framesFolder + '/' + files[0], framesFolder + '/' + '{:015d}.png'.format(endLast + averageDistance)) print("Made loop continuity frame:", framesFolder + '/' + '{:015d}.png'.format(endLast + averageDistance)) def removeLoopContinuityFrame(framesFolder): ''' Removes last frame (In sequence) in folder :param framesFolder: Path to folder with frames :return: ''' files = os.listdir(framesFolder) files.sort() os.remove(framesFolder + '/' + files[-1]) def generateTimecodesFile(projectFolder): ''' Scan a folder full of PNG frames and generate a timecodes file for FFmpeg ''' os.chdir(projectFolder) files = os.listdir("interpolated_frames") files.sort() # Generate duration for last frame beginFirst = int(files[0][:-4]) endFirst = int(files[1][:-4]) beginLast = int(files[-2][:-4]) endLast = int(files[-1][:-4]) averageDistance = int(((endFirst - beginFirst) + (endLast - beginLast)) / 2) f = open("interpolated_frames/frames.txt", "w") for i in range(0, len(files) - 1): # Calculate time duration between frames currentFrameFile = files[i] nextFrameFile = files[i + 1] # Each file has a .png extention, use [:-4] to remove frameDuration = int(int(nextFrameFile[:-4]) - int(currentFrameFile[:-4])) # Write line f.write( "file '" + projectFolder + "/interpolated_frames/" + currentFrameFile + "'\nduration " + "{:.5f}".format( float(frameDuration / float(GlobalValues.timebase))) + "\n") # Generate last frame lastFrameName = "{:015d}.png".format(endLast) f.write("file '" + projectFolder + "/interpolated_frames/" + lastFrameName + "'\nduration " + "{:.5f}".format( float(averageDistance / float(GlobalValues.timebase))) + "\n") f.close() def getOutputFPS(inputFile: str, mode: int, interpolationFactor: int, useAccurateFPS: bool, accountForDuplicateFrames: bool, mpdecimateSensitivity): ''' Takes an input file, and calculates the output FPS from a given interpolation factor Accurate FPS uses FFmpeg tbc for FPS AccountForDuplicateFrames runs mpdecimate and calculates FPS with duplicates removed ''' if (mode == 3 or mode == 4) and accountForDuplicateFrames: return (get_frame_count(inputFile, True, mpdecimateSensitivity) / get_length(inputFile)) * interpolationFactor if useAccurateFPS: return get_fps_accurate(inputFile) * interpolationFactor else: return get_fps(inputFile) * interpolationFactor def performAllSteps(inputFile, interpolatorConfig: InterpolatorConfig, encoderConfig: EncoderConfig, useAutoEncode=False, autoEncodeBlockSize=3000, step1=True, step2=True, step3=True): ''' Perform all interpolation steps; extract, interpolate, encode Options to run individual steps :param interpolatorConfig: :param encoderConfig: ''' interpolationFactor = interpolatorConfig.getInterpolationFactor() loopable = interpolatorConfig.getLoopable() mode = interpolatorConfig.getMode() clearPNGs = interpolatorConfig.getClearPngs() nonLocalPNGs = interpolatorConfig.getNonlocalPngs() scenechangeSensitivity = interpolatorConfig.getScenechangeSensitivity() mpdecimateSensitivity = interpolatorConfig.getMpdecimateSensitivity() useAccurateFPS = interpolatorConfig.getUseAccurateFPS() accountForDuplicateFrames = interpolatorConfig.getAccountForDuplicateFrames() # Get project folder path and make it if it doesn't exist projectFolder = inputFile[:inputFile.rindex(os.path.sep)] if nonLocalPNGs: projectFolder = installPath + os.path.sep + "tempFrames" if not os.path.exists(projectFolder): os.mkdir(projectFolder) if step1: # Clear pngs if they exist if os.path.exists(projectFolder + '/' + 'original_frames'): shutil.rmtree(projectFolder + '/' + 'original_frames') if os.path.exists(projectFolder + '/' + 'interpolated_frames'): shutil.rmtree(projectFolder + '/' + 'interpolated_frames') extractFrames(inputFile, projectFolder, mode, interpolatorConfig, mpdecimateSensitivity) if not step2 and not step3: return # Get outputFPS - Use mode 3 target FPS unless not mode 3 or not enabled outputFPS = interpolatorConfig.getMode3TargetFPSValue() if not interpolatorConfig.getMode3TargetFPSEnabled() or not mode == 3: outputFPS = getOutputFPS(inputFile, mode, interpolationFactor, useAccurateFPS, accountForDuplicateFrames, mpdecimateSensitivity) interpolationFactorFileLabel = [str(interpolationFactor), 'x'] if interpolatorConfig.getMode3TargetFPSEnabled() and mode == 3: interpolationFactorFileLabel = ['TargetFPS'] # Interpolation AI name interpolationAIname = '-' + interpolatorConfig.getInterpolator().lower() + '-' # Generate output name outputVideoNameSegments = ['{:.2f}'.format(outputFPS), 'fps-'] + interpolationFactorFileLabel + ['-mode', str(mode), interpolationAIname, inputFile[ inputFile.rindex( os.path.sep) + 1:inputFile.rindex( '.')], '.mp4'] # If limit output FPS is enabled if encoderConfig.ffmpeg_output_fps_enabled(): outputVideoNameSegments[0] = '{:.2f}'.format(encoderConfig.ffmpeg_output_fps_value()) outputVideoName = inputFile[:inputFile.rindex(os.path.sep) + 1] + ''.join(outputVideoNameSegments) if step2: # Auto encoding interpolationDone = [False] autoEncodeThread = None if useAutoEncode: ''' Wait for the thread to start, because python is stupid, and will not start it if the interpolator manages to start first''' waitForThreadStart = [False] if mode == 1: autoEncodeThread = threading.Thread(target=autoEncoding.mode1AutoEncoding_Thread, args=( waitForThreadStart, projectFolder, inputFile, outputVideoName, interpolationDone, outputFPS, currentSavingPNGRanges, encoderConfig, autoEncodeBlockSize,)) elif mode == 3 or mode == 4: autoEncodeThread = threading.Thread(target=autoEncoding.mode34AutoEncoding_Thread, args=( waitForThreadStart, projectFolder, inputFile, outputVideoName, interpolationDone, outputFPS, currentSavingPNGRanges, encoderConfig, autoEncodeBlockSize,)) autoEncodeThread.start() while waitForThreadStart[0] == False: time.sleep(1) outParams = runInterpolator(projectFolder, interpolatorConfig, outputFPS) if outParams[0] == -1: # Batch threads hit their restart limit - just DIE return print('---INTERPOLATION DONE---') interpolationDone[0] = True if useAutoEncode: autoEncodeThread.join() print("---AUTO ENCODING DONE---") if step3: if not useAutoEncode: create_output(inputFile, projectFolder, outputVideoName, outputFPS, loopable, mode, encoderConfig) if clearPNGs: shutil.rmtree(projectFolder + '/' + 'original_frames') shutil.rmtree(projectFolder + '/' + 'interpolated_frames') print("Created output file: {}".format(outputVideoName)) def batchInterpolateFolder(inputDirectory, interpolatorConfig: InterpolatorConfig, fpsTarget, encoderConfig: EncoderConfig, useAutoEncode=False, autoEncodeBlockSize=3000): ''' Batch process a folder to a specified fpsTarget Using performAllSteps on each file Checks to see if each input file isn't already above fpsTarget :param interpolatorConfig: :param encoderConfig: ''' mode = interpolatorConfig.getMode() mpdecimateSensitivity = interpolatorConfig.getMpdecimateSensitivity() useAccurateFPS = interpolatorConfig.getUseAccurateFPS() accountForDuplicateFrames = interpolatorConfig.getAccountForDuplicateFrames() input_files = [] for root, directories, files in os.walk(inputDirectory): for file in files: input_files.append(os.path.join(root, file)) input_files.sort() for inputVideoFile in input_files: try: print(inputVideoFile) currentFPS = getOutputFPS(inputVideoFile, mode, 1, useAccurateFPS, accountForDuplicateFrames, mpdecimateSensitivity) # Attempt to interpolate everything to above 59fps targetFPS = fpsTarget exponent = 1 if currentFPS < targetFPS: while (currentFPS * (2 ** exponent)) < targetFPS: exponent += 1 else: continue interpolatorConfig.setInterpolationFactor(int(2 ** exponent)) # use [l] to denote whether the file is a loopable video print("looping?", '[l]' in inputVideoFile) if '[l]' in inputVideoFile: print("LOOP") interpolatorConfig.setLoopable(True) encoderConfig.loopRepetitionsEnabled = True performAllSteps(inputVideoFile, interpolatorConfig, encoderConfig, useAutoEncode, autoEncodeBlockSize) else: print("DON'T LOOP") interpolatorConfig.setLoopable(False) encoderConfig.loopRepetitionsEnabled = False performAllSteps(inputVideoFile, interpolatorConfig, encoderConfig, useAutoEncode, autoEncodeBlockSize) except: traceback.print_exc()
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,985
HeylonNHP/RIFE-Colab
refs/heads/main
/QueuedFrames/FrameFile.py
import cv2 import numpy import os class FrameFile: filePath: str = None imageData = None def __init__(self, filePath: str): self.filePath = filePath def __str__(self): return self.filePath def setImageData(self, imageData): self.imageData = imageData def getImageData(self): return self.imageData def saveImageData(self): if not os.path.exists(self.filePath): cv2.imwrite(self.filePath, self.imageData) def loadImageData(self): self.imageData = cv2.imread(self.filePath,cv2.IMREAD_UNCHANGED) #print(self.imageData.dtype) #print(self.imageData) #self.imageData = self.imageData.astype(numpy.uint8)
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,986
HeylonNHP/RIFE-Colab
refs/heads/main
/runAndPrintOutput.py
from subprocess import Popen, PIPE, STDOUT, run def run_and_print_output(array_command: list): # result = run(arrayCommand, shell=False, universal_newlines=True, stderr=STDOUT, check=False).stdout p = Popen(array_command, shell=False, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) result = p.stdout.read() print(result)
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,987
HeylonNHP/RIFE-Colab
refs/heads/main
/Globals/InterpolatorConfig.py
class InterpolatorConfig: _interpolators = ["RIFE"] _interpolator = "RIFE" _interpolationFactor = 2 _loopable = False _mode = 1 _clearPngs = True _nonLocalPngs = True _scenechangeSensitivity = 0.20 _mpdecimateSensitivity = "64*12,64*8,0.33" _enableMpdecimate = True _useAccurateFPS = True _accountForDuplicateFrames = False _UhdScaleFactor: float = 0.5 _mode3TargetFPSEnabled: bool = False _mode3TargetFPSValue: float = 60 _backupThreadStartLimit = -1 _exitOnBackupThreadLimit = False def setInterpolationFactor(self, interpolationFactor: int): self._interpolationFactor = interpolationFactor def getInterpolationFactor(self): return self._interpolationFactor def setLoopable(self, loopable: bool): self._loopable = loopable def getLoopable(self): return self._loopable def setMode(self, mode: int): modes = [1, 3, 4] assert mode in modes self._mode = mode def getMode(self): return self._mode def setClearPngs(self, clearPngs: bool): self._clearPngs = clearPngs def getClearPngs(self): return self._clearPngs def setNonlocalPngs(self, nonlocalpngs: bool): self._nonLocalPngs = nonlocalpngs def getNonlocalPngs(self): return self._nonLocalPngs def setScenechangeSensitivity(self, sensitivity: float): assert 1 >= sensitivity >= 0 self._scenechangeSensitivity = sensitivity def getScenechangeSensitivity(self): return self._scenechangeSensitivity def enableMpdecimate(self, enable): self._enableMpdecimate = enable def getMpdecimatedEnabled(self): return self._enableMpdecimate def setMpdecimateSensitivity(self, sensitivity: str): self._mpdecimateSensitivity = sensitivity def getMpdecimateSensitivity(self): return self._mpdecimateSensitivity def setUseAccurateFPS(self, enable: bool): self._useAccurateFPS = enable def getUseAccurateFPS(self): return self._useAccurateFPS def setAccountForDuplicateFrames(self, enable: bool): self._accountForDuplicateFrames = enable def getAccountForDuplicateFrames(self): return self._accountForDuplicateFrames def setUhdScale(self, scaleFactor: float): self._UhdScaleFactor = scaleFactor def getUhdScale(self): return self._UhdScaleFactor def setMode3TargetFPS(self, enable: bool, value: float): self._mode3TargetFPSEnabled = enable self._mode3TargetFPSValue = value def getMode3TargetFPSEnabled(self): return self._mode3TargetFPSEnabled def getMode3TargetFPSValue(self): return self._mode3TargetFPSValue def setInterpolator(self, interpolator: str): self._interpolator = interpolator def getInterpolator(self): return self._interpolator def setBackupThreadStartLimit(self, limit: int): self._backupThreadStartLimit = limit def getBackupThreadStartLimit(self): return self._backupThreadStartLimit def setExitOnBackupThreadLimit(self, exit: bool): self._exitOnBackupThreadLimit = exit if not exit: self.setBackupThreadStartLimit(-1) def getExitOnBackupThreadLimit(self): return self._exitOnBackupThreadLimit
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,988
HeylonNHP/RIFE-Colab
refs/heads/main
/main_gui.py
# https://raevskymichail.medium.com/python-gui-building-a-simple-application-with-pyqt-and-qt-designer-e9f8cda76246 import glob import json # from PyQt5 import uic import os import sys # from PyQt5 import QtWidgets from PyQt5 import QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import mainGuiUi from Globals.MachinePowerStatesHandler import MachinePowerStatesHandler sys.path.insert(0, os.getcwd() + os.path.sep + 'arXiv2020RIFE') print(sys.path) from generalInterpolationProceedures import * def grab_latest_rife_model(): download_rife(installPath, onWindows, force_download_models=True) class RIFEGUIMAINWINDOW(QMainWindow, mainGuiUi.Ui_MainWindow): main_gui_path = os.path.realpath(__file__) main_gui_path = main_gui_path[:main_gui_path.rindex(os.path.sep)] MAIN_PRESET_FILE = main_gui_path + os.path.sep + "defaults.preset" progressBarUpdateSignal = pyqtSignal(object) runAllStepsButtonEnabledSignal = pyqtSignal(bool) extractFramesButtonEnabledSignal = pyqtSignal(bool) interpolateFramesButtonEnabledSignal = pyqtSignal(bool) encodeOutputButtonEnabledSignal = pyqtSignal(bool) batchProcessingMode: bool = False nonBatchControlLabels: dict = {} def __init__(self): # This is needed here for variable and method access super().__init__() self.setupUi(self) # Initialize a design # uic.loadUi("main_gui.ui", self) self.mode3_extra_options_enable(False) self.verticalLayout_6.setAlignment(Qt.AlignTop) self.verticalLayout_5.setAlignment(Qt.AlignTop) self.verticalLayout_4.setAlignment(Qt.AlignTop) self.verticalLayout_3.setAlignment(Qt.AlignTop) self.verticalLayout_2.setAlignment(Qt.AlignTop) self.updateRifeModelButton.clicked.connect(grab_latest_rife_model) self.browseInputButton.clicked.connect(self.browse_input_file) self.runAllStepsButton.clicked.connect(self.run_all_steps) self.extractFramesButton.clicked.connect(self.run_step_1) self.interpolateFramesButton.clicked.connect(self.run_step_2) self.encodeOutputButton.clicked.connect(self.run_step_3) self.interpolationFactorSelect.currentTextChanged.connect(self.update_video_fps_stats) self.accountForDuplicateFramesCheckbox.stateChanged.connect(self.update_video_fps_stats) self.useAccurateFPSCheckbox.stateChanged.connect(self.update_video_fps_stats) self.modeSelect.currentTextChanged.connect(self.update_video_fps_stats) self.mode3TargetFPS.valueChanged.connect(self.update_video_fps_stats) self.mode3UseTargetFPS.toggled.connect(self.update_video_fps_stats) self.mode3UseInterpolationFactor.toggled.connect(self.update_video_fps_stats) self.modeSelect.currentTextChanged.connect(self.check_current_mode) subscribeTointerpolationProgressUpdate(self.get_progress_update) self.progressBarUpdateSignal.connect(self.update_ui_progress) self.runAllStepsButtonEnabledSignal.connect(self.update_run_all_steps_button_enabled) self.extractFramesButtonEnabledSignal.connect(self.update_extract_frames_button_enabled) self.interpolateFramesButtonEnabledSignal.connect(self.update_interpolate_frames_button_enabled) self.encodeOutputButtonEnabledSignal.connect(self.update_encode_output_button_enabled) self.tabWidget.currentChanged.connect(self.changed_tabs) self.nonBatchControlLabels['input'] = self.inputLabel.text() self.nonBatchControlLabels['runall'] = self.runAllStepsButton.text() self.saveGUIstateCheck.stateChanged.connect(self.on_save_gui_state_check_change) self.load_settings_file(self.MAIN_PRESET_FILE) self.preset_update_list() self.createNewPresetButton.clicked.connect(self.preset_create_new) self.saveSelectedPresetButton.clicked.connect(self.preset_save) self.loadSelectedPresetButton.clicked.connect(self.preset_load) self.deleteSelectedPresetButton.clicked.connect(self.preset_delete) self.inputFilePathText.textChanged.connect(self.input_box_text_changed) self.enableLosslessEncodingCheck.stateChanged.connect(self.lossless_mode_check_change) def changed_tabs(self): if self.tabWidget.currentIndex() == 3: self.batchProcessingMode = True self.inputLabel.setText("Input folder") self.runAllStepsButton.setText("Run Batch") self.extractFramesButton.setEnabled(False) self.interpolateFramesButton.setEnabled(False) self.encodeOutputButton.setEnabled(False) else: self.batchProcessingMode = False self.inputLabel.setText(self.nonBatchControlLabels['input']) self.runAllStepsButton.setText(self.nonBatchControlLabels['runall']) self.extractFramesButton.setEnabled(True) self.interpolateFramesButton.setEnabled(True) self.encodeOutputButton.setEnabled(True) def lossless_mode_check_change(self): self.crfoutNumber.setEnabled(not self.enableLosslessEncodingCheck.isChecked()) def mode3_extra_options_enable(self, enable: bool): self.mode3UseInterpolationFactor.setHidden(not enable) self.mode3UseTargetFPS.setHidden(not enable) self.mode3TargetFPS.setHidden(not enable) def check_current_mode(self): mode: int = int(self.modeSelect.currentText()) if mode == 3: self.mode3_extra_options_enable(True) else: self.mode3_extra_options_enable(False) def input_box_text_changed(self): if not self.batchProcessingMode: self.update_video_fps_stats() def browse_input_file(self): file = None if not self.batchProcessingMode: file, _filter = QFileDialog.getOpenFileName(caption="Open video file to interpolate") else: file = str(QFileDialog.getExistingDirectory(caption="Open folder of files to interpolate")) print(str(file)) self.inputFilePathText.setText(file) if not self.batchProcessingMode: self.update_video_fps_stats() lastMPdecimate: str = "" lastVideoPath: str = "" lastVideoFPS: float = None def update_video_fps_stats(self): file = str(self.inputFilePathText.text()) if not os.path.exists(file): return if not os.path.isfile(file): return accurate_fps: bool = self.useAccurateFPSCheckbox.isChecked() account_for_duplicates_in_fps: bool = self.accountForDuplicateFramesCheckbox.isChecked() video_fps = None mode = int(str(self.modeSelect.currentText())) current_mpdecimate = str(self.mpdecimateText.text()) current_video_path = str(self.inputFilePathText.text()) if (mode == 3 or mode == 4) and account_for_duplicates_in_fps: if self.lastVideoFPS is not None and self.lastMPdecimate == current_mpdecimate and current_video_path == self.lastVideoPath: video_fps = self.lastVideoFPS if video_fps is None: video_fps = getOutputFPS(str(file), int(str(self.modeSelect.currentText())), 1, accurate_fps, account_for_duplicates_in_fps, str(self.mpdecimateText.text())) if (mode == 3 or mode == 4) and account_for_duplicates_in_fps: self.lastVideoFPS = video_fps self.lastMPdecimate = str(self.mpdecimateText.text()) self.lastVideoPath = current_video_path print(video_fps) self.VideostatsInputFPStext.setText(str(video_fps)) if mode == 3 and self.mode3UseTargetFPS.isChecked(): self.VideostatsOutputFPStext.setText(str(self.mode3TargetFPS.value())) else: self.VideostatsOutputFPStext.setText(str(video_fps * float(self.interpolationFactorSelect.currentText()))) def run_step_1(self): self.run_all_interpolation_steps(step1=True, step2=False, step3=False) def run_step_2(self): self.run_all_interpolation_steps(step1=False, step2=True, step3=False) def run_step_3(self): self.run_all_interpolation_steps(step1=False, step2=False, step3=True) def run_all_steps(self): # This function is required because python is stupid, and will set the first boolean function parameter to false self.run_all_interpolation_steps() def run_all_interpolation_steps(self, step1=True, step2=True, step3=True): selected_gpus = str(self.gpuidsSelect.currentText()).split(",") selected_gpus = [int(i) for i in selected_gpus] encoder_config: EncoderConfig = EncoderConfig() encoder_config.set_nvenc_gpu_id(selected_gpus[0]) # setNvencSettings(selected_gpus[0], 'slow') setGPUinterpolationOptions(int(self.batchthreadsNumber.value()), selected_gpus) input_file = str(self.inputFilePathText.text()) if os.name == 'nt': input_file = input_file.replace('/', '\\') if self.batchProcessingMode: if not os.path.isdir(input_file): QMessageBox.critical(self, "Path", "For batch processing, the input path must be a folder") return else: if not os.path.isfile(input_file): QMessageBox.critical(self, "Path", "For single video processing, the input path must be a video file") return interpolation_factor = int(self.interpolationFactorSelect.currentText()) loopable = bool(self.loopoutputCheck.isChecked()) loop_repetitions = bool(self.loopOutputRepeatedLoopsCheck.isChecked()) loop_preferred_length = float(self.loopOutputPreferredLengthNumber.value()) loop_max_length = float(self.loopOutputMaxLengthNumber.value()) mode = int(self.modeSelect.currentText()) crf_out = int(self.crfoutNumber.value()) clear_pngs = bool(self.clearpngsCheck.isChecked()) non_local_pngs = bool(self.nonlocalpngsCheck.isChecked()) scenechange_sensitivity = float(self.scenechangeSensitivityNumber.value()) mpdecimate_sensitivity = str(self.mpdecimateText.text()) mpdecimate_enabled = bool(self.mpdecimateEnableCheck.isChecked()) use_nvenc = bool(self.nvencCheck.isChecked()) use_autoencode = bool(self.autoencodeCheck.isChecked()) block_size = int(self.autoencodeBlocksizeNumber.value()) limit_fps_enabled: bool = bool(self.enableLimitFPScheck.isChecked()) limit_fps_value: float = float(self.limitFPSnumber.value()) mode3_target_fps_enabled: bool = bool(self.mode3UseTargetFPS.isChecked()) mode3_target_fps_value: float = float(self.mode3TargetFPS.value()) interpolation_ai: str = str(self.InterpolationAIComboBox.currentText()) losslessEncoding: bool = bool(self.enableLosslessEncodingCheck.isChecked()) target_fps = float(self.targetFPSnumber.value()) accurate_fps: bool = self.useAccurateFPSCheckbox.isChecked() account_for_duplicates_in_fps: bool = self.accountForDuplicateFramesCheckbox.isChecked() after_interpolation_action: int = self.systemPowerOptionsComboBox.currentIndex() use_half_precision_checked: bool = self.enableHalfPrecisionFloatsCheck.isChecked() output_encoder_selection: int = self.outputEncoderSelectComboBox.currentIndex() output_colourspace: str = self.colourspaceSelectionComboBox.currentText() uhd_scale_factor: float = self.UHDscaleNumber.value() set_use_half_precision(use_half_precision_checked) if use_nvenc: encoder_config.enable_nvenc(True) encoder_config.set_encoding_preset('slow') encoder_config.set_encoding_crf(crf_out + 10) else: encoder_config.set_encoding_preset('veryslow') encoder_config.set_encoding_crf(crf_out) if output_encoder_selection == 0: encoder_config.enable_h265(False) encoder_config.set_encoding_profile('high') else: encoder_config.enable_h265(True) encoder_config.set_encoding_profile('main') if limit_fps_enabled: encoder_config.set_ffmpeg_output_fps(limit_fps_enabled, limit_fps_value) encoder_config.set_lossless_encoding(losslessEncoding) encoder_config.set_pixel_format(output_colourspace) encoder_config.set_looping_options(loop_preferred_length, loop_max_length, loop_repetitions) interpolator_config = InterpolatorConfig() interpolator_config.setMode(mode) interpolator_config.setClearPngs(clear_pngs) interpolator_config.setLoopable(loopable) interpolator_config.setAccountForDuplicateFrames(account_for_duplicates_in_fps) interpolator_config.setInterpolationFactor(interpolation_factor) interpolator_config.setMpdecimateSensitivity(mpdecimate_sensitivity) interpolator_config.setUseAccurateFPS(accurate_fps) interpolator_config.setNonlocalPngs(non_local_pngs) interpolator_config.setScenechangeSensitivity(scenechange_sensitivity) interpolator_config.setUhdScale(uhd_scale_factor) interpolator_config.setMode3TargetFPS(mode3_target_fps_enabled, mode3_target_fps_value) interpolator_config.setInterpolator(interpolation_ai) interpolator_config.enableMpdecimate(mpdecimate_enabled) interpolator_config.setExitOnBackupThreadLimit(bool(self.threadRestartsMaxCheckbox.isChecked())) interpolator_config.setBackupThreadStartLimit(int(self.threadRestartsMaxSpinBox.value())) # Exceptions are hidden on the PYQt5 thread - Run interpolator on separate thread to see them interpolate_thread = threading.Thread(target=self.run_all_interpolation_steps_thread, args=( input_file, interpolator_config, use_autoencode, block_size, target_fps, step1, step2, step3, encoder_config, after_interpolation_action)) interpolate_thread.start() def run_all_interpolation_steps_thread(self, input_file, interpolator_config: InterpolatorConfig, use_auto_encode, block_size, target_fps, step1, step2, step3, encoder_config: EncoderConfig, after_interpolation_is_finished_action_choice=0): batch_processing = self.batchProcessingMode self.runAllStepsButtonEnabledSignal.emit(False) if not batch_processing: self.extractFramesButtonEnabledSignal.emit(False) self.interpolateFramesButtonEnabledSignal.emit(False) self.encodeOutputButtonEnabledSignal.emit(False) if not batch_processing: performAllSteps(input_file, interpolator_config, encoder_config, use_auto_encode, block_size, step1=step1, step2=step2, step3=step3) else: batchInterpolateFolder(input_file, interpolator_config, target_fps, encoder_config, use_auto_encode, block_size) self.runAllStepsButtonEnabledSignal.emit(True) if not batch_processing: self.extractFramesButtonEnabledSignal.emit(True) self.interpolateFramesButtonEnabledSignal.emit(True) self.encodeOutputButtonEnabledSignal.emit(True) if step3 or (use_auto_encode and step2): # The user likely doesn't want the machine to shutdown/suspend before the output is processed mps = MachinePowerStatesHandler() if after_interpolation_is_finished_action_choice == 1: # Shutdown mps.shutdownComputer() elif after_interpolation_is_finished_action_choice == 2: # Suspend mps.suspendComputer() def get_progress_update(self, progress: InterpolationProgress): self.progressBarUpdateSignal.emit(progress) def update_ui_progress(self, data: InterpolationProgress): self.interpolationProgressBar.setMaximum(data.totalFrames) self.interpolationProgressBar.setValue(data.completedFrames) def update_run_all_steps_button_enabled(self, data: bool): self.runAllStepsButton.setEnabled(data) def update_extract_frames_button_enabled(self, data: bool): self.extractFramesButton.setEnabled(data) def update_interpolate_frames_button_enabled(self, data: bool): self.interpolateFramesButton.setEnabled(data) def update_encode_output_button_enabled(self, data: bool): self.encodeOutputButton.setEnabled(data) def get_current_ui_settings(self): settings_dict = {'mpdecimate': str(self.mpdecimateText.text()), 'nonlocalpngs': bool(self.nonlocalpngsCheck.isChecked()), 'clearpngs': bool(self.clearpngsCheck.isChecked()), 'enableMpdecimate': bool(self.mpdecimateEnableCheck.isChecked()), 'useaccuratefps': bool(self.useAccurateFPSCheckbox.isChecked()), 'accountforduplicateframes': bool(self.accountForDuplicateFramesCheckbox.isChecked()), 'interpolationfactor': str(self.interpolationFactorSelect.currentText()), 'framehandlingmode': int(self.modeSelect.currentIndex()), 'scenechangesensitivity': float(self.scenechangeSensitivityNumber.value()), 'gpuids': str(self.gpuidsSelect.currentText()), 'batchthreads': int(self.batchthreadsNumber.value()), 'useHalfPrecisionFloats': bool(self.enableHalfPrecisionFloatsCheck.isChecked()), 'UHDscaleFactor': float(self.UHDscaleNumber.value()), 'interpolationAIchoice': int(self.InterpolationAIComboBox.currentIndex()), 'mode3UseInterpolationFactor': bool(self.mode3UseInterpolationFactor.isChecked()), 'mode3UseTargetFPS': bool(self.mode3UseTargetFPS.isChecked()), 'mode3TargetFPS': float(self.mode3TargetFPS.value()), 'loopoutput': bool(self.loopoutputCheck.isChecked()), 'loopablePreferredLength': float(self.loopOutputPreferredLengthNumber.value()), 'loopableMaxLength': float(self.loopOutputMaxLengthNumber.value()), 'loopRepetitionsEnabled': bool(self.loopOutputRepeatedLoopsCheck.isChecked()), 'usenvenc': bool(self.nvencCheck.isChecked()), 'crfout': float(self.crfoutNumber.value()), 'useautoencoding': bool(self.autoencodeCheck.isChecked()), 'autoencodingblocksize': int(self.autoencodeBlocksizeNumber.value()), 'outputEncoderSelection': int(self.outputEncoderSelectComboBox.currentIndex()), 'outputPixelFormat': int(self.colourspaceSelectionComboBox.currentIndex()), 'limitFPSEnable': bool(self.enableLimitFPScheck.isChecked()), 'limitFPSValue': float(self.limitFPSnumber.value()), 'batchtargetfps': float(self.targetFPSnumber.value()), 'saveguistate': bool(self.saveGUIstateCheck.isChecked()), 'systemPowerOption': int(self.systemPowerOptionsComboBox.currentIndex()), 'limitBackupThreadRestarts': ( bool(self.threadRestartsMaxCheckbox.isChecked()), int(self.threadRestartsMaxSpinBox.value())), 'losslessEncodingEnabled': bool(self.enableLosslessEncodingCheck.isChecked())} return settings_dict def set_current_ui_settings(self, settings_dict: dict): if 'mpdecimate' in settings_dict: self.mpdecimateText.setText(settings_dict['mpdecimate']) if 'nonlocalpngs' in settings_dict: self.nonlocalpngsCheck.setChecked(settings_dict['nonlocalpngs']) if 'clearpngs' in settings_dict: self.clearpngsCheck.setChecked(settings_dict['clearpngs']) if 'enableMpdecimate' in settings_dict: self.mpdecimateEnableCheck.setChecked(settings_dict['enableMpdecimate']) if 'useaccuratefps' in settings_dict: self.useAccurateFPSCheckbox.setChecked(settings_dict['useaccuratefps']) if 'accountforduplicateframes' in settings_dict: self.accountForDuplicateFramesCheckbox.setChecked(settings_dict['accountforduplicateframes']) if 'interpolationfactor' in settings_dict: self.interpolationFactorSelect.setCurrentText(settings_dict['interpolationfactor']) if 'framehandlingmode' in settings_dict: self.modeSelect.setCurrentIndex(settings_dict['framehandlingmode']) if 'scenechangesensitivity' in settings_dict: self.scenechangeSensitivityNumber.setValue(settings_dict['scenechangesensitivity']) if 'gpuids' in settings_dict: self.gpuidsSelect.setCurrentText(settings_dict['gpuids']) if 'batchthreads' in settings_dict: self.batchthreadsNumber.setValue(settings_dict['batchthreads']) if 'useHalfPrecisionFloats' in settings_dict: self.enableHalfPrecisionFloatsCheck.setChecked(settings_dict['useHalfPrecisionFloats']) if 'UHDscaleFactor' in settings_dict: self.UHDscaleNumber.setValue(settings_dict['UHDscaleFactor']) if 'interpolationAIchoice' in settings_dict: self.InterpolationAIComboBox.setCurrentIndex(settings_dict['interpolationAIchoice']) if 'mode3UseInterpolationFactor' in settings_dict: self.mode3UseInterpolationFactor.setChecked(settings_dict['mode3UseInterpolationFactor']) if 'mode3UseTargetFPS' in settings_dict: self.mode3UseTargetFPS.setChecked(settings_dict['mode3UseTargetFPS']) if 'mode3TargetFPS' in settings_dict: self.mode3TargetFPS.setValue(settings_dict['mode3TargetFPS']) if 'loopoutput' in settings_dict: self.loopoutputCheck.setChecked(settings_dict['loopoutput']) if 'loopablePreferredLength' in settings_dict: self.loopOutputPreferredLengthNumber.setValue(settings_dict['loopablePreferredLength']) if 'loopableMaxLength' in settings_dict: self.loopOutputMaxLengthNumber.setValue(settings_dict['loopableMaxLength']) if 'loopRepetitionsEnabled' in settings_dict: self.loopOutputRepeatedLoopsCheck.setChecked(settings_dict['loopRepetitionsEnabled']) if 'usenvenc' in settings_dict: self.nvencCheck.setChecked(settings_dict['usenvenc']) if 'crfout' in settings_dict: self.crfoutNumber.setValue(settings_dict['crfout']) if 'useautoencoding' in settings_dict: self.autoencodeCheck.setChecked(settings_dict['useautoencoding']) if 'autoencodingblocksize' in settings_dict: self.autoencodeBlocksizeNumber.setValue(settings_dict['autoencodingblocksize']) if 'outputEncoderSelection' in settings_dict: self.outputEncoderSelectComboBox.setCurrentIndex(settings_dict['outputEncoderSelection']) if 'outputPixelFormat' in settings_dict: self.colourspaceSelectionComboBox.setCurrentIndex(settings_dict['outputPixelFormat']) if 'limitFPSEnable' in settings_dict: self.enableLimitFPScheck.setChecked(settings_dict['limitFPSEnable']) if 'limitFPSValue' in settings_dict: self.limitFPSnumber.setValue(settings_dict['limitFPSValue']) if 'batchtargetfps' in settings_dict: self.targetFPSnumber.setValue(settings_dict['batchtargetfps']) if 'saveguistate' in settings_dict: self.saveGUIstateCheck.setChecked(settings_dict['saveguistate']) if 'systemPowerOption' in settings_dict: self.systemPowerOptionsComboBox.setCurrentIndex(settings_dict['systemPowerOption']) if 'limitBackupThreadRestarts' in settings_dict: limit_backup_thread_restarts = settings_dict['limitBackupThreadRestarts'] self.threadRestartsMaxCheckbox.setChecked(limit_backup_thread_restarts[0]) self.threadRestartsMaxSpinBox.setValue(limit_backup_thread_restarts[1]) if 'losslessEncodingEnabled' in settings_dict: self.enableLosslessEncodingCheck.setChecked(settings_dict['losslessEncodingEnabled']) def save_settings_file(self, filename: str): settings_dict = self.get_current_ui_settings() out_file = open(filename, 'w') out_file.write(json.dumps(settings_dict)) out_file.close() def load_settings_file(self, filename: str): if not os.path.isfile(filename): return in_file = open(filename, 'r') settings_dict: dict = json.loads(in_file.read()) in_file.close() self.set_current_ui_settings(settings_dict) def on_save_gui_state_check_change(self): # Remove preset file if user chooses not to save GUI state if not self.saveGUIstateCheck.isChecked(): if os.path.isfile(self.MAIN_PRESET_FILE): os.remove(self.MAIN_PRESET_FILE) def preset_update_list(self): self.presetListComboBox.clear() for data in glob.glob(self.main_gui_path + os.path.sep + "*.preset"): self.presetListComboBox.addItem(data[data.rindex(os.path.sep) + 1:]) def preset_create_new(self): preset_name, ok_pressed = QInputDialog.getText(self, "Enter new preset name", "Preset name:", QLineEdit.Normal, "") if not ok_pressed or preset_name == "": return if preset_name[-7:] != ".preset": preset_name = preset_name + ".preset" self.save_settings_file(self.main_gui_path + os.path.sep + preset_name) self.preset_update_list() def preset_load(self): selected_preset = self.presetListComboBox.currentText() self.load_settings_file(self.main_gui_path + os.path.sep + selected_preset) def preset_save(self): selected_preset = self.presetListComboBox.currentText() self.save_settings_file(self.main_gui_path + os.path.sep + selected_preset) def preset_delete(self): selected_preset = self.presetListComboBox.currentIndex() selected_preset_text = self.presetListComboBox.currentText() self.presetListComboBox.removeItem(selected_preset) if os.path.isfile(self.main_gui_path + os.path.sep + selected_preset_text): print("DELETE", self.main_gui_path + os.path.sep + selected_preset_text) os.remove(self.main_gui_path + os.path.sep + selected_preset_text) def closeEvent(self, a0: QCloseEvent) -> None: if self.saveGUIstateCheck.isChecked(): self.save_settings_file(self.MAIN_PRESET_FILE) def excepthook(exc_type, exc_value, exc_tb): tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb)) print("error catched!:") print("error message:\n", tb) QtWidgets.QApplication.quit() # or QtWidgets.QApplication.exit(0) def main(): app = QApplication(sys.argv) if 'Fusion' in QStyleFactory.keys(): app.setStyle('Fusion') base_intensity = 50 pal = QPalette() pal.setColor(QPalette.Background, QColor(base_intensity, base_intensity, base_intensity)) pal.setColor(QPalette.Window, QColor(base_intensity, base_intensity, base_intensity)) pal.setColor(QPalette.WindowText, QColor(255 - base_intensity, 255 - base_intensity, 255 - base_intensity)) pal.setColor(QPalette.Base, QColor(base_intensity + 10, base_intensity + 10, base_intensity + 10)) pal.setColor(QPalette.AlternateBase, QColor(base_intensity, base_intensity, base_intensity)) pal.setColor(QPalette.ToolTipBase, QColor(base_intensity, base_intensity, base_intensity)) pal.setColor(QPalette.ToolTipText, QColor(255 - base_intensity, 255 - base_intensity, 255 - base_intensity)) pal.setColor(QPalette.Text, QColor(255 - base_intensity, 255 - base_intensity, 255 - base_intensity)) pal.setColor(QPalette.Button, QColor(base_intensity + 10, base_intensity + 10, base_intensity + 10)) pal.setColor(QPalette.ButtonText, QColor(255 - base_intensity, 255 - base_intensity, 255 - base_intensity)) pal.setColor(QPalette.BrightText, QColor(255, 0, 0)) pal.setColor(QPalette.Highlight, QColor(125, 125, 200)) pal.setColor(QPalette.HighlightedText, QColor(255 - base_intensity, 255 - base_intensity, 255 - base_intensity)) pal.setColor(QPalette.Dark, QColor(base_intensity, base_intensity, base_intensity)) pal.setColor(QPalette.Light, QColor(255 - base_intensity, 255 - base_intensity, 255 - base_intensity)) app.setPalette(pal) sys.excepthook = excepthook window = RIFEGUIMAINWINDOW() window.show() ret = app.exec_() print("event loop exited") sys.exit(ret) if __name__ == '__main__': main()
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,989
HeylonNHP/RIFE-Colab
refs/heads/main
/Globals/BuildConfig.py
class BuildConfig: def isPyInstallerBuild(self): # If compiling rife-colab-gui into a pyinstaller build, set this to True, then run install_dependencies.py return False
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,990
HeylonNHP/RIFE-Colab
refs/heads/main
/QueuedFrames/queuedFrame.py
class QueuedFrame: beginFrame:str = None endFrame:str = None middleFrame:str = None scenechangeSensitivity = None def __init__(self, beginFrame, endFrame, middleFrame, scenechangeSensitivity): self.beginFrame = beginFrame self.endFrame = endFrame self.middleFrame = middleFrame self.scenechangeSensitivity = scenechangeSensitivity
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,991
HeylonNHP/RIFE-Colab
refs/heads/main
/FFmpegFunctions.py
import re import subprocess from Globals.GlobalValues import GlobalValues ffmpegLocation = GlobalValues().getFFmpegPath() ffprobeLocation = GlobalValues().getFFmpegPath(ffprobe=True) def set_ffmpeg_location(location): global ffmpegLocation ffmpegLocation = location def get_frame_count(input_path, mpdecimate, mpdecimate_sensitivity="64*12,64*8,0.33"): """ Gets the frame count of the video """ hi, lo, frac = mpdecimate_sensitivity.split(",") mpdecimate = "mpdecimate=hi={}:lo={}:frac={}".format(hi, lo, frac) if mpdecimate: # ffmpeg -i input.mkv -map 0:v:0 -c copy -f null - command_line = [ffmpegLocation, '-i', input_path, '-vf', mpdecimate, '-map', '0:v:0', '-c', 'rawvideo', '-f', 'null', '-'] else: command_line = [ffmpegLocation, '-i', input_path, '-map', '0:v:0', '-c', 'rawvideo', '-f', 'null', '-'] result = subprocess.run(command_line, stderr=subprocess.PIPE) lines = result.stderr.splitlines() decoded_lines = [] for line in lines: try: decoded_line = line.decode('UTF-8') except: continue decoded_lines.append(decoded_line) for i in range(len(decoded_lines) - 1, 0, -1): decoded_line = decoded_lines[i] if 'frame=' in decoded_line: print('Fetched frame count:', decoded_line) x = re.search(r"frame=[ ]*([0-9]+)", decoded_line) frame_count = int(x.group(1)) return frame_count def get_fps(input_path): """ Gets the FPS as a float from a given video path """ result = subprocess.run([ffmpegLocation, '-i', input_path], stderr=subprocess.PIPE) lines = result.stderr.splitlines() for line in lines: try: decoded_line = line.decode('UTF-8') except: continue if 'Stream #0:' in decoded_line: x = re.search(r"([0-9]+\.*[0-9]*) fps,", decoded_line) try: video_fps = float(x.group(1)) print('Fetched FPS:', video_fps) return video_fps except: continue return None def get_fps_accurate(input_path): """ Gets the FPS as a float from a given video path - Acquires fractional framerate for accuracy """ result = subprocess.run( [ffprobeLocation, '-v', '0', '-of', 'csv=p=0', '-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate', input_path], stdout=subprocess.PIPE) lines = result.stdout.splitlines() decoded_line = lines[0].decode('UTF-8') num, den = decoded_line.split("/") print('Fetched accurate FPS:', "{}/{}".format(num,den)) return float(num) / float(den) def get_length(input_path): """ Get the duration of a video in seconds as a float """ length_seconds = 0.0 result = subprocess.run([ffmpegLocation, '-i', input_path], stderr=subprocess.PIPE) lines = result.stderr.splitlines() for line in lines: try: decoded_line = line.decode('UTF-8') except: continue if 'Duration:' in decoded_line: x = re.search(r"Duration: ([0-9]+:[0-9]+:[0-9]+\.*[0-9]*)", decoded_line) time_string = x.group(1) time_string_list = time_string.split(':') length_seconds += float(time_string_list[0]) * 3600 length_seconds += float(time_string_list[1]) * 60 length_seconds += float(time_string_list[2]) print('Fetched video length (secs):', length_seconds) return length_seconds
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,992
HeylonNHP/RIFE-Colab
refs/heads/main
/runInterpolationAllSteps.py
from str2bool import * import argparse import os import sys import addInstalldirToPath from Globals.EncoderConfig import EncoderConfig # Why should we need to add the submodule to the path, just for the RIFE import to work # Thanks for being consistently terrible, python sys.path.insert(0, os.getcwd() + os.path.sep + 'arXiv2020RIFE') print(sys.path) parser = argparse.ArgumentParser(description='Interpolation for video input') parser.add_argument('-i', dest='inputFile', type=str, default=None) parser.add_argument('-if', dest='interpolationFactor', type=int, default=2) parser.add_argument('-targetfpsmode', dest='mode3targetfpsenabled', type=str2bool, default=False) parser.add_argument('-targetfps', dest='mode3targetfps', type=float, default=60) parser.add_argument('-maxBatchBackupThreadRestarts', dest='maxBatchBackupThreadRestarts', type=int) parser.add_argument('-exitOnMaxBatchBackupThreadRestarts', dest='exitOnMaxBatchBackupThreadRestarts', type=str2bool, default=False) parser.add_argument('-loop', dest='loopable', type=str2bool, default=False) parser.add_argument('-mode', dest='mode', type=int, default=3) parser.add_argument('-crf', dest='crfout', type=int, default=20) parser.add_argument('-clearpngs', dest='clearpngs', type=str2bool, default=True) parser.add_argument('-nonlocalpngs', dest='nonlocalpngs', type=str2bool, default=True) parser.add_argument('-scenesens', dest='scenechangeSensitivity', type=float, default=0.2) parser.add_argument('-mpdecimate', dest='mpdecimateSensitivity', type=str, default="64*12,64*8,0.33") parser.add_argument('-usenvenc', dest='useNvenc', type=str2bool, default=False) parser.add_argument('-gpuids', dest='gpuid', type=str, default="0") parser.add_argument('-batch', dest='batchSize', type=int, default=1) parser.add_argument('-autoencode', dest='autoencode', type=str2bool, default=False) parser.add_argument('-blocksize', dest='blocksize', type=int, default=3000) args = parser.parse_args() from generalInterpolationProceedures import * # setupRIFE(os.getcwd(),args.gpuid) selectedGPUs = str(args.gpuid).split(",") selectedGPUs = [int(i) for i in selectedGPUs] setGPUinterpolationOptions(args.batchSize, selectedGPUs) encoderConfig = EncoderConfig() encoderConfig.set_encoding_crf(float(args.crfout)) if bool(args.useNvenc): encoderConfig.enable_nvenc(True) encoderConfig.set_encoding_preset('slow') encoderConfig.set_nvenc_gpu_id(selectedGPUs[0]) interpolatorConfig = InterpolatorConfig() interpolatorConfig.setMode(args.mode) interpolatorConfig.setClearPngs(args.clearpngs) interpolatorConfig.setLoopable(args.loopable) if args.mode == 3 and args.mode3targetfpsenabled == True: interpolatorConfig.setMode3TargetFPS(True, args.mode3targetfps) else: interpolatorConfig.setInterpolationFactor(args.interpolationFactor) if (args.maxBatchBackupThreadRestarts is not None): interpolatorConfig.setBackupThreadStartLimit(args.maxBatchBackupThreadRestarts) interpolatorConfig.setExitOnBackupThreadLimit(args.exitOnMaxBatchBackupThreadRestarts) interpolatorConfig.setMpdecimateSensitivity(args.mpdecimateSensitivity) interpolatorConfig.setNonlocalPngs(args.nonlocalpngs) interpolatorConfig.setScenechangeSensitivity(args.scenechangeSensitivity) performAllSteps(args.inputFile, interpolatorConfig, encoderConfig, args.autoencode, args.blocksize)
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,993
HeylonNHP/RIFE-Colab
refs/heads/main
/rifeInterpolationFunctions.py
import os import threading import numpy as np # os.chdir('arXiv2020-RIFE/') import torch # from arXiv2020RIFE.model.RIFE_HDv2 import Model from arXiv2020RIFE.train_log.RIFE_HDv3 import Model from torch.nn import functional as F from QueuedFrames.FrameFile import FrameFile useHalfPrecision: bool = False setupRifeThreadLock = threading.Lock() def setup_rife(install_path, gpu_id): global useHalfPrecision with setupRifeThreadLock: try: # TODO: Potentially use model.Device instead? (Line 41) torch.cuda.set_device(gpu_id) except: print("Could net set CUDA device. Attempted CUDA device:", gpu_id) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if torch.cuda.is_available(): torch.set_grad_enabled(False) torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True if useHalfPrecision: torch.set_default_tensor_type(torch.HalfTensor) else: torch.set_default_tensor_type(torch.FloatTensor) else: print("WARNING: CUDA is not available, RIFE is running on CPU! [ff:nocuda-cpu]") model = Model() model.load_model(install_path + os.path.sep + 'arXiv2020RIFE' + os.path.sep + 'train_log', -1) model.eval() model.device() return device, model def rife_interpolate(device, model, img0frame: FrameFile, img1frame: FrameFile, output_frame: FrameFile, scenechange_sensitivity=0.2, scale=0.5): global useHalfPrecision img0 = img0frame.getImageData() img1 = img1frame.getImageData() h, w, _ = img0.shape img_list = [img0, img1] imgs = torch.from_numpy(np.transpose(img_list, (0, 3, 1, 2))).to(device, non_blocking=True).float() / 255. img0 = imgs[:-1] img1 = imgs[1:] tmp = max(32, int(32 / scale)) ph = ((h - 1) // tmp + 1) * tmp pw = ((w - 1) // tmp + 1) * tmp padding = (0, pw - w, 0, ph - h) p = (F.interpolate(img0, (16, 16), mode='bilinear', align_corners=False) - F.interpolate(img1, (16, 16), mode='bilinear', align_corners=False)).abs().mean() if useHalfPrecision: img0 = F.pad(img0, padding).half() img1 = F.pad(img1, padding).half() else: img0 = F.pad(img0, padding) img1 = F.pad(img1, padding) if p > scenechange_sensitivity: mid = img0 else: mid = model.inference(img0, img1, scale) item = (mid[:, :, :h, :w] * 255.).byte().cpu().detach().numpy().transpose(0, 2, 3, 1)[0] output_frame.setImageData(item) return output_frame def set_use_half_precision(enable: bool): global useHalfPrecision useHalfPrecision = enable
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,994
HeylonNHP/RIFE-Colab
refs/heads/main
/Globals/MachinePowerStatesHandler.py
import os import runAndPrintOutput class MachinePowerStatesHandler: def shutdownComputer(self): if os.name == 'nt': runAndPrintOutput.run_and_print_output(['shutdown', '/s', '/t', '1']) else: # Ubuntu runAndPrintOutput.run_and_print_output(['systemctl', 'poweroff']) def suspendComputer(self): if os.name == 'nt': runAndPrintOutput.run_and_print_output(['rundll32', 'Powrprof.dll,SetSuspendState', 'Sleep']) else: # Ubuntu runAndPrintOutput.run_and_print_output(['systemctl', 'suspend'])
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,995
HeylonNHP/RIFE-Colab
refs/heads/main
/pyqtHeaders/FileEdit.py
# !/usr/bin/env python # -*- coding:utf-8 -*- # Sourced from: https://www.reddit.com/r/learnpython/comments/97z5dq/pyqt5_drag_and_drop_file_option/ from PyQt5.QtWidgets import QMessageBox, QLineEdit from PyQt5.QtGui import QIcon import sys import os class FileEdit(QLineEdit): acceptedFiles = [".mp4",".webm",".mkv"] def __init__(self, parent): super(FileEdit, self).__init__(parent) self.setDragEnabled(True) def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': event.acceptProposedAction() def dragMoveEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == 'file': filepath = str(urls[0].path())[1:] # any file type here self.setText(filepath)
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,996
HeylonNHP/RIFE-Colab
refs/heads/main
/runInterpolationBatch.py
from str2bool import * import argparse import os import traceback import sys import addInstalldirToPath # Why should we need to add the submodule to the path, just for the RIFE import to work # Thanks for being consistently terrible, python sys.path.insert(0, os.getcwd() + os.path.sep + 'arXiv2020RIFE') from generalInterpolationProceedures import * parser = argparse.ArgumentParser(description='Interpolation for video input') parser.add_argument('-i', dest='inputDirectory', type=str, default=None) parser.add_argument('-mode', dest='mode', type=int, default=3) parser.add_argument('-fpstarget', dest='fpsTarget', type=float, default=59) parser.add_argument('-crf', dest='crf', type=float, default=20) parser.add_argument('-clearpngs', dest='clearpngs', type=str2bool, default=True) parser.add_argument('-nonlocalpngs', dest='nonlocalpngs', type=str2bool, default=True) parser.add_argument('-scenesens', dest='scenechangeSensitivity', type=float, default=0.2) parser.add_argument('-mpdecimate', dest='mpdecimateSensitivity', type=str, default="64*12,64*8,0.33") parser.add_argument('-usenvenc', dest='useNvenc', type=str2bool, default=False) parser.add_argument('-gpuids', dest='gpuid', type=str, default="0") parser.add_argument('-batch', dest='batchSize', type=int, default=1) parser.add_argument('-autoencode', dest='autoencode', type=str2bool, default=False) parser.add_argument('-blocksize', dest='blocksize', type=int, default=3000) args = parser.parse_args() print("NONLOCALPNGS", args.nonlocalpngs, "CLEARPNGS", args.clearpngs) selectedGPUs = str(args.gpuid).split(",") selectedGPUs = [int(i) for i in selectedGPUs] setGPUinterpolationOptions(args.batchSize, selectedGPUs) encoderConfig = EncoderConfig() encoderConfig.set_encoding_crf(float(args.crf)) if bool(args.useNvenc): encoderConfig.enable_nvenc(True) encoderConfig.set_encoding_preset('slow') encoderConfig.set_nvenc_gpu_id(selectedGPUs[0]) interpolatorConfig = InterpolatorConfig() interpolatorConfig.setMode(args.mode) interpolatorConfig.setClearPngs(args.clearpngs) encoderConfig.set_looping_options(10, 15, True) interpolatorConfig.setMpdecimateSensitivity(args.mpdecimateSensitivity) interpolatorConfig.setNonlocalPngs(args.nonlocalpngs) interpolatorConfig.setScenechangeSensitivity(args.scenechangeSensitivity) interpolatorConfig.setMode3TargetFPS(True, 60) interpolatorConfig.setBackupThreadStartLimit(10) # Batch interpolation code batchInterpolateFolder(args.inputDirectory, interpolatorConfig, args.fpsTarget, encoderConfig, args.autoencode, args.blocksize)
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,997
HeylonNHP/RIFE-Colab
refs/heads/main
/autoEncoding.py
import math from frameChooser import choose_frames_list from runAndPrintOutput import * import os import time import threading from Globals.GlobalValues import GlobalValues from Globals.EncoderConfig import EncoderConfig ffmpegPath = GlobalValues().getFFmpegPath() from FFmpegFunctions import * def mode1AutoEncoding_Thread(threadStart: list, projectFolder, inputFile, outputFile, interpolationDone, outputFPS, currentSavingPNGRanges, encoderConfig: EncoderConfig, blockSize=1000): """ :param encoderConfig: :param currentSavingPNGRanges: :param projectFolder: Interpolation project folder :param interpolationDone: First index is interpolation state, second index is output fps :param blockSize: Size of chunk to autoencode :return: """ print("PROJECT FOLDER", projectFolder) interpolatedFramesFolder = projectFolder + os.path.sep + 'interpolated_frames' blockFramesFilePath = projectFolder + os.path.sep + 'blockFrames.txt' blockCount = 1 blockDurationsList = [] while True: threadStart[0] = True if not os.path.exists(interpolatedFramesFolder): time.sleep(1) continue interpolatedFrames = os.listdir(interpolatedFramesFolder) if len(interpolatedFrames) < blockSize: if interpolationDone[0] == False: time.sleep(1) continue else: blockSize = len(interpolatedFrames) if len(interpolatedFrames) == 0: break interpolatedFrames.sort() filesInBlock = [] for i in range(0, blockSize): filesInBlock.append(interpolatedFrames[i]) # If the save thread hasn't finished saving PNGs into this block range - Wait if confirmCurrentSavingPNGRangesNotInAutoBlockRange(filesInBlock, currentSavingPNGRanges) == False: time.sleep(1) continue # Get duration of current block to maintain timing blockDuration = ((1.0 / outputFPS) * len(filesInBlock)) blockDurationsList.append(blockDuration) blockFramesFile = open(blockFramesFilePath, 'w') framesFileString = "" for file in filesInBlock: line = "file '" + interpolatedFramesFolder + os.path.sep + file + "'\n" framesFileString += line blockFramesFile.write(framesFileString) blockFramesFile.close() encodingPreset = generateEncodingPreset(encoderConfig) ffmpegCommand = [ffmpegPath, '-y', '-loglevel', 'quiet', '-vsync', '1', '-r', str(outputFPS), '-f', 'concat', '-safe', '0', '-i', blockFramesFilePath] ffmpegCommand = ffmpegCommand + encodingPreset ffmpegCommand = ffmpegCommand + [projectFolder + os.path.sep + 'autoblock' + str(blockCount) + '.mkv'] p1 = run(ffmpegCommand) # p1.wait() blockCount += 1 # Remove auto-encoded frames for file in filesInBlock: os.remove(interpolatedFramesFolder + os.path.sep + file) os.remove(blockFramesFilePath) # Interpolation finished, combine blocks concatFileLines = "" for i in range(1, blockCount): line = "file '" + projectFolder + os.path.sep + 'autoblock' + str(i) + '.mkv' + "'\n" line += 'duration ' + str(blockDurationsList[i - 1]) + '\n' concatFileLines += line concatFilePath = 'autoConcat.txt' concatFile = open(concatFilePath, 'w') concatFile.write(concatFileLines) concatFile.close() executeConcatAndGenerateOutput(concatFilePath, inputFile, outputFile, encoderConfig) if not confirmSuccessfulOutput(outputFile): print("Something went wrong generating concatenated output - Not Deleting temp files") return for i in range(1, blockCount): os.remove(projectFolder + os.path.sep + 'autoblock' + str(i) + '.mkv') os.remove(concatFilePath) def mode34AutoEncoding_Thread(threadStart: list, projectFolder, inputFile, outputFile, interpolationDone, outputFPS, currentSavingPNGRanges, encoderConfig: EncoderConfig, blockSize=3000): print("PROJECT FOLDER", projectFolder) interpolatedFramesFolder = projectFolder + os.path.sep + 'interpolated_frames' blockCount = 1 blockDurations = [] currentTime = 0 currentCount = 0 lastFrameFile = None totalLength = 0 while True: threadStart[0] = True if not os.path.exists(interpolatedFramesFolder): time.sleep(1) continue interpolatedFrames = os.listdir(interpolatedFramesFolder) if len(interpolatedFrames) < blockSize: if interpolationDone[0] == False: time.sleep(1) continue else: blockSize = len(interpolatedFrames) if len(interpolatedFrames) == 0: break interpolatedFrames.sort() '''Last frame from last block is kept for use by chooseFramesList If the only frame left is the frame kept from the last block Then we are finished encoding autoencode blocks''' if interpolatedFrames[0] == lastFrameFile and len(interpolatedFrames) == 1: break # Make list of frames in current block filesInBlock = [] for i in range(0, blockSize): filesInBlock.append(interpolatedFrames[i]) # If the save thread hasn't finished saving PNGs into this block range - Wait if confirmCurrentSavingPNGRangesNotInAutoBlockRange(filesInBlock, currentSavingPNGRanges) == False: time.sleep(1) continue # Get the length in ms of the current block, including the next block start time to get the length of the last frame in the current block # Used to keep duration of each block to use for maintaining correct timing when concatenating all blocks nextBlockStartTime = None try: nextBlockStartTime = int(interpolatedFrames[blockSize][:-4]) except: # If frame from next block doesn't exist (I.E. this is the last block) generate time from last frame pair in current block nextBlockStartTime = int(interpolatedFrames[blockSize - 1][:-4]) + ( int(interpolatedFrames[blockSize - 1][:-4]) - int(interpolatedFrames[blockSize - 2][:-4])) currentLength = nextBlockStartTime - int(filesInBlock[1][:-4]) totalLength += currentLength print('Auto encode block', blockCount, len(filesInBlock), str((nextBlockStartTime - int(filesInBlock[1][:-4])) / (GlobalValues.timebase / 1000)) + 'ms', "Before", filesInBlock[0], "Start", filesInBlock[1], 'End', filesInBlock[-1]) # Chose frames for use in output (Downsampling to target FPS) chosenFrames, blockDuration, currentTime, currentCount = choose_frames_list(filesInBlock, outputFPS, currentTime, currentCount) # blockDurations.append(blockDuration) blockDurations.append(currentLength) # Save concat file containing all the chosen frames framesFileString = "" for file in chosenFrames: line = "file '" + interpolatedFramesFolder + os.path.sep + file + "'\n" framesFileString += line blockFramesFilePath = projectFolder + os.path.sep + 'blockFrames{}.txt'.format(blockCount) blockFramesFile = open(blockFramesFilePath, 'w') blockFramesFile.write(framesFileString) blockFramesFile.close() # Build ffmpeg command and run ffmpeg encodingPreset = generateEncodingPreset(encoderConfig) ffmpegCommand = [ffmpegPath, '-y', '-loglevel', 'quiet', '-vsync', '1', '-r', str(outputFPS), '-f', 'concat', '-safe', '0', '-i', blockFramesFilePath] ffmpegCommand = ffmpegCommand + encodingPreset ffmpegCommand = ffmpegCommand + [projectFolder + os.path.sep + 'autoblock' + str(blockCount) + '.mkv'] p1 = run(ffmpegCommand) blockCount += 1 # Remove auto-encoded frames in current block lastFrameFile = filesInBlock[-1] for file in filesInBlock: # Don't delete last frame file in block, as it is used by chooseFramesList in next block if file == lastFrameFile: print("KEEP THIS FRAME", file) continue deleteFile = interpolatedFramesFolder + os.path.sep + file os.remove(deleteFile) os.remove(blockFramesFilePath) # Interpolation finished, combine blocks concatFileLines = "" for i in range(1, blockCount): line = "file '" + projectFolder + os.path.sep + 'autoblock' + str(i) + '.mkv' + "'\n" line += 'duration ' + str((blockDurations[i - 1]) / float(GlobalValues.timebase)) + '\n' concatFileLines += line concatFilePath = projectFolder + os.path.sep + 'autoConcat.txt' concatFile = open(concatFilePath, 'w') concatFile.write(concatFileLines) concatFile.close() executeConcatAndGenerateOutput(concatFilePath, inputFile, outputFile, encoderConfig) totalDuration = 0 for duration in blockDurations: totalDuration += duration # print(str(totalDuration)) # print('Test length',totalLength) if not confirmSuccessfulOutput(outputFile): print("Something went wrong generating concatenated output - Not Deleting temp files") return # Remove blocks and concat file - Output is already created, don't need these anymore for i in range(1, blockCount): os.remove(projectFolder + os.path.sep + 'autoblock' + str(i) + '.mkv') os.remove(concatFilePath) def executeConcatAndGenerateOutput(concatFilePath: str, inputFile: str, outputFile: str, encoderConfig: EncoderConfig): loopEnabled = encoderConfig.get_looping_options()[2] preferredLoopLength = encoderConfig.get_looping_options()[0] maxLoopLength = encoderConfig.get_looping_options()[1] if loopEnabled: inputLength = get_length(inputFile) # Looping enabled if (maxLoopLength / float(inputLength) > 2): # Looping the video won't extend it beyond maxLoopLength loopCount = math.ceil(preferredLoopLength / float(inputLength)) - 1 # Generate looped audio if os.path.exists('loop.flac'): os.remove('loop.flac') command = [ffmpegPath, '-y', '-stream_loop', str(loopCount), '-i', str(inputFile), '-vn', 'loop.flac'] run_and_print_output(command) audioInput = [] if os.path.exists('loop.flac'): audioInput = ['-i', 'loop.flac', '-map', '0', '-map', '1'] command = [ffmpegPath, '-y', '-f', 'concat', '-safe', '0', '-stream_loop', str(loopCount), '-i', concatFilePath] command = command + audioInput + ['-c:v', 'copy', outputFile] p2 = run(command) return p2 = run( [ffmpegPath, '-y', '-f', 'concat', '-safe', '0', '-i', concatFilePath, '-i', inputFile, '-map', '0', '-map', '1:a?', '-c:v', 'copy', outputFile]) def generateEncodingPreset(encoderConfig: EncoderConfig): encodingPreset = [] if encoderConfig.nvenc_enabled(): encodingPreset = ['-pix_fmt', encoderConfig.get_pixel_format(), '-c:v', encoderConfig.get_encoder(), '-gpu', str(encoderConfig.get_nvenc_gpu_id()), '-preset', encoderConfig.get_encoding_preset(), '-profile', encoderConfig.get_encoding_profile(), '-rc', 'vbr', '-b:v', '0', '-cq', str(encoderConfig.get_encoding_crf())] else: encodingPreset = ['-pix_fmt', encoderConfig.get_pixel_format(), '-c:v', encoderConfig.get_encoder(), '-preset', encoderConfig.get_encoding_preset(), '-crf', '{}'.format(encoderConfig.get_encoding_crf())] if encoderConfig.ffmpeg_output_fps_enabled(): encodingPreset = encodingPreset + ['-r', str(encoderConfig.ffmpeg_output_fps_value())] return encodingPreset def confirmSuccessfulOutput(outputFile): # Check exists if not os.path.exists(outputFile): return False if os.path.getsize(outputFile) == 0: return False return True def confirmCurrentSavingPNGRangesNotInAutoBlockRange(filesInBlock: list, currentSavingPNGRanges: list): """ Ensure we're not trying to generate a new autoblock from PNG files that are still in the process of being saved """ maxTimecodeInBlock = int(max(filesInBlock)[:-4]) for frameRange in currentSavingPNGRanges: start: str = frameRange[0] end: str = frameRange[1] # Strip out path start = start[start.rindex('/') + 1:-4] end = end[end.rindex('/') + 1:-4] startInt: int = int(start) endInt: int = int(end) if startInt <= maxTimecodeInBlock or endInt <= maxTimecodeInBlock: '''If there are frames still being saved within the current block Return false''' print("Waiting on save thread before processing autoblock...") return False else: return True
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,998
HeylonNHP/RIFE-Colab
refs/heads/main
/QueuedFrames/queuedFrameList.py
from QueuedFrames.InterpolationProgress import InterpolationProgress class QueuedFrameList: frameList:list = None startFrame:str = None startFrameDest:str = None endFrame:str = None endFrameDest:str = None interpolationProgress:InterpolationProgress = None def __init__(self, frameList, startFrame,startFrameDest, endFrame,endFrameDest): self.frameList = frameList self.startFrame = startFrame self.startFrameDest = startFrameDest self.endFrame = endFrame self.endFrameDest = endFrameDest
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}
50,999
HeylonNHP/RIFE-Colab
refs/heads/main
/addInstalldirToPath.py
import os import sys path = os.path.realpath(__file__) path = path[:path.rindex(os.path.sep)] print(path) sys.path.insert(0, path)
{"/install_dependencies.py": ["/addInstalldirToPath.py", "/Globals/BuildConfig.py"], "/mainGuiUi.py": ["/pyqtHeaders/FileEdit.py"], "/QueuedFrames/SaveFramesList.py": ["/QueuedFrames/FrameFile.py"], "/runInterpolationIndividualSteps.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/generalInterpolationProceedures.py": ["/QueuedFrames/SaveFramesList.py", "/QueuedFrames/queuedFrameList.py", "/QueuedFrames/queuedFrame.py", "/QueuedFrames/FrameFile.py", "/autoEncoding.py", "/runAndPrintOutput.py", "/FFmpegFunctions.py", "/frameChooser.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/Globals/InterpolatorConfig.py", "/rifeFunctions.py", "/rifeInterpolationFunctions.py"], "/main_gui.py": ["/mainGuiUi.py", "/Globals/MachinePowerStatesHandler.py", "/generalInterpolationProceedures.py"], "/FFmpegFunctions.py": ["/Globals/GlobalValues.py"], "/runInterpolationAllSteps.py": ["/addInstalldirToPath.py", "/Globals/EncoderConfig.py", "/generalInterpolationProceedures.py"], "/rifeInterpolationFunctions.py": ["/QueuedFrames/FrameFile.py"], "/Globals/MachinePowerStatesHandler.py": ["/runAndPrintOutput.py"], "/runInterpolationBatch.py": ["/addInstalldirToPath.py", "/generalInterpolationProceedures.py"], "/autoEncoding.py": ["/frameChooser.py", "/runAndPrintOutput.py", "/Globals/GlobalValues.py", "/Globals/EncoderConfig.py", "/FFmpegFunctions.py"], "/QueuedFrames/queuedFrameList.py": ["/QueuedFrames/InterpolationProgress.py"], "/frameChooser.py": ["/Globals/GlobalValues.py"], "/rifeFunctions.py": ["/Globals/BuildConfig.py"]}