-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.py
403 lines (332 loc) · 14.7 KB
/
actions.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
# This is a simple example for a custom action which utters "Hello World!"
import string
from collections import defaultdict
import yaml
import unidecode
from datetime import datetime, timedelta
from elasticsearch_dsl import connections, Q
from rasa_sdk import Action, Tracker
from rasa_sdk.events import SlotSet, ReminderScheduled
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.forms import FormAction
from typing import Any, Text, Dict, List, Union, Optional
from stop_words import get_stop_words
from model import Talk
elastic_endpoint = 'localhost'
with open("config.yml", 'r') as stream:
try:
config = yaml.safe_load(stream)
elastic_endpoint = config.get('endpoints')[0].get('elasticsearch')
except yaml.YAMLError as exc:
print(exc)
connections.create_connection(hosts=[elastic_endpoint])
talks_db = {}
stop_words = get_stop_words('es')
def tokenize(text):
input_normalized = unidecode.unidecode(text.lower()).strip(string.punctuation)
tokens = input_normalized.split(' ')
return [token for token in tokens if token not in stop_words]
with open('./data/talks.txt') as fp:
lines = fp.readlines()
for line in lines:
line = line.replace('\n', '')
talks_db[line] = tokenize(line)
def search_talks_database(tokens):
candidates = []
winner = 0
for talk, tokens_candidates in talks_db.items():
intersect = list(set(tokens) & set(tokens_candidates))
intersected = len(intersect)
if intersected > 0:
if intersected > winner:
candidates = [talk]
elif intersected == winner:
candidates.append(talk)
return candidates
class ActionHelloAndScheduleReminder(Action):
def name(self) -> Text:
return "action_hello"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
dispatcher.utter_template('utter_saludo', tracker)
return [ReminderScheduled('action_schedule_reminder', datetime.now() + timedelta(seconds=30),
kill_on_user_message=True)]
class ActionScheduleReminder(Action):
def name(self) -> Text:
return "action_schedule_reminder"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
dispatcher.utter_template('utter_reminder', tracker)
return []
class ActionFindNextTalks(Action):
def name(self) -> Text:
return "action_find_next_talks"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
now = datetime.now()
# now = datetime.strptime("2019-10-06 11:00", '%Y-%m-%d %H:%M')
search = Talk.search()
query = search.sort('start').query('range', start={'gt': now})
if query.count() == 0:
dispatcher.utter_message("Pues ahora mismo no encuentro ninguna")
else:
message = "Las próximas charlas que he encontrado son:\n"
message += range_query_to_message(query)
dispatcher.utter_message(message)
return []
class ActionFindTalksByTime(Action):
def name(self) -> Text:
return "action_find_talks_by_time"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
search = Talk.search()
time_slot = tracker.get_slot('time')
day_slot = tracker.get_slot('day')
if time_slot and day_slot:
if day_slot.lower() == 'hoy' or day_slot.lower() == 'mañana':
weekday = datetime.today().weekday()
if day_slot.lower() == 'mañana':
weekday += 1
if weekday == 5:
day = 'Sabado'
elif weekday == '6':
day = 'Domingo'
else:
dispatcher.utter_message("Solo tengo registradas charlas el Sábado y Domingo\n")
return []
else:
day = unidecode.unidecode(day_slot).lower()
if day != 'sabado' and day != 'domingo':
dispatcher.utter_message("Solo tengo registradas charlas el Sábado y Domingo\n")
return []
if ':' in time_slot:
time_parts = time_slot.split(':')
hour = int(time_parts[0])
minute = int(time_parts[1])
else:
hour = int(time_slot)
minute = 0
if day == 'sabado':
date = datetime(year=2019, month=10, day=5, hour=hour, minute=minute)
else:
date = datetime(year=2019, month=10, day=6, hour=hour, minute=minute)
query = search.sort('start').\
query('term', day=day).\
query('range', start={'gte': date})
if query.count() == 0:
dispatcher.utter_message("No he encontrado ninguna charla el dia {} a las {}\n".format(day, time_slot))
else:
message = "He encontrado las siguientes charlas el dia {} a las {}:\n".format(day, time_slot)
message += range_query_to_message(query)
dispatcher.utter_message(message)
return[SlotSet('time', None), SlotSet('day', None)]
elif time_slot and not day_slot:
dispatcher.utter_message("¿Qué día, Sábado o Domingo?\n")
elif day_slot and not time_slot:
dispatcher.utter_message("¿A qué hora?\n")
else:
dispatcher.utter_message("He entendido que buscas una charla, pero no he encontrado día ni hora\n")
return []
class SpeakerForm(FormAction):
def name(self) -> Text:
"""Unique identifier of the form"""
return "talk_form"
@staticmethod
def required_slots(tracker: Tracker) -> List[Text]:
"""A list of required slots that the form has to fill"""
return ["day", "time"]
def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
"""A dictionary to map required slots to
- an extracted entity
- intent: value pairs
- a whole message
or a list of them, where a first match will be picked"""
return {
"day": self.from_entity("day"),
"time": self.from_entity("time")
}
def submit(
self,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> List[Dict]:
"""Define what the form has to do
after all required slots are filled"""
dispatcher.utter_message("Perfecto! Voy a ver que encuentro\n")
return []
def range_query_to_message(query):
first_talk = query[0].execute()
talks = [first_talk[0]]
results = query[1:].execute()
for talk in results:
if talk.start == first_talk[0].start and talk.day == first_talk[0].day:
talks.append(talk)
else:
break
titles = [t.title + " - " + '/'.join(t.speakers) + " en " + t.place for t in talks]
return '\n'.join(titles)
class ActionFindTalk(Action):
def name(self) -> Text:
return "action_find_talk"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
search = Talk.search()
talk_slot = tracker.get_slot('talk')
if talk_slot:
query = search.sort('start').query('match', title=talk_slot)
if query.count() > 0:
talks = []
for t in query:
talks.append(
t.title + " el " + t.day + " a las " + t.start.strftime('%H:%M') + " en " + t.place)
dispatcher.utter_message("Las charlas que he encontrado son:\n{}".
format('\n'.join(talks)))
else:
dispatcher.utter_message("No he encontrado ninguna charla sobre ese tema. ¿Puedes reformular la pregunta?")
return [SlotSet('talk', None)]
speaker = tracker.get_slot('speaker')
if speaker:
query = search.sort('start').query('match', speakers=speaker)
if query.count() > 0:
# TODO Replace this ugly code by an Elastic Aggregation. Make speakers field a keyword as well
talksBySpeaker = defaultdict(list)
for t in query:
t.speakers.sort()
for s in t.speakers:
if speaker.lower() in s.lower():
talksBySpeaker[s].append(t)
if len(talksBySpeaker) == 1:
talks = []
for t in list(talksBySpeaker.values())[0]:
talks.append(
t.title + " el " + t.day + " a las " + t.start.strftime('%H:%M') + " en " + t.place)
dispatcher.utter_message("Las charlas que he encontrado de {} son:\n{}".
format(speaker, '\n'.join(talks)))
else:
found_speakers = talksBySpeaker.keys()
message = "¿A qué '{}' te refieres?. He encontrado {}:\n{}".\
format(speaker, len(talksBySpeaker), '\n'.join(found_speakers))
dispatcher.utter_message(message)
return[SlotSet("found_speakers", list(found_speakers))]
else:
query = search.sort('start').query('match', title=speaker)
if query.count() == 0:
dispatcher.utter_message("No he encontrado ninguna charla de {}".format(speaker))
else:
talks = []
for t in query:
talks.append(
t.title + " el " + t.day + " a las " + t.start.strftime('%H:%M') + " en " + t.place)
dispatcher.utter_message("Las charlas que he encontrado de {} son:\n{}".
format(speaker, '\n'.join(talks)))
return[SlotSet("speaker", None)]
else:
tokens = tokenize(tracker.latest_message.get('text'))
candidates = search_talks_database(tokens)
if len(candidates) > 0:
shoulds = []
for candidate in candidates:
shoulds.append(Q('match_phrase', title=candidate))
q = Q('bool', should=shoulds)
query = search.sort('start').query(q)
if query.count() == 0:
dispatcher.utter_message("No he podido encontrar ninguna charla, lo siento".format(speaker))
else:
talks = []
for t in query:
talks.append(
t.title + " el " + t.day + " a las " + t.start.strftime('%H:%M') + " en " + t.place)
dispatcher.utter_message("Las posibles charlas relevantes que he encontrado son:\n{}".
format('\n'.join(talks)))
else:
dispatcher.utter_message("No he encontrado ninguna charla. ¿Puedes reformular la pregunta?")
return []
class SpeakerForm(FormAction):
def name(self) -> Text:
"""Unique identifier of the form"""
return "speaker_form"
@staticmethod
def ordinal_db() -> Dict[Text, int]:
"""Database of supported cuisines"""
return {
"el primero": 0,
"el segundo": 1,
"el tercero": 2,
"el cuarto": 3,
"el quinto": 4,
"el sexto": 5,
}
@staticmethod
def required_slots(tracker: Tracker) -> List[Text]:
"""A list of required slots that the form has to fill"""
return ["confirmed_speaker"]
def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
"""A dictionary to map required slots to
- an extracted entity
- intent: value pairs
- a whole message
or a list of them, where a first match will be picked"""
return {
"confirmed_speaker": self.from_text()
}
def validate_confirmed_speaker(
self,
value: Text,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> Optional[Text]:
"""Validate cuisine value."""
found_speakers = tracker.get_slot('found_speakers')
if not found_speakers:
self.deactivate()
return {"confirmed_speaker": None}
matches = []
if value.lower() in self.ordinal_db():
index = self.ordinal_db().get(value.lower())
if index < len(found_speakers):
matches.append(found_speakers[index])
else:
for speaker in found_speakers:
if unidecode.unidecode(value).lower() in unidecode.unidecode(speaker).lower():
matches.append(speaker)
if len(matches) == 0:
dispatcher.utter_message("No me suena {}. Prueba otra vez".format(value))
return {"confirmed_speaker": None}
elif len(matches) == 1:
return {"confirmed_speaker": matches[0]}
else:
dispatcher.utter_message("{} pueden ser:\n {}\n. ¿Puedes ser más preciso amigo?".
format(value, '\n'.join(matches)))
return {"confirmed_speaker": None}
def submit(
self,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> List[Dict]:
"""Define what the form has to do
after all required slots are filled"""
# utter submit template
speaker = tracker.get_slot('confirmed_speaker')
search = Talk.search()
query = search.sort('start').query('match_phrase', speakers=speaker)
talks = []
for t in query:
talks.append(
t.title + " el " + t.day + " a las " + t.start.strftime('%H:%M') + " en " + t.place)
dispatcher.utter_message("Las charlas que he encontrado de {} son:\n{}".
format(speaker, '\n'.join(talks)))
self.deactivate()
return [SlotSet("confirmed_speaker", None), SlotSet("found_speakers", None), SlotSet('speaker', None)]