Somewhat fancy voice command recognition software
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

shell.py 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # This is part of Kaylee
  2. # -- this code is licensed GPLv3
  3. # Copyright 2015-2017 Clayton G. Hobbs
  4. # Portions Copyright 2013 Jezra
  5. """Run shell commands that match voice commands
  6. This Kaylee plugin can be used to perform the job of `Blather
  7. <https://gitlab.com/jezra/blather>`__. Its configuration is of the
  8. following format::
  9. ".shell": {
  10. "VOICE_COMMAND": "SHELL_COMMAND",
  11. ...
  12. }
  13. A VOICE_COMMAND may contain any number of the special word ``%d``,
  14. which is a stand-in for a spoken number. The spoken number is
  15. transformed into a decimal integer which may be substituted into the
  16. SHELL_COMMAND any number of times. These substitutions are made by
  17. writing ``{INDEX}`` in the SHELL_COMMAND, where INDEX is an integer
  18. counting the ``%d`` strings from 0. An example of this type of command
  19. is::
  20. "%d is a number": "echo 'the number you said was {0}'"
  21. """
  22. import subprocess
  23. from . import PluginBase, Handler
  24. from ..numbers import NumberParser
  25. class Plugin(PluginBase):
  26. """Run shell commands that match voice commands"""
  27. def __init__(self, config, name):
  28. """Initialize the shell plugin"""
  29. super().__init__(config, name)
  30. self.number_parser = NumberParser()
  31. self.commands = self.options
  32. for voice_cmd in self.commands.keys():
  33. self.corpus_strings.add(voice_cmd.strip().replace('%d', ''))
  34. def get_handler(self, text):
  35. """Return whether or not the command can be handled"""
  36. if text in self.commands:
  37. # If there's an exact match, return a handler for it
  38. return ShellHandler(1, self.commands[text])
  39. else:
  40. # Otherwise, try substituting numbers
  41. numt, nums = self.number_parser.parse_all_numbers(text)
  42. if numt in self.commands:
  43. # Return a handler if we have a match
  44. return ShellHandler(1, self.commands[numt], nums)
  45. # Return None if that fails too
  46. return None
  47. class ShellHandler(Handler):
  48. """Handle a voice command that corresponds to a shell command"""
  49. def __init__(self, confidence, command, nums=None):
  50. """Determine the exact command that will be run"""
  51. super().__init__(confidence)
  52. if nums is None:
  53. self.command = command
  54. else:
  55. self.command = command.format(*nums)
  56. def __call__(self, tts):
  57. """Print the command, then run it"""
  58. print(self.command)
  59. subprocess.call(self.command, shell=True)