forked from vavrek/Open-Assistant-Version-Zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
executable file
·188 lines (154 loc) · 6.09 KB
/
run.py
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
import logging
logging.basicConfig(level=logging.CRITICAL)
logger = logging.getLogger(__name__)
from argparse import ArgumentParser, Namespace
import os
import signal
import sys
import subprocess
from pocketsphinx import LiveSpeech, get_model_path
from core import Config, Assistant
from modules.language import LanguageUpdater
def _parser(args):
parser = ArgumentParser()
parser.add_argument("-c", "--continuous",
action="store_true", dest="continuous", default=False,
help="Start interface with 'continuous' listen enabled")
parser.add_argument("-p", "--pass-words",
action="store_true", dest="pass_words", default=False,
help="Pass the recognized words as arguments to the shell" +
" command")
parser.add_argument("-H", "--history", type=int,
action="store", dest="history",
help="Number of commands to store in history file")
parser.add_argument("-m", "--microphone", type=int,
action="store", dest="microphone", default=None,
help="Audio input card to use (if other than system default)")
parser.add_argument("--valid-sentence-command", type=str,
dest="valid_sentence_command", action='store',
help="Command to run when a valid sentence is detected")
parser.add_argument("--invalid-sentence-command", type=str,
dest="invalid_sentence_command", action='store',
help="Command to run when an invalid sentence is detected")
parser.add_argument("-M", "--mind", type=str,
dest="mind_dir", action='store',
help="Path to mind to use for assistant")
return parser.parse_args(args)
def recognizer_finished(a, recognizer, text):
logger.debug("Agent: {}, Recognier: {}, Text: {}".format(a, recognizer, text))
t = text.lower()
#numt, nums = self.number_parser.parse_all_numbers(t)
# Is There A Matching Command?
if t in a.config.commands:
# Run The 'valid_sentence_command' If It's Set
os.system('clear')
print("Open Assistant: \x1b[32mListening\x1b[0m")
if a.config.options['valid_sentence_command']:
subprocess.call(a.config.options['valid_sentence_command'],
shell=True)
cmd = a.config.commands[t]
# Should We Be Passing Words?
os.system('clear')
print("Open Assistant: \x1b[32mListening\x1b[0m")
if a.config.options['pass_words']:
cmd += " " + t
print("\x1b[32m< ! >\x1b[0m {0}".format(t))
run_command(a, cmd)
log_history(a, text)
#elif numt in self.commands:
# # Run 'valid_sentence_command' Set
# os.system('clear')
# print("Open Assistant: \x1b[32mListening\x1b[0m")
# if self.config.options['valid_sentence_command']:
# subprocess.call(self.config.options['valid_sentence_command'],
# shell=True)
# cmd = self.commands[numt]
# cmd = cmd.format(*nums)
# # Should We Be Passing Words?
# if self.config.options['pass_words']:
# cmd += " " + t
# print("\x1b[32m< ! >\x1b[0m {0}".format(t))
# self.run_command(cmd)
# self.log_history(text)
else:
# Run The Invalid_sentence_command If It's Set
if a.config.options['invalid_sentence_command']:
subprocess.call(a.config.options['invalid_sentence_command'],
shell=True)
print("\x1b[31m< ? >\x1b[0m {0}".format(t))
def log_history(a, text):
if a.config.options['history']:
a.history.append(text)
if len(a.history) > a.config.options['history']:
# Pop Off First Item
a.history.pop(0)
# Open And Truncate History File
with open(a.config.history_file, 'w') as hfile:
for line in a.history:
hfile.write(line + '\n')
def run_command(a, cmd):
"""PRINT COMMAND AND RUN"""
print("\x1b[32m< ! >\x1b[0m", cmd)
#recognizer.pause()
subprocess.call(cmd, shell=True)
#recognizer.listen()
def process_command(self, command):
print(command)
if command == "listen":
#self.recognizer.listen()
pass
elif command == "stop":
#self.recognizer.pause()
pass
elif command == "continuous_listen":
#self.continuous_listen = True
#self.recognizer.listen()
pass
elif command == "continuous_stop":
#self.continuous_listen = False
#self.recognizer.pause()
pass
elif command == "quit":
self.quit()
def main():
model_path = get_model_path()
#print (model_path)
# Parse command-line options,
# use `Config` to load mind configuration
# command-line overrides config file
args = _parser(sys.argv[1:])
logger.debug("Arguments: {args}".format(args=args))
conf = Config(path=args.mind_dir, **vars(args))
#
# Further patching to ease transition..
#
# Configure Language
logger.debug("Configuring Module: Language")
conf.strings_file = os.path.join(conf.cache_dir, "sentences.corpus")
conf.dic_file = os.path.join(conf.cache_dir, 'dic')
conf.lang_file = os.path.join(conf.cache_dir, 'lm')
conf.fsg_file = None #os.path.join(conf.cache_dir, 'fsg')
# sphinx_jsgf2fsg < conf.jsgf_file > conf.fsg_file
l = LanguageUpdater(conf)
l.update_language()
recognizer = LiveSpeech(
verbose=False,
sampling_rate=16000,
buffer_size=2048,
no_search=False,
full_utt=False,
hmm=os.path.join(model_path, 'en-us'),
lm=conf.lang_file,
dic=conf.dic_file
)
# A configured Assistant
a = Assistant(config=conf)
for phrase in recognizer:
#print(phrase.hypothesis())
recognizer_finished(a, recognizer, phrase.hypothesis())
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Killed by user')
sys.exit(0)