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.8KB

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