def main(): print("Choose the top left and bottom right coordinates of your box.") button_presses = [] # Stream of events with mouse.Events() as events: for event in events: if hasattr(event, "button") and event.pressed: print( "The {0} button was {1} at the following coordinates: x:{2}, y:{3}".format( event.button, "pressed" if event.pressed else "released", event.x, event.y, ) ) button_presses.append(event) if len(button_presses) == 2: break screen_shot = ImageGrab.grab( bbox=( button_presses[0].x, button_presses[0].y, button_presses[1].x, button_presses[1].y, ) ) save_img(screen_shot, "pre") run_sift(screen_shot) save_img(screen_shot, "post")
def ms_track_time(start_time): print(f'*****Mouse Start time***** {start_time}') report_info['Last_Start'] = f'{start_time:%Y.%m.%d %I:%M:%S %p}' mouse_listener = mouse.Listener() mouse_listener.start() mouse_listener.wait() print(f'Listening for mouse {mouse_listener.native_id}') movement = True while movement is True: with mouse.Events() as mouse_events: ms_event = mouse_events.get(timeout=delay) if ms_event is None: print( f'You did not interact with the mouse within {delay} seconds' ) end_time = datetime.datetime.now() print(f'End Time {end_time}') mouse_listener.stop() print(f'Stopped Listening to Mouse {mouse_listener.native_id}') movement = False else: event_time = datetime.datetime.now() # if ms_event: # print(f'Received Mouse event {event_time}') movement = True continue time_elapsed = (end_time - start_time) - datetime.timedelta(seconds=delay) print(f'Time Elapsed {time_elapsed}') # add_time(time_elapsed) return time_elapsed
def track_time(start_time): print(f'*****Start time**** {start_time}') report_info['Last_Start'] = f'{start_time:%Y.%m.%d %I:%M:%S %p}' movement = True while movement is True: with mouse.Events() as mouse_events, keyboard.Events( ) as keyboard_events: ms_event = mouse_events.get(timeout=delay / 2) kb_event = keyboard_events.get(timeout=delay / 2) if (ms_event is None) and (kb_event is None): print(f'You did not interact within {delay} seconds') end_time = datetime.datetime.now() print(f'End Time {end_time}') mouse_listener.stop() print(f'Stopped Listening to Mouse {mouse_listener.native_id}') keyboard_listener.stop() print( f'Stopped Listening to Keyboard {keyboard_listener.native_id}' ) movement = False else: event_time = datetime.datetime.now() if kb_event: print(f'Received Keyboard event {event_time}') if ms_event: print(f'Received Mouse event {event_time}') movement = True continue time_elapsed = (end_time - start_time) - datetime.timedelta(seconds=delay) print(f'Time Elapsed {time_elapsed}') add_time(time_elapsed) return time_elapsed
def start_recording(runningThread): global tic tic = time() try: with mouse.Events() as events: while config.state == config.RECORDING_MOUSE_SEQ: # Block at most 0.01 second event = events.get(timeout=0.01) if event is not None: if type(event) == mouse.Events.Move: on_move(event) elif type(event) == mouse.Events.Click: on_click(event) # remove the click on Stop button from the sequence i = len(config.currentPreset['mouseSeq']['recordedEvents']) - 1 cnt = 0 while i >= 0 and cnt < 2: if (config.currentPreset['mouseSeq']['recordedEvents'][i][0] and config.currentPreset['mouseSeq']['recordedEvents'] [i][1] == mouse.Button.left): cnt += 1 del config.currentPreset['mouseSeq']['recordedEvents'][i] del config.currentPreset['mouseSeq']['recordedTimes'][i] i -= 1 raise mouse.Listener.StopException() except mouse.Listener.StopException: # we need to raise these exceptions because of a listener.stop() bug with Xorg pass
def get_position_with_click(): with mouse.Events() as events: for event in events: if isinstance( event, mouse.Events.Click) and event.button == mouse.Button.right: x, y = pag.position() if RETINA: x *= 2 y *= 2 return (x, y)
def on_recording_press(key): global mainThread # map key to the next mouse click mainThread.emit('update-gui', "Waiting for mouse input") sleep(0.1) with mouse.Events() as events: while config.state == config.RECORDING_KBM_CONNECTIONS: # Block at most 0.01 second event = events.get(timeout=0.01) if event is not None: if type(event) == mouse.Events.Click: on_click_map_key(event, key) break raise mouse.Listener.StopException()
def set_aimbot(self, stdscr): try: # The event listener will be running in this block with mouse.Events() as events: for event in events: try: if event.button == mouse.Button.right: stdscr.clear() stdscr.addstr(str(self.myObject.rpc.set_aimbot())) stdscr.refresh() except: pass except KeyboardInterrupt: return
def listen_and_count(): args = process_args() timeout = args.timeout silent = args.silent mouse_controller = mouse.Controller() signal.signal(signal.SIGINT, signal_handler) with mouse.Events() as events: while True: event = events.get(timeout) if event is None: invisible_move(mouse_controller) if not silent: print( f'You did not interact with the mouse within {timeout} seconds' )
def listener_mouse(self) -> None: """ listen what you are doing on the mouse :return: """ # listen __mouse event with mouse.Events() as events: for event in events: if not mixer.music.get_busy(): if hasattr(event, 'button'): self.listener_mouse_click() elif hasattr(event, 'dy') and event.dy == -1: self.listener_mouse_scroll() else: original = self.get_axes() self.listener_mouse_movement(original) if self.__can_speak: break
def run(seconds): click.secho("Running..", fg="green") # Opening web camera and loading face classifier face_cascade = cv2.CascadeClassifier( str(BASE_DIR / pl.Path('haarcascade_frontalface_default.xml'))) video_capture = cv2.VideoCapture(0) # Flag to check if screen is bright or not bright = True while True: with mouse.Events() as events: try: # Blocks thread until a mouse event is recieved within (seconds) # else it throws an Exception event = events.get(seconds) # CTRL+C was pressed except KeyboardInterrupt: click.secho("Exiting..", fg="red") video_capture.release() break # No mouse event was detected - proceeds to detect face except Exception as e: if face_detected(face_cascade, video_capture): if not bright: change_brightness(brightness=100) bright = True else: if bright: change_brightness(brightness=0) bright = False # Mouse event was detected - sleeps for (seconds) instead else: if not bright: change_brightness(brightness=100) bright = True time.sleep(seconds)
def main(): while True: time_offset = 30 with mouse.Events() as events: counter = 0 future = time.time() + time_offset # Block at most one second for event in events: if event is pynput.mouse.Events.Click: print('Click!') if time.time() < future: counter += 1 #print('event happened') else: print(counter) send_data_to_server(counter) counter = 0 future = time.time() + time_offset event = events.get(time_offset) if event is None: print('nope')
def main(): """ Manual test is an interactive screen shot tool that will perform SIFT on the image. todo: Add more options for edge detection algorithm and options on where to save image. todo: Add functionality for previewing before saving an image. """ print("Choose the top left and bottom right coordinates of your box.") button_presses = [] # Stream of events with mouse.Events() as events: for event in events: if hasattr(event, "button") and event.pressed: print( "The {0} button was {1} at the following coordinates: x:{2}, y:{3}" .format( event.button, "pressed" if event.pressed else "released", event.x, event.y, )) button_presses.append(event) if len(button_presses) == 2: break screen_shot = ImageGrab.grab(bbox=( button_presses[0].x, button_presses[0].y, button_presses[1].x, button_presses[1].y, )) save_img(screen_shot, "pre") run_sift(screen_shot) save_img(screen_shot, "post")
import time import pylint import pyautogui from pynput import mouse print('Enter your message:') blaster = input() with mouse.Events() as events: for event in events: print('Click your target') try: if event.button == mouse.Button.left: while 1: ''' Loop is broken by default with pyautogui\'s escape, putting the mouse in the top left corner''' pyautogui.press('enter') pyautogui.write(blaster) time.sleep(.01) elif event.button == mouse.Button.right: '''listener can be broken by right clicking''' break else: print(type(event)) except: print(type(event))
def record(self, function_name: str): filename = os.path.join(self.data_path, function_name) if os.path.isfile(filename): raise FileExistsError( 'Function "{}" already exists'.format(function_name)) input_hotkey_str = '<ESC>+I' output_hotkey_str = '<ESC>+O' print('Starting recording ...') print('Press {} to put clipboard content into output variable'.format( output_hotkey_str)) print('Press {} to put input variable into clipboard'.format( input_hotkey_str)) print('Press <ESC> to stop') myevents: List[MyInputEvent] = [] input_variables: List[str] = [] output_variables: List[str] = [] stop_event = threading.Event() input_event = threading.Event() output_event = threading.Event() time_delta: float = 0 def on_input(): input_event.set() stop_event.set() def on_output(): output_event.set() stop_event.set() input_hotkey = keyboard.HotKey(keyboard.HotKey.parse(input_hotkey_str), on_input) output_hotkey = keyboard.HotKey( keyboard.HotKey.parse(output_hotkey_str), on_output) def on_press(key): input_hotkey.press(listener.canonical(key)) output_hotkey.press(listener.canonical(key)) myevent = MyInputEvent(KeyPressEvent(key), time_delta=time_delta) myevents.append(myevent) def on_release(key): if key == keyboard.Key.esc: stop_event.set() return False input_hotkey.release(listener.canonical(key)) output_hotkey.release(listener.canonical(key)) myevent = MyInputEvent(KeyReleaseEvent(key), time_delta=time_delta) myevents.append(myevent) last_move_myevent = None def on_mouse_event(event): nonlocal last_move_myevent if isinstance(event, mouse.Events.Move): myevent = MyInputEvent(MoveEvent(x=event.x, y=event.y), time_delta=time_delta) if last_move_myevent: if myevent.timestamp - last_move_myevent.timestamp < 0.1: return # no need to keep all move events last_move_myevent = myevent elif isinstance(event, mouse.Events.Click): myevent = MyInputEvent(ClickEvent(x=event.x, y=event.y, button=event.button, pressed=event.pressed), time_delta=time_delta) elif isinstance(event, mouse.Events.Scroll): myevent = MyInputEvent(ScrollEvent(x=event.x, y=event.y, dx=event.dx, dy=event.dy), time_delta=time_delta) else: raise RuntimeError( 'Unrecognized mouse event: {}'.format(event)) myevents.append(myevent) while True: stop_event.clear() listener = keyboard.Listener(on_press=on_press, on_release=on_release) listener.start() with mouse.Events() as events: while True: if stop_event.is_set(): listener.stop() break event = events.get(0.5) if event is None: continue on_mouse_event(event) if input_event.is_set(): input_event.clear() t0 = time.time() name = self.read_variable_name(kind='Input variable name') if not name: continue example_value = self.read_variable_name( kind='Input example value') if example_value: pyperclip.copy(example_value) deadtime = time.time() - t0 time_delta += deadtime if name in input_variables: print('WARNING: input variable "{}" already exists'.format( name)) else: input_variables.append(name) myevent = MyInputEvent(PasteFromVarEvent(name), time_delta=time_delta) myevents.append(myevent) elif output_event.is_set(): output_event.clear() t0 = time.time() name = self.read_variable_name(kind='Output variable name') if not name: continue deadtime = time.time() - t0 time_delta += deadtime if name in output_variables: print( 'WARNING: output variable "{}" already exists'.format( name)) else: output_variables.append(name) myevent = MyInputEvent(CopyToVarEvent(name), time_delta=time_delta) myevents.append(myevent) else: break if myevents: myfunction = MyFunction(events=myevents, input_variables=input_variables, output_variables=output_variables) self.save(myfunction, filename) else: print('WARNING: no input events detected!')
def main(): # Set path where the results are stored results_path = Path('./results/') results_path.mkdir(parents=False, exist_ok=True) # We have 2 conditions (monaural, binaural). In each condition, two different sounds are randomly played conditions = ['mono'] soundtype = ['white', 'rippled'] #comparison = [-2, -1, 1, 2] #location = [3, 4, 5, 10] comparison = [-3, -2, -1, 1, 2, 3] location = [4, 10] n_noise = len(soundtype) n_ref = len(comparison) n_comb = len(location) n_condition = len(conditions) tot_trial = n_comb * n_condition * n_noise * n_ref * 25 lst_spkorder = list(('True', 'False') * (tot_trial // 2)) rd.shuffle(lst_spkorder) trial_list = [] for i in soundtype: for j in location: for k in comparison: trial_list.append(Trial(i, j, k)) trial_list = trial_list * 25 rd.shuffle(trial_list) # Ask for user id print(Fore.GREEN + 'Please enter participant id: ' + Style.RESET_ALL) user_id = input() date = datetime.now() resultsFile = 'userid_' + user_id + '_date_' + date.strftime( '%d.%m.%Y') + '_time_' + date.strftime('%H.%M') + '.csv' resultsStoredIn = results_path / resultsFile with open(resultsStoredIn.as_posix(), mode='w', newline='') as resFile: # Create the file res_file_writer = csv.writer(resFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) # Add headers res_file_writer.writerow([ 'trial', # Trial number 'sound_type', # type of the sound 'location_standard', # speaker number standard stimulus 'location_comparison', # speaker number comparison stimulus 'user_estimate', # which stimulus was perceived as higher (standard or comparison) 'stimulus_order', # which stimulus was played first (standard or comparison) 'reaction_time', # time for participant to respond 'user_id' # id of the user ]) resFile.flush() # Adjust the level of the sound so that the participant does not hear anything with both ears occluded. print(Fore.RED + 'Make sure participant is wearing ear plugs and headphones' + Style.RESET_ALL) input() test_deafness() clear_screen() print(Fore.RED + 'Tell participant to remove headphone from leading ear' + Style.RESET_ALL) input() clear_screen() print(Fore.GREEN + 'All set. Experiments is about to start...' + Style.RESET_ALL) # Initialize AudioPlayer audio_player = AudioPlayer(dummy=dummy_audio_player) # Start the experiment # Play one sound first, then 1s break, then second sound # There is a 2min break every 200 trials clear_screen() print(Back.RED + '###### Experiment is starting NOW ######' + Style.RESET_ALL) print(Back.RED + '########################################' + Style.RESET_ALL) print(Back.RED + '########################################' + Style.RESET_ALL) for i_cond, cond in enumerate(conditions): print(Fore.GREEN + 'The following condition is tested: ' + cond + '\n' + Style.RESET_ALL) for i in range(len(trial_list)): order_random = lst_spkorder[i] print(order_random) if i == 200 or i == 400 or i == 600: print(Fore.RED + 'BREAK' + Style.RESET_ALL) audio_player.set_audio_file(rippled_noise_sound.as_posix()) audio_player.set_output_line(4) audio_player.play() audio_player.play() audio_player.play() audio_player.play() audio_player.play() time.sleep(120) print('2 minute break is over') input() # Decode the stimulus sequence speaker_standard = trial_list[i].location speaker_comparison = trial_list[i].comparison sound_type = trial_list[i].soundtype if sound_type == 'rippled': audio_player.set_audio_file(rippled_noise_sound.as_posix()) else: audio_player.set_audio_file(white_noise_sound.as_posix()) if order_random == 'True': stimulus_order = "Standard first" print(stimulus_order) audio_player.set_output_line(speaker_standard) audio_player.play() time.sleep(1) audio_player.set_output_line(speaker_standard + speaker_comparison) audio_player.play() else: stimulus_order = "Comparison first" print(stimulus_order) audio_player.set_output_line(speaker_standard + speaker_comparison) audio_player.play() audio_player.set_output_line(speaker_standard) time.sleep(1) audio_player.play() # Start measuring the time ts = datetime.now() # Get participant response print('Waiting for participant response...') mouse_input = None with mouse.Events() as events: for event in events: if not type(event) == mouse.Events.Click: continue if event.button == mouse.Button.right: mouse_input = "right" break elif event.button == mouse.Button.left: mouse_input = "left" break else: print('Received event {}'.format(event)) # Calculate reaction time reaction_time = (datetime.now() - ts).total_seconds() # Create data entry and add it to file result_item = [ i, # Trial sound_type, # speaker_standard, # speaker_comparison, # mouse_input, stimulus_order, reaction_time, user_id # ] res_file_writer.writerow(result_item) resFile.flush() # Wait some time until playing the next sound time.sleep(1) print( "First Condition is finished. Let participant remove headset") input() # Adjust the level of the sound so that the participant does not hear anything with both ears occluded. print(Fore.RED + 'Make sure participant is wearing ear plugs and headphones' + Style.RESET_ALL) input() test_deafness() clear_screen() print(Fore.RED + 'Tell participant to remove headphone from leading ear' + Style.RESET_ALL)
import pynput import pyautogui import time from pynput import mouse from pynput import keyboard running = True mouse_event = mouse.Events() def on_press(key): global running if key == keyboard.Key.f1: running = False print('fim') return False def msg(): mouse_event.start() for event in mouse_event: if running: if isinstance(event, mouse.Events.Click): if not event.pressed: pyautogui.typewrite('hello world\n', interval=0.009) else: time.sleep(1) print('teste1') return False