Somewhat fancy voice command recognition software
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # This is part of Kaylee
  2. # -- this code is licensed GPLv3
  3. # Copyright 2015-2016 Clayton G. Hobbs
  4. # Portions Copyright 2013 Jezra
  5. import re
  6. import json
  7. import hashlib
  8. import os
  9. from argparse import ArgumentParser, Namespace
  10. import requests
  11. from gi.repository import GLib
  12. class Config:
  13. """Keep track of the configuration of Kaylee"""
  14. # Name of the program, for later use
  15. program_name = "kaylee"
  16. # Directories
  17. conf_dir = os.path.join(GLib.get_user_config_dir(), program_name)
  18. cache_dir = os.path.join(GLib.get_user_cache_dir(), program_name)
  19. data_dir = os.path.join(GLib.get_user_data_dir(), program_name)
  20. # Configuration files
  21. opt_file = os.path.join(conf_dir, "options.json")
  22. # Cache files
  23. history_file = os.path.join(cache_dir, program_name + "history")
  24. hash_file = os.path.join(cache_dir, "hash.json")
  25. # Data files
  26. strings_file = os.path.join(data_dir, "sentences.corpus")
  27. lang_file = os.path.join(data_dir, 'lm')
  28. dic_file = os.path.join(data_dir, 'dic')
  29. def __init__(self):
  30. # Ensure necessary directories exist
  31. self._make_dir(self.conf_dir)
  32. self._make_dir(self.cache_dir)
  33. self._make_dir(self.data_dir)
  34. # Set up the argument parser
  35. self._parser = ArgumentParser()
  36. self._parser.add_argument("-i", "--interface", type=str,
  37. dest="interface", action='store',
  38. help="Interface to use (if any). 'g' for GTK or 'gt' for GTK" +
  39. " system tray icon")
  40. self._parser.add_argument("-c", "--continuous",
  41. action="store_true", dest="continuous", default=False,
  42. help="Start interface with 'continuous' listen enabled")
  43. self._parser.add_argument("-H", "--history", type=int,
  44. action="store", dest="history",
  45. help="Number of commands to store in history file")
  46. self._parser.add_argument("-m", "--microphone", type=int,
  47. action="store", dest="microphone", default=None,
  48. help="Audio input card to use (if other than system default)")
  49. self._parser.add_argument("--valid-sentence-command", type=str,
  50. dest="valid_sentence_command", action='store',
  51. help="Command to run when a valid sentence is detected")
  52. self._parser.add_argument("--invalid-sentence-command", type=str,
  53. dest="invalid_sentence_command", action='store',
  54. help="Command to run when an invalid sentence is detected")
  55. # Read the configuration file
  56. self._read_options_file()
  57. # Parse command-line arguments, overriding config file as appropriate
  58. self._parser.parse_args(namespace=self.options)
  59. def _make_dir(self, directory):
  60. if not os.path.exists(directory):
  61. os.makedirs(directory)
  62. def _read_options_file(self):
  63. try:
  64. with open(self.opt_file, 'r') as f:
  65. self.options = json.load(f)
  66. self.options = Namespace(**self.options)
  67. except FileNotFoundError:
  68. # Make an empty options namespace
  69. self.options = Namespace()
  70. class Hasher:
  71. """Keep track of hashes for Kaylee"""
  72. def __init__(self, config):
  73. self.config = config
  74. try:
  75. with open(self.config.hash_file, 'r') as f:
  76. self.hashes = json.load(f)
  77. except IOError:
  78. # No stored hash
  79. self.hashes = {}
  80. def __getitem__(self, hashname):
  81. try:
  82. return self.hashes[hashname]
  83. except (KeyError, TypeError):
  84. return None
  85. def __setitem__(self, hashname, value):
  86. self.hashes[hashname] = value
  87. def get_hash_object(self):
  88. """Returns an object to compute a new hash"""
  89. return hashlib.sha256()
  90. def store(self):
  91. """Store the current hashes into a the hash file"""
  92. with open(self.config.hash_file, 'w') as f:
  93. json.dump(self.hashes, f)
  94. class LanguageUpdater:
  95. """
  96. Handles updating the language using the online lmtool.
  97. This class provides methods to check if the corpus has changed, and to
  98. update the language to match the new corpus using the lmtool. This allows
  99. us to automatically update the language if the corpus has changed, saving
  100. the user from having to do this manually.
  101. """
  102. def __init__(self, config):
  103. self.config = config
  104. self.hasher = Hasher(config)
  105. def update_language_if_changed(self):
  106. """Test if the language has changed, and if it has, update it"""
  107. if self.language_has_changed():
  108. self.update_language()
  109. self.save_language_hash()
  110. def language_has_changed(self):
  111. """Use hashes to test if the language has changed"""
  112. self.stored_hash = self.hasher['language']
  113. # Calculate the hash the language file has right now
  114. hasher = self.hasher.get_hash_object()
  115. with open(self.config.strings_file, 'rb') as sfile:
  116. buf = sfile.read()
  117. hasher.update(buf)
  118. self.new_hash = hasher.hexdigest()
  119. return self.new_hash != self.stored_hash
  120. def update_language(self):
  121. """Update the language using the online lmtool"""
  122. print('Updating language using online lmtool')
  123. host = 'http://www.speech.cs.cmu.edu'
  124. url = host + '/cgi-bin/tools/lmtool/run'
  125. # Submit the corpus to the lmtool
  126. response_text = ""
  127. with open(self.config.strings_file, 'rb') as corpus:
  128. files = {'corpus': corpus}
  129. values = {'formtype': 'simple'}
  130. r = requests.post(url, files=files, data=values)
  131. response_text = r.text
  132. # Parse response to get URLs of the files we need
  133. path_re = r'.*<title>Index of (.*?)</title>.*'
  134. number_re = r'.*TAR([0-9]*?)\.tgz.*'
  135. for line in response_text.split('\n'):
  136. # If we found the directory, keep it and don't break
  137. if re.search(path_re, line):
  138. path = host + re.sub(path_re, r'\1', line)
  139. # If we found the number, keep it and break
  140. elif re.search(number_re, line):
  141. number = re.sub(number_re, r'\1', line)
  142. break
  143. lm_url = path + '/' + number + '.lm'
  144. dic_url = path + '/' + number + '.dic'
  145. self._download_file(lm_url, self.config.lang_file)
  146. self._download_file(dic_url, self.config.dic_file)
  147. def save_language_hash(self):
  148. self.hasher['language'] = self.new_hash
  149. self.hasher.store()
  150. def _download_file(self, url, path):
  151. r = requests.get(url, stream=True)
  152. if r.status_code == 200:
  153. with open(path, 'wb') as f:
  154. for chunk in r:
  155. f.write(chunk)