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.

util.py 7.0KB

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