This repository has been archived by the owner on Feb 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
obsolete.py
executable file
·270 lines (235 loc) · 9.99 KB
/
obsolete.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
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
#!/usr/bin/env python3
"""Snips skill action.
Subscribes to franc:addToList and franc:checkList intents and processes them.
"""
import configparser
import gettext
from io import open
import json
import locale
import re
from subprocess import Popen, PIPE, STDOUT
import sys
from threading import Timer, Lock
from hermes_python.hermes import Hermes
from hermes_python.ontology import *
import our_groceries_client
# Set up locale
locale.setlocale(locale.LC_ALL, '')
# Set gettext to be the right thing for python2 and python3
if sys.version_info[0] < 3:
gettext = gettext.translation('messages', localedir='locales').ugettext
else:
gettext.bindtextdomain('messages', 'locales')
gettext = gettext.gettext
CONFIG_INI = 'config.ini'
CONFIG_ENCODING = 'utf-8'
__all__ = []
class RepeatTimer(object):
"""Class to repeatedly run a given function via a timer"""
def __init__(self, interval, function, *args, **kwargs):
"""Initialize the object
interval: Time between running, in seconds
function: A function to call when the timer goes off
args, kwargs: The arguments to pass to function
"""
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
def _run(self):
"""_run is called when the timer goes off, and invokes self.function"""
self.is_running = False
self.function(*self.args, **self.kwargs)
self.start() # Start the timer again!
def start(self):
"""Checks that the timer isn't running, and if not, creates a timer,
and starts it"""
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
"""Kills the timer"""
if self.is_running:
if self._timer is not None:
self._timer.cancel()
self.is_running = False
class SnipsConfigParser(configparser.ConfigParser):
"""Subclass configparser.ConfigParser to add to_dict method."""
def to_dict(self):
"""Returns a dictionary of sections and options from the config file"""
return {section: {option_name : option for option_name,
option in self.items(section)} for section in self.sections()}
def read_configuration_file(file_name):
"""Reads and parses CONFIG_INI. Returns a dictionary based on its contents"""
try:
with open(file_name, encoding=CONFIG_ENCODING) as file:
config_parser = SnipsConfigParser()
config_parser.readfp(file)
return config_parser.to_dict()
except (IOError, configparser.Error):
return dict()
def get_items_payload(client, list_names):
"""Gets all items from the given lists, and formats them for injection"""
item_names = []
for list_name in list_names:
items = client._get_list_data(list_name)
for item in items:
item_names.append(item['value'])
item_names = list(set(item_names))
return ['addFromVanilla', {'our_groceries_item_name': item_names}]
def get_lists_payload(list_names):
"""Formats the given list names as needed for injection"""
return ['addFromVanilla', {'our_groceries_list_name': list_names}]
def get_update_payload(hermes):
"""Retrives list names and items names, formatting them for injection"""
operations = []
client = our_groceries_client.OurGroceriesClient()
client.authenticate(hermes.skill_config['secret']['username'],
hermes.skill_config['secret']['password'],
hermes.skill_config['secret']['defaultlist'])
list_names = []
for list_info in client._lists:
list_names.append(list_info['name'])
operations.append(get_lists_payload(list_names))
operations.append(get_items_payload(client, list_names))
payload = {'operations': operations}
return json.dumps(payload)
def add_to_list(hermes, intent_message):
"""Adds the given item and quantity to the given list"""
if hermes.injection_lock:
sentence = gettext("STR_UPDATING_WAIT_ADD")
hermes.publish_end_session(intent_message.session_id, sentence)
return
quantity = 1
what = None
which_list = None
if intent_message.slots is not None:
try:
what = intent_message.slots.what[0].raw_value
except (TypeError, LookupError, ValueError):
pass
try:
which_list = intent_message.slots.list[0].slot_value.value.value
except (TypeError, LookupError, ValueError):
pass
try:
quantity = int(float(intent_message.slots.quantity[0].slot_value.value.value))
except (TypeError, LookupError, ValueError):
pass
# Set whichList to defaultlist if it's None or matches
# gettext("STR_DEFAULT_LIST") The API would use the same list if we
# passed None, but the code below would fail when giving the
# response.
if (which_list is None) or \
(which_list.casefold() == gettext("STR_DEFAULT_LIST").casefold()):
which_list = hermes.skill_config['secret']['defaultlist']
if what is None:
sentence = gettext("STR_ADD_MISSING_WHAT").format(l=which_list)
hermes.publish_end_session(intent_message.session_id, sentence)
return
client = our_groceries_client.OurGroceriesClient()
client.authenticate(hermes.skill_config['secret']['username'],
hermes.skill_config['secret']['password'],
hermes.skill_config['secret']['defaultlist'])
client.add_to_list(what, quantity, which_list)
# Respond that we added it to the list
sentence = gettext("STR_ADD_SUCCESS_DETAILS") \
.format(q=quantity, w=what, l=which_list)
hermes.publish_end_session(intent_message.session_id, sentence)
def check_list(hermes, intent_message):
"""Checks the given list for an item and speaks if it's there"""
if hermes.injection_lock:
sentence = gettext("STR_UPDATING_WAIT_ADD")
hermes.publish_end_session(intent_message.session_id, sentence)
return
quantity = '1'
what = None
which_list = None
sentence = None
if intent_message.slots is not None:
try:
what = intent_message.slots.what[0].raw_value
except (TypeError, LookupError, ValueError):
pass
try:
which_list = intent_message.slots.list[0].slot_value.value.value
except (TypeError, LookupError, ValueError):
pass
# Set whichList to defaultlist if it's None or matches
# gettext("STR_DEFAULT_LIST") The API would use the same list if we
# passed None, but the code below would fail when giving the
# response.
if (which_list is None) or \
(which_list.casefold() == gettext("STR_DEFAULT_LIST").casefold()):
which_list = hermes.skill_config['secret']['defaultlist']
if what is None:
sentence = gettext("STR_CHECK_MISSING_WHAT").format(l=which_list)
hermes.publish_end_session(intent_message.session_id, sentence)
return
client = our_groceries_client.OurGroceriesClient()
client.authenticate(hermes.skill_config['secret']['username'],
hermes.skill_config['secret']['password'],
hermes.skill_config['secret']['defaultlist'])
items = client._get_list_data(which_list)
for item in items:
crossed_off = item.get('crossedOff', False)
# Note our two primary regular expressions are commented out
# below and combined into regex. The uncommented regex line
# below this is just building the expression all at once.
#regex1 = r"^" + re.escape(what) + r" *$"
#regex2 = r"^" + re.escape(what) + r"\ \((\d+)\)$"
#regex = r"(" + regex1 + r")|(" + regex2 + r")"
regex = r'(^' + re.escape(what) + r' *$)|(^' + re.escape(what) + r'\ \((\d+)\)$)'
res = re.search(regex, item['value'], re.IGNORECASE)
# Note the following two conditions are not combined because we
# want to break the loop even if the item is crossed off. If
# it's crossed off, we don't need to keep looking for a match --
# you can't have the same item on the list with different case.
# Perhaps with different spelling, but we're not doing sounds
# like checking here. :(
if res is not None:
if not crossed_off:
quantity = res.group(3)
if quantity is None:
quantity = '1'
sentence = gettext("STR_CHECK_SUCCESS_DETAILS") \
.format(q=quantity, w=what, l=which_list)
break
if sentence is None:
sentence = gettext("STR_CHECK_NOT_FOUND").format(w=what, l=which_list)
# Respond that we added it to the list
hermes.publish_end_session(intent_message.session_id, sentence)
def inject_lists_and_items(hermes):
""" Injects the lists and items"""
hermes.injection_lock = True
payload = get_update_payload(hermes) + '\n'
pipe = Popen(['/usr/bin/mosquitto_pub',
'-t',
'hermes/injection/perform',
'-l'
],
stdin=PIPE,
stdout=PIPE,
stderr=STDOUT)
pipe.communicate(input=payload.encode('utf-8'))
hermes.injection_lock = False
def main(hermes):
"""main function"""
hermes.skill_config = read_configuration_file(CONFIG_INI)
hermes.injection_lock = False
inject_lists_and_items(hermes)
#injection_timer = RepeatTimer(3600, inject_lists_and_items, hermes)
#injection_timer.start()
hermes.subscribe_intent('franc:addToList', add_to_list) \
.subscribe_intent('franc:checkList', check_list) \
.loop_forever()
# Note this isn't really necessary, but just in case loop_forever()
# doesn't, we should kill the timer.
#injection_timer.stop()
if __name__ == '__main__':
with Hermes('localhost:1883') as h:
main(h)