-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.py
274 lines (214 loc) · 8.37 KB
/
helpers.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
import json
import dateutil.parser
import datetime
import time
import os
import math
import random
import logging
from io import StringIO
from html.parser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
""" --- Helpers to build responses which match the structure of the necessary dialog actions --- """
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message, response_card):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'ElicitSlot',
'intentName': intent_name,
'slots': slots,
'slotToElicit': slot_to_elicit,
'message': message,
'responseCard': response_card
}
}
def confirm_intent(session_attributes, intent_name, slots, message, response_card):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'ConfirmIntent',
'intentName': intent_name,
'slots': slots,
'message': message,
'responseCard': response_card
}
}
def close(session_attributes, fulfillment_state, message):
response = {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': message
}
}
return response
def delegate(session_attributes, slots):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Delegate',
'slots': slots
}
}
def build_response_card(title, subtitle, options):
"""
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
"""
buttons = None
if options is not None:
buttons = []
for i in range(min(5, len(options))):
buttons.append(options[i])
return {
'contentType': 'application/vnd.amazonaws.card.generic',
'version': 1,
'genericAttachments': [{
'title': title,
'subTitle': subtitle,
'buttons': buttons
}]
}
""" --- Helper Functions --- """
def parse_int(n):
try:
return int(n)
except ValueError:
return float('nan')
def try_ex(func):
"""
Call passed in function in try block. If KeyError is encountered return None.
This function is intended to be used to safely access dictionary.
Note that this function would have negative impact on performance.
"""
try:
return func()
except KeyError:
return None
def increment_time_by_thirty_mins(appointment_time):
hour, minute = map(int, appointment_time.split(':'))
return '{}:00'.format(hour + 1) if minute == 30 else '{}:30'.format(hour)
def get_random_int(minimum, maximum):
"""
Returns a random integer between min (included) and max (excluded)
"""
min_int = math.ceil(minimum)
max_int = math.floor(maximum)
return random.randint(min_int, max_int - 1)
def get_availabilities(date):
"""
Helper function which in a full implementation would feed into a backend API to provide query schedule availability.
The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format.
In order to enable quick demonstration of all possible conversation paths supported in this example, the function
returns a mixture of fixed and randomized results.
On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at
10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday.
"""
day_of_week = dateutil.parser.parse(date).weekday()
availabilities = []
available_probability = 0.3
if day_of_week == 0:
start_hour = 10
while start_hour <= 16:
if random.random() < available_probability:
# Add an availability window for the given hour, with duration determined by another random number.
appointment_type = get_random_int(1, 4)
if appointment_type == 1:
availabilities.append('{}:00'.format(start_hour))
elif appointment_type == 2:
availabilities.append('{}:30'.format(start_hour))
else:
availabilities.append('{}:00'.format(start_hour))
availabilities.append('{}:30'.format(start_hour))
start_hour += 1
if day_of_week == 2 or day_of_week == 4:
availabilities.append('10:00')
availabilities.append('16:00')
availabilities.append('16:30')
return availabilities
def isvalid_date(date):
try:
dateutil.parser.parse(date)
return True
except ValueError:
return False
def is_available(appointment_time, duration, availabilities):
"""
Helper function to check if the given time and duration fits within a known set of availability windows.
Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM.
"""
if duration == 30:
return appointment_time in availabilities
elif duration == 60:
second_half_hour_time = increment_time_by_thirty_mins(appointment_time)
return appointment_time in availabilities and second_half_hour_time in availabilities
# Invalid duration ; throw error. We should not have reached this branch due to earlier validation.
raise Exception('Was not able to understand duration {}'.format(duration))
def get_duration(appointment_type):
appointment_duration_map = {'chat': 60, 'call': 30}
return try_ex(lambda: appointment_duration_map[appointment_type.lower()])
def get_availabilities_for_duration(duration, availabilities):
"""
Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.
"""
duration_availabilities = []
start_time = '10:00'
while start_time != '17:00':
if start_time in availabilities:
if duration == 30:
duration_availabilities.append(start_time)
elif increment_time_by_thirty_mins(start_time) in availabilities:
duration_availabilities.append(start_time)
start_time = increment_time_by_thirty_mins(start_time)
return duration_availabilities
def build_validation_result(is_valid, violated_slot, message_content):
return {
'isValid': is_valid,
'violatedSlot': violated_slot,
'message': {'contentType': 'PlainText', 'content': message_content}
}
def build_time_output_string(appointment_time):
hour, minute = appointment_time.split(':') # no conversion to int in order to have original string form. for eg) 10:00 instead of 10:0
if int(hour) > 12:
return '{}:{} p.m.'.format((int(hour) - 12), minute)
elif int(hour) == 12:
return '12:{} p.m.'.format(minute)
elif int(hour) == 0:
return '12:{} a.m.'.format(minute)
return '{}:{} a.m.'.format(hour, minute)
def build_available_time_string(availabilities):
"""
Build a string eliciting for a possible time slot among at least two availabilities.
"""
prefix = 'We have availabilities at '
if len(availabilities) > 3:
prefix = 'We have plenty of availability, including '
prefix += build_time_output_string(availabilities[0])
if len(availabilities) == 2:
return '{} and {}'.format(prefix, build_time_output_string(availabilities[1]))
return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))
def build_options(slot, appointment_type, booking_map):
"""
Build a list of potential options for a given slot, to be used in responseCard generation.
"""
if slot == 'AppointmentType':
return [
{'text': 'chat (60 min)', 'value': 'chat'},
{'text': 'call (30 min)', 'value': 'call'}
]