-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
223 lines (179 loc) · 6.37 KB
/
main.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
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
#!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run a recognizer using the Google Assistant Library.
The Google Assistant Library has direct access to the audio API, so this Python
code doesn't need to record audio. Hot word detection "OK, Google" is supported.
It is available for Raspberry Pi 2/3 only; Pi Zero is not supported.
"""
import logging
import platform
import subprocess
import sys
import time
import os
import aiy.assistant.auth_helpers
from aiy.assistant.library import Assistant
import aiy.audio
import aiy.voicehat
from google.assistant.library.event import EventType
import requests
import json
import threading
from difflib import SequenceMatcher
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
)
_settings = {}
_items = []
def power_off_pi():
aiy.audio.say('Good bye!')
subprocess.call('sudo shutdown now', shell=True)
def reboot_pi():
aiy.audio.say('See you in a bit!')
subprocess.call('sudo reboot', shell=True)
def terminate():
aiy.audio.say('See you')
exit(-1)
def runItem(itemId, status):
#aiy.audio.say('ok')
print('runItem ' + itemId + ' with status ' + status)
url = _settings['remoteUrl'] + 'toggle.php';
postData = {'outletId' : itemId, 'outletStatus' : status, 'outletDelayed': '0'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(postData), headers=headers)
def initVariables():
global _settings
settingsFile = open(os.path.join(os.path.dirname(__file__),'settings.json'))
_settings = json.load(settingsFile)
def getDevicesData():
try:
global _items
url = _settings['remoteUrl'] + 'Services.php';
postData = {'service':'CheckItemsData', 'receive' : '1', 'category' : 'general'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(postData), headers=headers)
#print(r.text)
items = json.loads(r.text)
if 'items' not in items:
return
for item in items['items']:
if 'hotword' in item and item['hotword'] is not None:
print('Found configured device ' + item['id'] + ' by hotword ' + item['hotword'])
_items.append(item)
#print(_items)
except requests.exceptions.Timeout:
time.sleep(10)
getDevicesData()
except requests.exceptions.RequestException as e:
print('Error during getDevicesData')
print(str(e))
pass
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
def removeAllTrailing(command, toRemove):
while True:
if command.endswith(toRemove):
command = command[:(-1)*(len(toRemove))]
else:
break
return command
def checkItem(name):
returnObject = None
status = None
for initRecognition in _settings['initRecognitionStatuses']:
if name.endswith(initRecognition['ending']):
status = initRecognition['status']
name = removeAllTrailing(name, initRecognition['ending'])
name = removeAllTrailing(name, ' ')
if status is None:
return None
returnObject = {'maxRatio': 0.0}
for item in _items:
currentRatio = similar(item['hotword'], name)
if currentRatio > returnObject['maxRatio']:
returnObject['maxRatio'] = currentRatio
returnObject['id'] = item['id']
returnObject['hotword'] = item['hotword']
if returnObject['maxRatio'] >= _settings['hotwordRatioThreshold']:
print('Found winner device "' + returnObject['id']+ '" with max score ' + str(returnObject['maxRatio']))
returnObject = {'name':returnObject['id'], 'status':status}
elif 'id' in returnObject and 'hotword' in returnObject and returnObject['maxRatio'] >= 0:
print('Most similar item was "' + returnObject['id'] + '" with hotword "' + returnObject['hotword'] + '" name of "' + name + '" gives score ' + str(returnObject['maxRatio']))
else:
print('No sufficiently similar item found ')
if 'name' in returnObject:
return returnObject
else:
return None
def say_ip():
ip_address = subprocess.check_output("hostname -I | cut -d' ' -f1", shell=True)
aiy.audio.say('My IP address is %s' % ip_address.decode('utf-8'))
def process_event(assistant, event):
print(event)
status_ui = aiy.voicehat.get_status_ui()
if event.type == EventType.ON_START_FINISHED:
status_ui.status('ready')
if sys.stdout.isatty():
print('Say "OK, Google" then speak, or press Ctrl+C to quit...')
elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
status_ui.set_trigger_sound_wave('/home/pi/AIY_stuff/yup_sil.wav')
status_ui.status('listening')
elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and event.args:
print('You said:', event.args['text'])
text = event.args['text'].lower()
if text == 'power off':
assistant.stop_conversation()
power_off_pi()
elif text == 'reboot':
assistant.stop_conversation()
reboot_pi()
elif text == 'ip address':
assistant.stop_conversation()
say_ip()
elif text == 'terminate':
assistant.stop_conversation()
terminate()
else:
checked = checkItem(text)
if checked is not None:
if 'name' in checked:
t = threading.Thread(target=runItem, args=(checked['name'], checked['status']))
t.start()
assistant.stop_conversation()
else:
assistant.stop_conversation()
aiy.audio.play_wave('/home/pi/AIY_stuff/nope_sil.wav')
elif event.type == EventType.ON_END_OF_UTTERANCE:
status_ui.status('thinking')
elif (event.type == EventType.ON_CONVERSATION_TURN_FINISHED
or event.type == EventType.ON_CONVERSATION_TURN_TIMEOUT
or event.type == EventType.ON_NO_RESPONSE):
status_ui.status('ready')
elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and event.args['is_fatal']:
sys.exit(1)
def main():
if platform.machine() == 'armv6l':
print('Cannot run hotword demo on Pi Zero!')
exit(-1)
initVariables()
getDevicesData()
#exit(-1)
credentials = aiy.assistant.auth_helpers.get_assistant_credentials()
with Assistant(credentials) as assistant:
for event in assistant.start():
process_event(assistant, event)
if __name__ == '__main__':
main()