Somewhat fancy voice command recognition software
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.py 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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("-p", "--pass-words",
  44. action="store_true", dest="pass_words", default=False,
  45. help="Pass the recognized words as arguments to the shell" +
  46. " command")
  47. self._parser.add_argument("-H", "--history", type=int,
  48. action="store", dest="history",
  49. help="Number of commands to store in history file")
  50. self._parser.add_argument("-m", "--microphone", type=int,
  51. action="store", dest="microphone", default=None,
  52. help="Audio input card to use (if other than system default)")
  53. self._parser.add_argument("--valid-sentence-command", type=str,
  54. dest="valid_sentence_command", action='store',
  55. help="Command to run when a valid sentence is detected")
  56. self._parser.add_argument("--invalid-sentence-command", type=str,
  57. dest="invalid_sentence_command", action='store',
  58. help="Command to run when an invalid sentence is detected")
  59. # Read the configuration file
  60. self._read_options_file()
  61. # Parse command-line arguments, overriding config file as appropriate
  62. self._parser.parse_args(namespace=self.options)
  63. def _make_dir(self, directory):
  64. if not os.path.exists(directory):
  65. os.makedirs(directory)
  66. def _read_options_file(self):
  67. try:
  68. with open(self.opt_file, 'r') as f:
  69. self.options = json.load(f)
  70. self.options = Namespace(**self.options)
  71. except FileNotFoundError:
  72. # Make an empty options namespace
  73. self.options = Namespace()
  74. class Hasher:
  75. """Keep track of hashes for Kaylee"""
  76. def __init__(self, config):
  77. self.config = config
  78. try:
  79. with open(self.config.hash_file, 'r') as f:
  80. self.hashes = json.load(f)
  81. except IOError:
  82. # No stored hash
  83. self.hashes = {}
  84. def __getitem__(self, hashname):
  85. try:
  86. return self.hashes[hashname]
  87. except (KeyError, TypeError):
  88. return None
  89. def __setitem__(self, hashname, value):
  90. self.hashes[hashname] = value
  91. def get_hash_object(self):
  92. """Returns an object to compute a new hash"""
  93. return hashlib.sha256()
  94. def store(self):
  95. """Store the current hashes into a the hash file"""
  96. with open(self.config.hash_file, 'w') as f:
  97. json.dump(self.hashes, f)
  98. class LanguageUpdater:
  99. """
  100. Handles updating the language using the online lmtool.
  101. This class provides methods to check if the corpus has changed, and to
  102. update the language to match the new corpus using the lmtool. This allows
  103. us to automatically update the language if the corpus has changed, saving
  104. the user from having to do this manually.
  105. """
  106. def __init__(self, config):
  107. self.config = config
  108. self.hasher = Hasher(config)
  109. def update_language_if_changed(self):
  110. """Test if the language has changed, and if it has, update it"""
  111. if self.language_has_changed():
  112. self.update_language()
  113. self.save_language_hash()
  114. def language_has_changed(self):
  115. """Use hashes to test if the language has changed"""
  116. self.stored_hash = self.hasher['language']
  117. # Calculate the hash the language file has right now
  118. hasher = self.hasher.get_hash_object()
  119. with open(self.config.strings_file, 'rb') as sfile:
  120. buf = sfile.read()
  121. hasher.update(buf)
  122. self.new_hash = hasher.hexdigest()
  123. return self.new_hash != self.stored_hash
  124. def update_language(self):
  125. """Update the language using the online lmtool"""
  126. print('Updating language using online lmtool')
  127. host = 'http://www.speech.cs.cmu.edu'
  128. url = host + '/cgi-bin/tools/lmtool/run'
  129. # Submit the corpus to the lmtool
  130. response_text = ""
  131. with open(self.config.strings_file, 'rb') as corpus:
  132. files = {'corpus': corpus}
  133. values = {'formtype': 'simple'}
  134. r = requests.post(url, files=files, data=values)
  135. response_text = r.text
  136. # Parse response to get URLs of the files we need
  137. path_re = r'.*<title>Index of (.*?)</title>.*'
  138. number_re = r'.*TAR([0-9]*?)\.tgz.*'
  139. for line in response_text.split('\n'):
  140. # If we found the directory, keep it and don't break
  141. if re.search(path_re, line):
  142. path = host + re.sub(path_re, r'\1', line)
  143. # If we found the number, keep it and break
  144. elif re.search(number_re, line):
  145. number = re.sub(number_re, r'\1', line)
  146. break
  147. lm_url = path + '/' + number + '.lm'
  148. dic_url = path + '/' + number + '.dic'
  149. self._download_file(lm_url, self.config.lang_file)
  150. self._download_file(dic_url, self.config.dic_file)
  151. def save_language_hash(self):
  152. self.hasher['language'] = self.new_hash
  153. self.hasher.store()
  154. def _download_file(self, url, path):
  155. r = requests.get(url, stream=True)
  156. if r.status_code == 200:
  157. with open(path, 'wb') as f:
  158. for chunk in r:
  159. f.write(chunk)