How to use set_idle_state method in avocado

Best Python code snippet using avocado_python

pymini.py

Source:pymini.py Github

copy

Full Screen

...242 """ Check queue for any io initiated events. """243 while (not self.guiq.empty()):244 e = self.guiq.get()245 if (e['id'] == GuiEvent.MECH_IDLE):246 self.set_idle_state(e['bstate'])247 elif (e['id'] == GuiEvent.LOG_MSG):248 self.display_logger_message(e)249 elif (e['id'] == GuiEvent.MECH_POSITION):250 self.update_position(e)251 elif (e['id'] == GuiEvent.MECH_ESTOP):252 self.set_estop_state() # auto estop from mech253 elif (e['id'] == GuiEvent.MECH_PAUSED):254 self.set_idle_state(ButtonState.RESUME) # auto pause from parser255 else:256 logging.info("unable to process gui event %d\n" % (e['id']))257 e = None258 #=======================================================================259 def get_ini(self, section, option, default=None):260 try:261 val = self.cfg.get(section, option)262 except:263 val = default264 return val265 #=======================================================================266 def create_widgets(self):267 self.grid()268 grow=0269 self.x_val = tkinter.Label(self, relief=tkinter.GROOVE)270 self.x_val.grid(row=grow, column=0, sticky='ew')271 self.x_val.bind("<Button-1>", lambda event: self.axis_button(AxisSel.X))272 grow += 1273 self.y_val = tkinter.Label(self)274 self.y_val.grid(row=grow, column=0, sticky='ew')275 self.y_val.bind("<Button-1>", lambda event: self.axis_button(AxisSel.Y))276 grow += 1277 self.z_val = tkinter.Label(self)278 self.z_val.grid(row=grow, column=0, sticky='ew')279 self.z_val.bind("<Button-1>", lambda event: self.axis_button(AxisSel.Z))280 grow += 1281 self.a_val = tkinter.Label(self)282 self.a_val.grid(row=grow, column=0, sticky='ew')283 self.a_val.bind("<Button-1>", lambda event: self.axis_button(AxisSel.A))284 grow += 1285 self.estop_button = tkinter.Button(self, text="EStop", command=self.toggle_estop)286 self.estop_button.grid(row=grow, column=3, columnspan=2, sticky='news')287 self.home_button = tkinter.Button(self, text="All Zero", command=self.set_all_zero)288 self.home_button.grid(row=grow, column=0, sticky='news')289 self.jogneg_button = tkinter.Button(self, text="Jog X -", command=lambda: self.jog(JogSel.NEG))290 self.jogneg_button.grid(row=grow, column=1, sticky='news')291 self.jogpos_button = tkinter.Button(self, text="Jog X +", command=lambda: self.jog(JogSel.POS))292 self.jogpos_button.grid(row=grow, column=2, sticky='news')293 self.resume_button = tkinter.Button(self, text="Resume", command=self.resume)294 self.resume_button.grid(row=grow, column=5, sticky='news')295 grow = 1296 self.status_button = tkinter.Label(self, text="status")297 self.status_button.grid(row=grow, column=4, sticky='e')298 self.led_button = tkinter.Label(self, image=self.green_led)299 self.led_button.grid(row=grow, column=5, sticky='w')300 panelrow = 17301 lastrow = panelrow302 self.log_panel = tkinter.Text(self, state=tkinter.DISABLED, width=80, height=Panel.MAX_LINE, wrap=tkinter.NONE,303 bg=self.x_val['bg'], relief=tkinter.SUNKEN, borderwidth=4)304 self.log_panel.grid(row=lastrow, columnspan=6, sticky='news')305 lastrow += 1306 self.status_line_num = tkinter.Label(self)307 self.status_line_num.grid(row=lastrow, column=5, sticky='w')308 # Pipe log messages to Text widget.309 self.create_logger(self.guiq)310 # Load persistent data from .ini for MDI buttons. Note, 'realpath' takes care of any symlink.311 if (os.path.dirname(IniFile.name) == ""):312 IniFile.name = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), IniFile.name)313 self.open(IniFile.name)314 grow = 0315 self.units = self.get_ini("TRAJ", "LINEAR_UNITS", default="inch")316 self.speed_button = tkinter.Label(self, text="Speed (%s/minute)" % (self.units))317 self.speed_button.grid(row=grow, column=1, sticky='e')318 self.speed_val = tkinter.StringVar()319 self.speed_val.set(self.get_ini("DISPLAY", "JOG_SPEED", default="6"))320 self.speed_entry = tkinter.Entry(self, textvariable=self.speed_val) # use max z speed for default321 self.speed_entry.grid(row=grow, column=2, sticky='w')322 grow += 1323 self.inc_button = tkinter.Button(self, text="Incremental Jog (%s)" % (self.units),324 command=lambda: self.jog_type_button(JogTypeSel.INC))325 self.inc_button.grid(row=grow, column=1, sticky='e')326 self.inc_val = tkinter.StringVar()327 self.inc_val.set(self.get_ini("DISPLAY", "INC_JOG", default="0.2"))328 self.inc_entry = tkinter.Entry(self, textvariable=self.inc_val)329 self.inc_entry.grid(row=grow, column=2, sticky='w')330 grow += 1331 self.abs_button = tkinter.Button(self, text="Absolute Jog (%s)" % (self.units),332 command=lambda: self.jog_type_button(JogTypeSel.ABS))333 self.abs_button.grid(row=grow, column=1, sticky='e')334 self.abs_val = tkinter.StringVar()335 self.abs_val.set(self.get_ini("DISPLAY", "ABS_JOG", default="1"))336 self.abs_entry = tkinter.Entry(self, textvariable=self.abs_val, state=tkinter.DISABLED)337 self.abs_entry.grid(row=grow, column=2, sticky='w')338 grow = 5339 self.mdi_button1 = tkinter.Button(self, text=self.get_ini("DISPLAY", "MDI_LABEL_1", default="MDI-1"),340 command=lambda: self.mdi(self.mdi_val1))341 self.mdi_button1.grid(row=grow, column=0, sticky='news')342 self.mdi_val1 = tkinter.StringVar()343 self.mdi_val1.set(self.get_ini("DISPLAY", "MDI_CMD_1", default=""))344 self.mdi_entry1 = tkinter.Entry(self, textvariable=self.mdi_val1)345 self.mdi_entry1.grid(row=grow, column=1, columnspan=5, sticky='ew')346 grow += 1347 self.mdi_button2 = tkinter.Button(self, text=self.get_ini("DISPLAY", "MDI_LABEL_2", default="MDI-2"),348 command=lambda: self.mdi(self.mdi_val2))349 self.mdi_button2.grid(row=grow, column=0, sticky='news')350 self.mdi_val2 = tkinter.StringVar()351 self.mdi_val2.set(self.get_ini("DISPLAY", "MDI_CMD_2", default=""))352 self.mdi_entry2 = tkinter.Entry(self, textvariable=self.mdi_val2)353 self.mdi_entry2.grid(row=grow, column=1, columnspan=5, sticky='ew')354 grow += 1355 self.mdi_button3 = tkinter.Button(self, text=self.get_ini("DISPLAY", "MDI_LABEL_3", default="MDI-3"),356 command=lambda: self.mdi(self.mdi_val3))357 self.mdi_button3.grid(row=grow, column=0, sticky='news')358 self.mdi_val3 = tkinter.StringVar()359 self.mdi_val3.set(self.get_ini("DISPLAY", "MDI_CMD_3", default=""))360 self.mdi_entry3 = tkinter.Entry(self, textvariable=self.mdi_val3)361 self.mdi_entry3.grid(row=grow, column=1, columnspan=5, sticky='ew')362 grow += 1363 self.mdi_button4 = tkinter.Button(self, text=self.get_ini("DISPLAY", "MDI_LABEL_4", default="MDI-4"),364 command=lambda: self.mdi(self.mdi_val4))365 self.mdi_button4.grid(row=grow, column=0, sticky='news')366 self.mdi_val4 = tkinter.StringVar()367 self.mdi_val4.set(self.get_ini("DISPLAY", "MDI_CMD_4", default=""))368 self.mdi_entry4 = tkinter.Entry(self, textvariable=self.mdi_val4)369 self.mdi_entry4.grid(row=grow, column=1, columnspan=5, sticky='ew')370 grow += 1371 self.auto_button = tkinter.Button(self, text="Auto", command=lambda: self.auto(AutoSel.OPEN))372 self.auto_button.grid(row=grow, column=0, sticky='news')373 self.auto_val = tkinter.StringVar()374 self.auto_val.set(self.get_ini("DISPLAY", "AUTO_FILE", default="your_file.nc"))375 self.auto_entry = tkinter.Entry(self, textvariable=self.auto_val)376 self.auto_entry.grid(row=grow, column=1, columnspan=3, sticky='ew')377 self.run_button = tkinter.Button(self, text="Run", command=lambda: self.auto(AutoSel.RUN))378 self.run_button.grid(row=grow, column=4, sticky='news')379 self.verify_button = tkinter.Button(self, text="Verify", command=lambda: self.auto(AutoSel.VERIFY))380 self.verify_button.grid(row=grow, column=5, sticky='news')381 grow += 1382 backrow = grow383 self.backplot_canvas = tkinter.Canvas(self, relief=tkinter.SUNKEN, borderwidth=4)384 self.backplot_canvas.grid(row=grow, column=0, columnspan=6, sticky='news')385 grow += 1386 self.zoom_in_button = tkinter.Button(self, text="Zoom In", command=lambda: self.bp3d.zoom_in())387 self.zoom_in_button.grid(row=grow, column=0, sticky='news')388 self.zoom_out_button = tkinter.Button(self, text="Zoom Out", command=lambda: self.bp3d.zoom_out())389 self.zoom_out_button.grid(row=grow, column=1, sticky='news')390 self.plot_3d_button = tkinter.Button(self, text="3D", command=lambda: self.bp3d.plot_3d())391 self.plot_3d_button.grid(row=grow, column=2, sticky='news')392 self.plot_xy_button = tkinter.Button(self, text="X - Y", command=lambda: self.bp3d.plot_xy())393 self.plot_xy_button.grid(row=grow, column=3, sticky='news')394 self.plot_xz_button = tkinter.Button(self, text="X - Z", command=lambda: self.bp3d.plot_xz())395 self.plot_xz_button.grid(row=grow, column=4, sticky='news')396 self.plot_yz_button = tkinter.Button(self, text="Y - Z", command=lambda: self.bp3d.plot_yz())397 self.plot_yz_button.grid(row=grow, column=5, sticky='news')398 #grow += 1399 self.columnconfigure(1, weight=1)400 self.columnconfigure(2, weight=1)401 self.rowconfigure(backrow, weight=1)402 self.rowconfigure(panelrow, weight=1)403 #=======================================================================404 def axis_button(self, id):405 if (id == AxisSel.X):406 self.x_val.config(relief=tkinter.GROOVE)407 self.y_val.config(relief=tkinter.FLAT)408 self.z_val.config(relief=tkinter.FLAT)409 self.a_val.config(relief=tkinter.FLAT)410 self.jogneg_button.config(text="Jog X -")411 self.jogpos_button.config(text="Jog X +")412 elif (id == AxisSel.Y):413 self.x_val.config(relief=tkinter.FLAT)414 self.y_val.config(relief=tkinter.GROOVE)415 self.z_val.config(relief=tkinter.FLAT)416 self.a_val.config(relief=tkinter.FLAT)417 self.jogneg_button.config(text="Jog Y -")418 self.jogpos_button.config(text="Jog Y +")419 elif (id == AxisSel.Z):420 self.x_val.config(relief=tkinter.FLAT)421 self.y_val.config(relief=tkinter.FLAT)422 self.z_val.config(relief=tkinter.GROOVE)423 self.a_val.config(relief=tkinter.FLAT)424 self.jogneg_button.config(text="Jog Z -")425 self.jogpos_button.config(text="Jog Z +")426 else:427 self.x_val.config(relief=tkinter.FLAT)428 self.y_val.config(relief=tkinter.FLAT)429 self.z_val.config(relief=tkinter.FLAT)430 self.a_val.config(relief=tkinter.GROOVE)431 self.jogneg_button.config(text="Jog A -")432 self.jogpos_button.config(text="Jog A +")433 self.sel_axis = id434 #=======================================================================435 def jog_type_button(self, id):436 if (id == JogTypeSel.INC):437 self.inc_entry.config(state=tkinter.NORMAL)438 self.abs_entry.config(state=tkinter.DISABLED)439 else:440 self.inc_entry.config(state=tkinter.DISABLED)441 self.abs_entry.config(state=tkinter.NORMAL)442 self.sel_jog_type = id443 #=======================================================================444 def update_position(self, e):445 self.cur_pos = e['pos']446 self.x_val.config(text="X %07.3f" % (self.cur_pos['x']))447 self.y_val.config(text="Y %07.3f" % (self.cur_pos['y']))448 self.z_val.config(text="Z %07.3f" % (self.cur_pos['z']))449 self.a_val.config(text="A %07.3f" % (self.cur_pos['a']))450 if (e['line'] > 0):451 # Display gcode lines that have completed plus the next line.452 beg = self.line_num453 end = e['line']454 if (beg > 1):455 beg += 2456 if (end < self.line_max):457 end += 1458 self.line_num = e['line'] # save completed line459 # Display gcode lines in log_panel.460 line_txt = self.display_gcode_lines(self.auto_val.get(), beg, end, self.line_num)461 # Display completed line in backplot.462 self.bp3d.update_plot(line_txt, self.line_num, self.cur_pos)463 # Update status line count.464 self.status_line_num.config(text="%d/%d" % (self.line_num, self.line_max))465 #=======================================================================466 def display_logger_message(self, e):467 numlines = self.log_panel.index('end - 1 line').split('.')[0]468 self.log_panel['state'] = 'normal'469 if (numlines == Panel.MAX_LINE):470 self.log_panel.delete(1.0, 2.0)471 if (self.log_panel.index('end-1c') != '1.0'):472 self.log_panel.insert('end', '\n')473 self.log_panel.see('end')474 self.log_panel.insert('end', e['msg'])475 self.log_panel['state'] = 'disabled'476 #=======================================================================477 def set_idle_state(self, flag):478 if (flag[0]):479 self.estop_button.config(state=tkinter.ACTIVE)480 else:481 self.estop_button.config(state=tkinter.DISABLED)482 if (flag[1]):483 self.home_button.config(state=tkinter.ACTIVE)484 else:485 self.home_button.config(state=tkinter.DISABLED)486 if (flag[2]):487 self.jogneg_button.config(state=tkinter.ACTIVE)488 self.jogpos_button.config(state=tkinter.ACTIVE)489 else:490 self.jogneg_button.config(state=tkinter.DISABLED)491 self.jogpos_button.config(state=tkinter.DISABLED)492 if (flag[3]):493 self.run_button.config(state=tkinter.ACTIVE)494 else:495 self.run_button.config(state=tkinter.DISABLED)496 if (flag[4]):497 self.mdi_button1.config(state=tkinter.ACTIVE)498 self.mdi_button2.config(state=tkinter.ACTIVE)499 self.mdi_button3.config(state=tkinter.ACTIVE)500 self.mdi_button4.config(state=tkinter.ACTIVE)501 else:502 self.mdi_button1.config(state=tkinter.DISABLED)503 self.mdi_button2.config(state=tkinter.DISABLED)504 self.mdi_button3.config(state=tkinter.DISABLED)505 self.mdi_button4.config(state=tkinter.DISABLED)506 if (flag[5] == 1):507 self.resume_button.config(state=tkinter.ACTIVE)508 else:509 self.resume_button.config(state=tkinter.DISABLED)510 if (flag[6] == 1):511 self.verify_button.config(state=tkinter.ACTIVE, text='Verify')512 elif (flag[6] == 2):513 self.verify_button.config(state=tkinter.ACTIVE, text='Cancel')514 else:515 self.verify_button.config(state=tkinter.DISABLED, text='Verify')516 if (self.dog.get_state() & MechStateBit.ESTOP):517 self.led_button.config(image=self.red_led)518 elif ((self.dog.get_state() & MechStateBit.PAUSED) and (not flag[5] == 2)):519 self.led_button.config(image=self.orange_led)520 else:521 self.led_button.config(image=self.green_led)522 if (self.dog.get_state() & MechStateBit.HOMED):523 self.x_val.config(fg="blue")524 self.y_val.config(fg="blue")525 self.z_val.config(fg="blue")526 self.a_val.config(fg="blue")527 else:528 self.x_val.config(fg="red")529 self.y_val.config(fg="red")530 self.z_val.config(fg="red")531 self.a_val.config(fg="red")532 #=======================================================================533 def jog(self, id):534 if (not self.safety_check_ok()):535 return536 self.set_idle_state(ButtonState.BUSY)537 m = {}538 m['id'] = MechEvent.CMD_MDI539 if (id == JogSel.NEG):540 # Jog negative.541 if (self.sel_jog_type == JogTypeSel.INC):542 # perform incremental move543 val = float(self.inc_val.get())544 m['cmd'] = "G1 %s%f F%s" % (545 axis_name[self.sel_axis], self.cur_pos[pos_name[self.sel_axis]] - val, self.speed_val.get())546 else:547 # perform absolute move548 val = float(self.abs_val.get())549 m['cmd'] = "G1 %s%f F%s" % (axis_name[self.sel_axis], val, self.speed_val.get())550 else:551 # Jog positive.552 if (self.sel_jog_type == JogTypeSel.INC):553 # perform incremental move554 val = float(self.inc_val.get())555 m['cmd'] = "G1 %s%f F%s" % (556 axis_name[self.sel_axis], self.cur_pos[pos_name[self.sel_axis]] + val, self.speed_val.get())557 else:558 # perform absolute move559 val = float(self.abs_val.get())560 m['cmd'] = "G1 %s%f F%s" % (axis_name[self.sel_axis], val, self.speed_val.get())561 self.mechq.put(m)562 #=======================================================================563 def mdi(self, id):564 if (not self.safety_check_ok()):565 return566 self.set_idle_state(ButtonState.BUSY)567 m = {}568 m['id'] = MechEvent.CMD_MDI569 m['cmd'] = id.get()570 self.mechq.put(m)571 #=======================================================================572 def set_all_zero(self):573 self.set_idle_state(ButtonState.BUSY)574 m = {}575 m['id'] = MechEvent.CMD_ALL_ZERO576 self.mechq.put(m)577 #=======================================================================578 def toggle_estop(self):579 self.set_idle_state(ButtonState.BUSY2) # disable (block) estop button during a estop580 if (self.dog.get_state() & MechStateBit.ESTOP):581 m = {}582 m['id'] = MechEvent.CMD_ESTOP_RESET583 self.mechq.put(m) # this command goes through the mech thread584 else:585 self.dog.estop() # this command goes through the GUI thread.586 #=======================================================================587 def set_estop_state(self):588 if (self.dog.get_state() & MechStateBit.ESTOP):589 self.set_idle_state(ButtonState.ESTOP)590 else:591 self.set_idle_state(ButtonState.IDLE)592 #=======================================================================593 def safety_check_ok(self):594 if (self.dog.get_state() & MechStateBit.ESTOP):595 logging.error("Not out of ESTOP. Try pressing the ESTOP button.")596 return False597 if (not(self.dog.get_state() & MechStateBit.HOMED)):598 logging.warn("Not all zeroed. Try pressing the 'All Zero' button.")599 return False600 return True # ok to run mech601 #=======================================================================602 def resume(self):603 self.set_idle_state(ButtonState.RESUME2)604 m = {}605 m['id'] = MechEvent.CMD_RUN606 m['file'] = "paused"607 self.mechq.put(m)608 #=======================================================================609 def display_gcode_lines(self, gcodefile, beg, end, done):610 # Attempt to open the file.611 done_line = ""612 try:613 gfile = open(gcodefile,'r')614 # Count number of lines.615 cnt = 0616 line = gfile.readline()617 while (line != ''):618 cnt += 1619 if (cnt >= beg):620 logging.info("%d: %s" % (cnt, line.rstrip()))621 if (cnt == done):622 done_line = line.rstrip() # save this line for backplot623 if (cnt == end):624 break625 line = gfile.readline()626 gfile.close()627 except:628 pass629 return done_line630 #=======================================================================631 def display_max_line(self, gcodefile):632 # Attempt to open the file.633 try:634 gfile = open(gcodefile,'r')635 # Count number of lines.636 self.line_max = 0637 while (gfile.readline() != ''):638 self.line_max += 1639 self.line_num = 1640 self.status_line_num.config(text="%d/%d" % (self.line_num, self.line_max))641 gfile.close()642 except:643 pass644 #=======================================================================645 def auto(self, id):646 if (id == AutoSel.OPEN):647 gcodefile = filedialog.askopenfilename(parent=self, title="Open Gcode File")648 if (len(gcodefile) != 0):649 self.auto_val.set(gcodefile)650 self.display_max_line(gcodefile)651 elif (id == AutoSel.RUN):652 gcodefile = self.auto_val.get()653 if (gcodefile == ''):654 return655 if (not self.safety_check_ok()):656 return657 self.display_max_line(gcodefile)658 self.set_idle_state(ButtonState.BUSY)659 m = {}660 m['id'] = MechEvent.CMD_RUN661 m['file'] = gcodefile662 self.mechq.put(m)663 self.bp3d.clear_plot()664 else:665 gcodefile = self.auto_val.get()666 if (gcodefile == ''):667 return668 if (self.dog.get_state() & MechStateBit.VERIFY):669 self.dog.verify_cancel()670 else:671 self.display_max_line(gcodefile)672 self.set_idle_state(ButtonState.VERIFY)673 m = {}674 m['id'] = MechEvent.CMD_VERIFY675 m['file'] = gcodefile676 self.mechq.put(m)677 self.bp3d.clear_plot()678 #=======================================================================679 def create_logger(self, panel):680 if (not os.path.exists(HOME_DIR)):681 # Create application '.' directory in user's home directory.682 os.makedirs(HOME_DIR)683 root = logging.getLogger()684 root.setLevel(level=logging.DEBUG)685 h = logging.handlers.TimedRotatingFileHandler("%s/%s" % (HOME_DIR, "log.txt"), "D", 1, backupCount=5)686 f = logging.Formatter('%(asctime)s:%(levelname)s:%(filename)s:%(lineno)s:%(message)s')...

Full Screen

Full Screen

robin.py

Source:robin.py Github

copy

Full Screen

...37 self.talk(bio)38 time.sleep(0.5)39 p = self.ui.robinGUI.create_popup()40 p.open()41 def set_idle_state(self, idle):42 print(f"setting idle to {idle}")43 self.idle = idle44 if idle is True:45 self.execute_ui_action("check_bg_processes_status", idle)46 def startup_message(self):47 """ Returns message that would be spoken at start up """48 if self.config["is_first_launch"] is True:49 message = f"Hi, I am {self.config['name']}, your virtual assistant. To talk to me, please say " \50 f"'hello {self.config['name']}', or tap the mic button."51 else:52 affiliation = random.choice(['friend', 'buddy', 'paddy', 'yo'])53 message = f"Hey {affiliation}! What can i do for you today?"54 return message55 def execute_ui_action(self, callback_name, *args):56 """57 Checks if instance of self.ui has been initialized and then executes callback if true58 else skip59 """60 if self.ui is not None:61 getattr(self.ui, callback_name)(*args)62 return True63 return False64 def sanitize_command(self, command):65 # Convert command to lowercase66 command = command.lower()67 words_list = ['i said ', 'what i said was ', 'what i said is ', f'hello {self.config["name"]}',68 f'hey {self.config["name"]}', 'can you ', self.config["name"]]69 if contains(command, words_list):70 for i in range(len(words_list)):71 if command.startswith(words_list[i]) > -1:72 command = command.replace(words_list[i], '')73 command = command.strip()74 return command75 def remember_command(self, command):76 command = '' if command is None else command77 self.questions.append(command)78 def forget_command(self):79 if len(self.questions) > 0:80 self.questions.pop()81 def display_on_ui(self, message):82 success = self.execute_ui_action('update_ui_screen', message)83 if success is False:84 print(message)85 def audio_to_text(self, **kwargs):86 mic_is_listening = False87 language = self.config["language"] or 'en-us'88 try:89 _input = sr.Microphone()90 with _input as source:91 self.listener.adjust_for_ambient_noise(source)92 # Display listening and do mic animation93 mic_is_listening = True94 self.execute_ui_action('start_mic_animation')95 self.display_on_ui('Listening...')96 # Listen with specified source device97 recorded_audio = self.listener.listen(source, 15, 25)98 mic_is_listening = False99 self.execute_ui_action('stop_mic_animation')100 self.display_on_ui('Processing...')101 # Translate recorded audio to command102 return self.listener.recognize_google(recorded_audio, language=language)103 finally:104 if mic_is_listening:105 self.execute_ui_action('stop_mic_animation')106 def listen(self, is_asking_for_confirmation=False, confirmation_callbacks=None):107 def callback(instance, is_asking_for_confirmation, confirmation_callbacks):108 try:109 instance.set_idle_state(False)110 command = self.audio_to_text()111 # Process command112 instance.display_on_ui(f'[color={instance.green_text_color}]You:[/color] {command}')113 time.sleep(1)114 instance.process_command(command, is_asking_for_confirmation, confirmation_callbacks)115 instance.set_idle_state(True)116 except sr.UnknownValueError as unknown_value:117 if unknown_value is not '':118 print(str(unknown_value))119 # If user has not being asked120 if is_asking_for_confirmation is False:121 # Ask user to repeat question, if something was said122 message = "Sorry I couldn't process what you said. Did you say something?"123 def yes_callback(*args):124 c = args[1]125 instance.forget_command()126 if 'i said' in c:127 what_was_said = c.split('i said')[1]128 instance.process_command(what_was_said)129 instance.set_idle_state(True)130 else:131 instance.talk('ok, what did you say?')132 instance.listen(True)133 def no_callback(robin_instance, c):134 robin_instance.forget_command()135 self.talk('ok, bye!')136 instance.set_idle_state(True)137 instance.ask_for_confirmation(None, message, yes_callback, no_callback)138 else:139 instance.talk("I didn't hear anything")140 self.forget_command()141 instance.set_idle_state(True)142 except sr.RequestError:143 instance.talk("I cannot listen to your commands while your device is offline")144 instance.set_idle_state(True)145 except Exception as ex:146 instance.talk(ex)147 instance.set_idle_state(True)148 # Run callback on a different thread to avoid blocking main thread149 if current_thread() is main_thread():150 ask_confirmation_thread = Thread(target=callback, daemon=True, args=(151 self, is_asking_for_confirmation, confirmation_callbacks152 ))153 ask_confirmation_thread.start()154 else:155 callback(self, is_asking_for_confirmation, confirmation_callbacks)156 def ask_for_confirmation(self, command, message=None, yes_callback=None, no_callback=None):157 if message is None:158 message = f'You said, {self.word_processor.transform_speech_to_other_person(command)}. Am I right?'159 print(self.questions)160 # Confirm command161 if len(self.questions) == 0:162 self.talk(message)163 self.remember_command(command)164 confirmation_callbacks = {165 "yes": yes_callback,166 "no": no_callback167 }168 self.listen(True, confirmation_callbacks)169 # Command might be a confirmation170 else:171 ret_value = None172 if contains(command, self.word_processor.get_examples('confirmations')) or \173 starts_with(command, self.word_processor.get_starters('confirmations')):174 if yes_callback is not None:175 yes_callback(self, self.questions[0])176 ret_value = True177 elif contains(command, self.word_processor.get_examples('disagreements')) or \178 starts_with(command, self.word_processor.get_starters('disagreements')):179 if no_callback is not None:180 no_callback(self, self.questions[0])181 ret_value = False182 else:183 self.talk("Sorry, I didn't quite understand that")184 self.forget_command()185 return ret_value186 def process_command(self, command, is_asking_for_confirmation=False, confirmation_callbacks=None):187 # Thread callback function188 def callback(instance, command, is_asking_for_confirmation, confirmation_callbacks):189 confirmation_callbacks = {190 "yes": None, "no": None191 } if confirmation_callbacks is None else confirmation_callbacks192 # Remove unnecessary words in command193 command = instance.sanitize_command(command)194 command = instance.word_processor.transform_text_to_numbers(command)195 has_modified_command = False196 command_classification = instance.word_processor.get_classification(command)197 # ====[START]===================================================================198 # Casual greetings command199 if 'greetings' in command_classification:200 results = greetings_handler(instance, command, command_classification)201 command = results["modified_command"]202 response_to_command = " ".join(results["responses"])203 command_classification = results["command_classifications"]204 has_modified_command = results["has_modified_command"]205 # Respond on a separate thread to avoid blocking current thread206 response_thread = Thread(target=instance.talk, daemon=True, args=(response_to_command,))207 response_thread.start()208 time.sleep(0.5)209 # Permission request210 if 'permission_request' in command_classification:211 instance.talk('Yeah sure')212 time.sleep(0.5)213 command_classification.remove('permission_request')214 for starter in instance.word_processor.get_starters('permission_request'):215 found = re.match(starter, command)216 if found:217 command = command[found.end():].strip()218 has_modified_command = True219 break220 # Gratitude221 if 'gratitude' in command_classification:222 instance.talk('Yeah sure. Anytime!')223 time.sleep(0.5)224 command_classification.remove('gratitude')225 if len(command_classification) <= 0:226 instance.set_idle_state(True)227 return228 # =====[END]====================================================================229 # Classify remaining command230 command_classification = instance.word_processor.get_classification(command)231 # Remove "greeting", "permission", and "gratitude" requests from classification232 command_classification = remove_list_elements(command_classification, [233 "greetings", "gratitude", "permission_request"234 ])235 # If the AI doesn't understand the remaining command after being modified, return236 if len(command_classification) == 0 and has_modified_command:237 instance.set_idle_state(True)238 return239 # ====[START]===================================================================240 # Exit request241 if 'sendoffs' in command_classification:242 instance.talk("Goodbye! Let's talk again later.")243 instance.set_idle_state(False)244 instance.ui.exit()245 # AI info requests246 elif 'name_request' in command_classification:247 instance.talk(f'My name is {instance.config["name"]}')248 # Time requests249 elif 'time_request' in command_classification:250 results = time_request_handler(instance, command, command_classification)251 command_classification = results["command_classifications"]252 # Date request253 elif 'date_request' in command_classification:254 results = date_request_handler(instance, command, command_classification)255 command_classification = results["command_classifications"]256 # Media request257 elif 'media_request' in command_classification:258 results = media_request_handler(instance, command, command_classification)259 command_classification = results["command_classifications"]260 # System task requests261 elif 'system_action_request' in command_classification:262 results = system_action_handler(instance, command, command_classification)263 command_classification = results["command_classifications"]264 # Calculation request265 elif 'calculation_request' in command_classification:266 results = calculation_request_handler(instance, command, command_classification)267 command_classification = results["command_classifications"]268 # AI customisation requests269 elif "ai_customisation_requests" in command_classification:270 results = ai_customization_handler(instance, command, command_classification)271 has_modified_command = results["has_modified_command"]272 # Request for info about something273 elif 'info_request' in command_classification:274 if contains(command, r'tell me\s*(.+)?\s*about you(rself)?'):275 instance.introduce_ai()276 return277 if contains(command, [r'my (\w+)?(\s*)battery percent', r'the (\w+)?(\s*)battery percent']):278 battery_percent = plyer.battery.status["percentage"]279 instance.talk(f'Your PC battery is currently at {battery_percent}%')280 return281 # Remove this starters282 starters = ['do you know', 'who is', 'who was', 'who were', 'tell me about', 'i want to know']283 if starts_with(command, starters):284 for phrase in starters:285 if phrase in command:286 command = command.split(phrase)[1].strip()287 formatted_command = command288 results = info_request_handler(instance, formatted_command, command_classification)289 command_classification = results["command_classifications"]290 # Dismissal command291 elif 'dismissals' in command_classification:292 instance.talk('Ok, sure!')293 instance.forget_command()294 # Unknown classifications295 else:296 # Default confirmation callbacks297 def yes_callback(*args):298 responses_to_give = [299 "Sadly, I am still unable to fully understand your command for now.",300 "Uhm, I don't really know how to respond to this kinds of requests yet.",301 "Still learning."302 ]303 instance.talk(random.choice(responses_to_give))304 time.sleep(0.5)305 try:306 instance.talk("But here is what I got from the web...")307 from pywhatkit import search308 query = args[1]309 search(query)310 except Exception:311 instance.talk("I couldn't access the internet. Your device seems to be offline")312 def no_callback(*args):313 responses_to_give = ["ok", "Ouch sorry about that", "My bad"]314 instance.forget_command()315 instance.talk(f'{random.choice(responses_to_give)}, what did you say?')316 instance.listen()317 if is_asking_for_confirmation is True:318 instance.ask_for_confirmation(319 command, yes_callback=confirmation_callbacks['yes'],320 no_callback=confirmation_callbacks['no']321 )322 else:323 instance.ask_for_confirmation(command, yes_callback=yes_callback, no_callback=no_callback)324 time.sleep(1)325 instance.set_idle_state(True)326 # =====[END]====================================================================327 if current_thread() is main_thread():328 process_thread = Thread(329 target=callback, daemon=True,330 args=(self, command, is_asking_for_confirmation, confirmation_callbacks)331 )332 process_thread.start()333 else:334 callback(self, command, is_asking_for_confirmation, confirmation_callbacks)335 def talk(self, text, display_message=True):336 def speak(string_to_speak, ai_instance):337 try:338 _tts_engine = conf.get_tts_engine(voice_index=self.config['default_voice'])339 _tts_engine.say(string_to_speak)340 _tts_engine.runAndWait()341 except RuntimeError as ree:342 print(ree)343 time.sleep(0.5)344 self.set_idle_state(False)345 if display_message:346 self.display_on_ui(f"[color={self.green_text_color}]{self.config['name']}:[/color] {text}")347 self.execute_ui_action('audio_visualizer_action')348 speak(text, self)349 def stop_talk(self):350 # self.tts_engine351 pass352 def exit(self):353 self.ui.robin_background_service.should_exit = True354 conf.save_config(ai_pref_path, self.config)355class RobinInterface:356 def __init__(self, robin_instance=None, ui_instance=None):357 self.listener = sr.Recognizer()358 self.stop_listen_in_bg = None359 self.robin = robin_instance360 self.ui = ui_instance361 self.process_db = None362 def __init_robin_instance(self):363 """ Initializes robin instance and saves it """364 self.robin = Robin(self.ui)365 def verify_robin_instance(self, ui=None):366 """367 Checks if instance of robin engine has been initialized. If it has been initialized,368 skip else initialized robin instance369 """370 if self.robin is None:371 if self.ui is None:372 self.ui = ui373 self.__init_robin_instance()374 # UI HANDLERS ===================================================================375 def robin_listen_action(self, ui=None):376 display_calling_process('AppBGListener: robin_listen_action')377 self.verify_robin_instance(ui)378 self.robin.set_idle_state(False)379 self.ui.robin_background_service.pause_capture(False)380 self.robin.listen()381 def robin_stop_listen_action(self, ui=None):382 display_calling_process('AppBGListener: robin_stop_listen_action')383 self.verify_robin_instance(ui)384 self.robin.set_idle_state(True)385 self.robin.execute_ui_action('stop_mic_animation')386 def robin_read_action(self, command, ui=None):387 display_calling_process('AppBGListener: robin_read_action')388 try:389 self.verify_robin_instance(ui)390 self.ui.robin_background_service.pause_capture(False)391 self.robin.set_idle_state(False)392 self.robin.display_on_ui(f'You: {command}')393 time.sleep(1)394 # Process command395 self.robin.process_command(command)396 except Exception as ex:397 print('robin_read_action: ', ex)398# stop_it = False399# wp = Robin()400# while stop_it is False:401# sentence = input('Type in a sentence: ')402# wp.process_command(sentence)403#404# stop_command = input('Type "stop" to exit or press enter to continue:\n>>>')405# print()...

Full Screen

Full Screen

utils_stress.py

Source:utils_stress.py Github

copy

Full Screen

...172 logging.debug("Current governor: %s", cpu.get_freq_governor() if hasattr(cpu, 'get_freq_governor') else cpu.get_cpufreq_governor())173 time.sleep(self.event_sleep_time)174 elif "cpu_idle" in event:175 idlestate = cpu.get_idle_state() if hasattr(cpu, 'get_idle_state') else cpu.get_cpuidle_state()176 cpu.set_idle_state() if hasattr(cpu, 'set_idle_state') else cpu.set_cpuidle_state()177 time.sleep(self.event_sleep_time)178 cpu.set_idle_state(setstate=idlestate) if hasattr(cpu, 'set_idle_state') else cpu.set_cpuidle_state(setstate=idlestate)179 time.sleep(self.event_sleep_time)180 elif "cpuoffline" in event:181 online_count = cpu.online_count() if hasattr(cpu, 'online_count') else cpu.online_cpus_count()182 processor = self.host_cpu_list[random.randint(0, online_count-1)]183 cpu.offline(processor)184 time.sleep(self.event_sleep_time)185 cpu.online(processor)186 else:187 raise NotImplementedError...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful