def deleteMacro(tokens): log.info("In deleteMacro. Tokens: " + ' '.join(tokens)) config = settings.loadConfig() if ' '.join(tokens) in config["MACROS"]: del config["MACROS"][' '.join(tokens)] settings.saveConfig(config) #Reload the menu to reload the macros gui.settingsMode(settings.loadConfig()["MACROS"])
def __init__(self): #Create the GUI object and set window properties self.root = Tk() self.root.title("SpeechV") self.recording = False self.namingMacro = False self.inProcessing = True self.processingLock = Lock() self.status = Status.INITIALIZING # #Setup window properties self.root.attributes("-topmost", True) config = settings.loadConfig() s = config["SETTINGS"]["WINDOW_SIZE"] self.setupWindow(True, s) #This has to go after setupWindow so the labels are declared self.setMode(GlobalMode.NAVIGATE) self.root.update() # #Calculate screen size and move the window to the bottom right self.getPositions() self.root.geometry(self.RIGHT + self.BOTTOM) self.right = True
def adjustTimeout(tokens): if len(tokens) != 3 or tokens[1] != "POINT": raise AttributeError("Ill-formed timeout command") try: wholeNum = w2n.word_to_num(tokens[0]) decimal = w2n.word_to_num(tokens[2]) r.pause_threshold = wholeNum+decimal/10 log.info("Changed audio timeout to: " + str(r.pause_threshold)) config = settings.loadConfig() config["SETTINGS"]["TIMEOUT"] = r.pause_threshold settings.saveConfig(config) except: raise AttributeError("Number conversion failed in adjust timeout")
def exeSettings(tokens, mode): if len(tokens) == 0: gui.settingsMode(settings.loadConfig()["MACROS"]) return ([], GlobalMode.SETTINGS) elif tokens[0] == 'CALIBRATE': voice.recalibrate() #Need to fix circular dependency in order to do this elif tokens[0] == 'TIMEOUT': pass voice.adjustTimeout(tokens[1:]) elif len(tokens) > 1 and tokens[0] == 'TIME' and tokens[1] == 'OUT': pass voice.adjustTimeout(tokens[2:]) elif tokens[0] == 'CLOSE': gui.closeSettings() elif tokens[0] == 'RESIZE': gui.resizeWindow(tokens[1:]) else: log.error(log.ParseError.HELP, tokens[0])
def __init__(self): # handle input based on mode self.mode = GlobalMode.NAVIGATE #Stores whether to interpret the next command as a new sentence self.newSentence = True # Load the configuration file into a dictionary try: self.config = settings.loadConfig() except FileNotFoundError as e: log.error(str(e)) # FIXME: handle case where there is no config file log.error("No config file found! Ignoring error for now...") self.config = {} self.config["MACROS"] = {} self.config["SETTINGS"] = {} self.wordForwarder = commands.WordForwarder() self.macroManager = MacroManager(self.config) # all of these functions must return one of the following: # - None (this is returned if there is no explicit 'return') # - A tuple of the form (A, B) where A is a list of tokens that # need to be parsed after command execution and B is the global mode self.commands = { "ALT": commands.exeAlt, "RESIZE": commands.exeResize, "HELP": commands.exeHelp, "SETTINGS": commands.exeSettings, "LAUNCH": commands.exeLaunch, "SWITCH": commands.exeSwitch, "MOVE": commands.exeMove, "RECORD": commands.exeRecord, "TYPE": commands.exeKeystroke, "FOCUS": commands.exeFocus, "MINIMIZE": commands.exeMinimize, "CANCEL": commands.exeCancel, "MAXIMIZE": commands.exeMaximize, "TERMINATE": commands.exeTerminate, "COPY": commands.exeCopy, "PASTE": commands.exePaste, "SLEEP": commands.exeSleep }
def main(): track_playing = None track_next = None # Load config file config = settings.loadConfig('config.json') # Spawn GUI gui = GUI() # Initialize library lib = Library(config['library']['dbfile']) for folder in config['library']['folders']: lib.addFolder(folder) player = Player() track_playing = lib.getRandomFile() track_next = lib.getRandomFile() player.cue(u"file:///"+track_playing) player.play() print track_playing player.cue(u"file:///"+track_next) print track_next #gui.queueTrack(track_playing) while True: pos = player.get_position() dur = player.get_duration() gui.set_status("%s %02d:%02d / %02d:%02d " % (track_playing, pos/60, (pos%60), dur/60, (dur%60))) gui.update() if player.queue is None: track_playing = track_next track_next = lib.getRandomFile() player.cue(u"file:///"+track_next) print player.queue
def resizeWindow(self, tokens): if len(tokens) == 0: return if isinstance(tokens[0], int): size = tokens[0] else: if isinstance(tokens, list): tokens = ' '.join(tokens) size = w2n.word_to_num(tokens.lower()) # self.resizeWindowHelper(size) self.setupWindow(False, size) self.getPositions() if self.right: self.root.geometry(self.RIGHT + self.BOTTOM) else: self.root.geometry(self.RIGHT + self.BOTTOM) self.root.update() config = settings.loadConfig() config["SETTINGS"]["WINDOW_SIZE"] = size settings.saveConfig(config)
def get_image(): directory = os.path.dirname(__file__) USER_NAME = getpass.getuser() osvar = platform.system() if osvar == "Windows": directory = r'C:\Users\%s\AppData\Local\unsplashipy' % USER_NAME else: directory=os.path.dirname(__file__) global filepath filepath = directory + "/" + str(time.time()) + ".jpg" print(f"\r[+] Status: Starting download...", end="") try: screensize = get_screensize() config=settings.loadConfig() urllib.request.urlretrieve("https://source.unsplash.com/random/" + screensize+"/?"+config["collection"], filepath) # TODO choose image type (nature,...) print(f"\r[+] Status: Downloaded image from source.unsplash.com/random/{screensize} to {filepath}", end="") return filepath except: print(f"\r[-] Status: Encountered some problems while downloading the image.", end="") traceback.print_exc() sys.exit(1)
""" Nextcloud Security Checker 2020 maschhoff github.com/maschhoff """ import requests import settings import json import noti config = settings.loadConfig() def check(url): # Request POST https://scan.nextcloud.com/api/queue data_send = {"url": url} se = requests.post('https://scan.nextcloud.com/api/queue', data=json.dumps(data_send), headers={ 'X-CSRF': 'true', 'Content-Type': 'application/json' }) se = se.json() # Request GET https://scan.nextcloud.com/api/result/ UUID res = requests.get('https://scan.nextcloud.com/api/result/' + se["uuid"],
def voiceLoop(): global restartLoop config = settings.loadConfig() AUDIO_TIMEOUT = config["SETTINGS"]["TIMEOUT"] # length of pause marking end of command with open('command_set.txt', 'r') as myfile: str_command_set = myfile.read() command_set = str_command_set.split('\n') in_debug_mode = False if os.path.exists('DEBUG_FLAG'): in_debug_mode = True log.info("debug mode activated") opened = False while not opened: try: pipe = win32file.CreateFile( r'\\.\pipe\named_pipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_WRITE | win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None) opened = True except Exception as e: log.error("HELLO WORLD") log.error(str(e)) log.error(traceback.format_exc()) time.sleep(1) time.sleep(1) else: log.info("voice mode activated") p = parsing.Parser() with mic as source: #Automatically adjust for ambient noise instead of calling calibrate r.dynamic_energy_threshold = True r.pause_threshold = AUDIO_TIMEOUT while True: try: gui.ready() raw_command = '' if in_debug_mode: message = win32file.ReadFile(pipe, 4096) log.debug('pipe message: ', message[1].decode()) raw_command = message[1].decode() else: audio = r.listen(source) # recognize speech using Google Cloud Speech API log.debug("Pre recognize") raw_command = recognize(audio, command_set) gui.processing() cmdPromptHandle = None if in_debug_mode and not os.path.exists('BATCH_FLAG'): keyboard.press_and_release("alt+tab") time.sleep(1) # give OS time to alt-tab if raw_command == -1: raise ValueError("Failed to recognize speech") else: p.parse(raw_command) if os.path.exists('BATCH_FLAG'): # send an ACK to tell them we're ready for more input win32file.WriteFile(pipe, 'ACK'.encode()) elif in_debug_mode: time.sleep(1) # give the user time to see the result commands.exeFocus(['CMD'], GlobalMode.NAVIGATE) gui.updateCommands(raw_command) except Exception as e: log.error(str(e)) log.error(traceback.format_exc()) errorMsg = None try: log.debug('type(raw_command) = {}'.format(type(raw_command))) # this looks incredibly dumb, but there's a reason: we really # just want to check if raw_command is an integer. This could be # refactored but #timepressure if raw_command == -1: errorMsg = '(google api failed!)' else: errorMsg = '(google api failed!)' except ValueError: errorMsg = 'error: ' + str(raw_command) gui.updateCommands(errorMsg) gui.showError("Error parsing\nTry again.") if p.mode == GlobalMode.FOLLOW: continue gui.setMode(p.mode)