-
Notifications
You must be signed in to change notification settings - Fork 990
Expand file tree
/
Copy pathapplication.py
More file actions
271 lines (239 loc) · 11 KB
/
Copy pathapplication.py
File metadata and controls
271 lines (239 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# -*- coding: utf-8 -*-
import logging
import os
import shutil
import yaml
import pkg_resources
from . import audioengine
from . import brain
from . import paths
from . import pluginstore
from . import conversation
from . import mic
from . import local_mic
from . import batch_mic
USE_STANDARD_MIC = 0
USE_TEXT_MIC = 1
USE_BATCH_MIC = 2
class Jasper(object):
def __init__(self, use_mic=USE_STANDARD_MIC, batch_file=None):
self._logger = logging.getLogger(__name__)
# Create config dir if it does not exist yet
if not os.path.exists(paths.CONFIG_PATH):
try:
os.makedirs(paths.CONFIG_PATH)
except OSError:
self._logger.error("Could not create config dir: '%s'",
paths.CONFIG_PATH, exc_info=True)
raise
# Check if config dir is writable
if not os.access(paths.CONFIG_PATH, os.W_OK):
self._logger.critical("Config dir %s is not writable. Jasper " +
"won't work correctly.",
paths.CONFIG_PATH)
# FIXME: For backwards compatibility, move old config file to newly
# created config dir
old_configfile = os.path.join(paths.PKG_PATH, 'profile.yml')
new_configfile = paths.config('profile.yml')
if os.path.exists(old_configfile):
if os.path.exists(new_configfile):
self._logger.warning("Deprecated profile file found: '%s'. " +
"Please remove it.", old_configfile)
else:
self._logger.warning("Deprecated profile file found: '%s'. " +
"Trying to copy it to new location '%s'.",
old_configfile, new_configfile)
try:
shutil.copy2(old_configfile, new_configfile)
except shutil.Error:
self._logger.error("Unable to copy config file. " +
"Please copy it manually.",
exc_info=True)
raise
# Read config
self._logger.debug("Trying to read config file: '%s'", new_configfile)
try:
with open(new_configfile, "r") as f:
self.config = yaml.safe_load(f)
except OSError:
self._logger.error("Can't open config file: '%s'", new_configfile)
raise
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e:
self._logger.error("Unable to parse config file: %s %s",
e.problem.strip(), str(e.problem_mark).strip())
raise
try:
language = self.config['language']
except KeyError:
self._logger.warning(
"language not specified in profile, using 'en-US'")
else:
self._logger.info("Using language '%s'", language)
try:
audio_engine_slug = self.config['audio_engine']
except KeyError:
audio_engine_slug = 'pyaudio'
self._logger.info("audio_engine not specified in profile, using " +
"defaults.")
self._logger.debug("Using Audio engine '%s'", audio_engine_slug)
try:
active_stt_slug = self.config['stt_engine']
except KeyError:
active_stt_slug = 'sphinx'
self._logger.warning("stt_engine not specified in profile, " +
"using defaults.")
self._logger.debug("Using STT engine '%s'", active_stt_slug)
try:
passive_stt_slug = self.config['stt_passive_engine']
except KeyError:
passive_stt_slug = active_stt_slug
self._logger.debug("Using passive STT engine '%s'", passive_stt_slug)
try:
tts_slug = self.config['tts_engine']
except KeyError:
tts_slug = 'espeak-tts'
self._logger.warning("tts_engine not specified in profile, using " +
"defaults.")
self._logger.debug("Using TTS engine '%s'", tts_slug)
try:
tti_slug = self.config['tti_engine']
except KeyError:
tti_slug = 'phrasematcher-tti'
self._logger.warning("tti_engine not specified in profile, using " +
"defaults.")
self._logger.debug("Using TTI engine '%s'", tti_slug)
try:
keyword = self.config['keyword']
except KeyError:
keyword = 'Jasper'
self._logger.info("Using keyword '%s'", keyword)
# Load plugins
plugin_directories = [
paths.config('plugins'),
pkg_resources.resource_filename(__name__, '../plugins')
]
self.plugins = pluginstore.PluginStore(plugin_directories)
self.plugins.detect_plugins()
# Initialize AudioEngine
ae_info = self.plugins.get_plugin(audio_engine_slug,
category='audioengine')
self.audio = ae_info.plugin_class(ae_info, self.config)
# Initialize audio input device
devices = [device.slug for device in self.audio.get_devices(
device_type=audioengine.DEVICE_TYPE_INPUT)]
try:
device_slug = self.config['input_device']
except KeyError:
device_slug = self.audio.get_default_device(output=False).slug
self._logger.warning("input_device not specified in profile, " +
"defaulting to '%s' (Possible values: %s)",
device_slug, ', '.join(devices))
try:
input_device = self.audio.get_device_by_slug(device_slug)
if audioengine.DEVICE_TYPE_INPUT not in input_device.types:
raise audioengine.UnsupportedFormat(
"Audio device with slug '%s' is not an input device"
% input_device.slug)
except (audioengine.DeviceException) as e:
self._logger.critical(e.args[0])
self._logger.warning('Valid output devices: %s',
', '.join(devices))
raise
# Initialize audio output device
devices = [device.slug for device in self.audio.get_devices(
device_type=audioengine.DEVICE_TYPE_OUTPUT)]
try:
device_slug = self.config['output_device']
except KeyError:
device_slug = self.audio.get_default_device(output=True).slug
self._logger.warning("output_device not specified in profile, " +
"defaulting to '%s' (Possible values: %s)",
device_slug, ', '.join(devices))
try:
output_device = self.audio.get_device_by_slug(device_slug)
if audioengine.DEVICE_TYPE_OUTPUT not in output_device.types:
raise audioengine.UnsupportedFormat(
"Audio device with slug '%s' is not an output device"
% output_device.slug)
except (audioengine.DeviceException) as e:
self._logger.critical(e.args[0])
self._logger.warning('Valid output devices: %s',
', '.join(devices))
raise
# create instanz of SST and TTS
active_stt_plugin_info = self.plugins.get_plugin(
active_stt_slug, category='stt')
active_stt_plugin = active_stt_plugin_info.plugin_class(
active_stt_plugin_info,
self.config)
if passive_stt_slug != active_stt_slug:
passive_stt_plugin_info = self.plugins.get_plugin(
passive_stt_slug, category='stt')
else:
passive_stt_plugin_info = active_stt_plugin_info
passive_stt_plugin = passive_stt_plugin_info.plugin_class(
passive_stt_plugin_info, self.config)
tts_plugin_info = self.plugins.get_plugin(tts_slug, category='tts')
tts_plugin = tts_plugin_info.plugin_class(tts_plugin_info, self.config)
# Initialize Mic
if use_mic == USE_TEXT_MIC:
self.mic = local_mic.Mic()
self._logger.info('Using local text input and output')
elif use_mic == USE_BATCH_MIC:
self.mic = batch_mic.Mic(passive_stt_plugin,
active_stt_plugin, batch_file,
keyword=keyword)
self._logger.info('Using batched mode')
else:
self.mic = mic.Mic(
input_device, output_device,
passive_stt_plugin, active_stt_plugin,
tts_plugin, self.config, keyword=keyword)
# Text-to-intent handler
tti_plugin_info = self.plugins.get_plugin(tti_slug, category='tti')
#tti_plugin = tti_plugin_info.plugin_class(tti_plugin_info, self.config)
# Initialize Brain
self.brain = brain.Brain(self.config,
tti_plugin_info.plugin_class(tti_plugin_info, self.config))
for info in self.plugins.get_plugins_by_category('speechhandler'):
# create instanz
try:
plugin = info.plugin_class(info, self.config,
tti_plugin_info.plugin_class(tti_plugin_info, self.config), self.mic)
except Exception as e:
self._logger.warning(
"Plugin '%s' skipped! (Reason: %s)", info.name,
e.message if hasattr(e, 'message') else 'Unknown',
exc_info=(
self._logger.getEffectiveLevel() == logging.DEBUG))
else:
self.brain.add_plugin(plugin)
if len(self.brain.get_plugins()) == 0:
msg = 'No plugins for handling speech found!'
self._logger.error(msg)
raise RuntimeError(msg)
elif len(self.brain.get_all_phrases()) == 0:
msg = 'No command phrases found!'
self._logger.error(msg)
raise RuntimeError(msg)
# init SSTs and compile vocabulary if needed
active_stt_plugin.init('default', self.brain.get_plugin_phrases())
passive_stt_plugin.init('keyword', self.brain.get_standard_phrases() + [keyword])
# Initialize Conversation
self.conversation = conversation.Conversation(
self.mic, self.brain, self.config)
def list_plugins(self):
plugins = self.plugins.get_plugins()
len_name = max(len(info.name) for info in plugins)
len_version = max(len(info.version) for info in plugins)
for info in plugins:
print("%s %s - %s" % (info.name.ljust(len_name),
("(v%s)" % info.version).ljust(len_version),
info.description))
def list_audio_devices(self):
for device in self.audio.get_devices():
device.print_device_info(
verbose=(self._logger.getEffectiveLevel() == logging.DEBUG))
def run(self):
self.conversation.greet()
self.conversation.handleForever()