-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlex_boto3.py
400 lines (264 loc) · 11 KB
/
lex_boto3.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
# Build, deploy, and manage bots using boto3
# Collect the following info
# Your bot ID
# Your alias ID
# Your locale ID (language code)
# -----------------------------------------------------------------------------------------------------------------------
# Runtime API
# -----------------------------------------------------------------------------------------------------------------------
import uuid
# str(uuid.uuid4())
# uuid.uuid4().hex
# Just creating unique ID number for session ID, pretty sure it can be anything but used this anyway
# LocaleId here: https://docs.aws.amazon.com/lex/latest/dg/how-it-works-language.html
# Setup
botId = 'MYCSXHKEKY'
botAliasId = 'GVOI7JIYSF'
localeId = 'en_GB'
sessionId = uuid.uuid4().hex
from AWS_keys import *
import boto3
# LexV2 client uses 'lexv2-runtime'
client = boto3.client('lexv2-runtime', region_name='eu-west-2',
aws_access_key_id=AWS_KEY_ID,
aws_secret_access_key=AWS_SECRET)
print(client)
# https://aws.amazon.com/blogs/machine-learning/interact-with-an-amazon-lex2v2-bot-with-the-aws-cli-aws-sdk-for-python-and-aws-sdk-dotnet/
# Interacting with your bot
# Submit text
response = client.recognize_text(
botId=botId,
botAliasId=botAliasId,
localeId=localeId,
sessionId=sessionId,
text='I need help with Python')
import json
print(json.dumps(response, indent=4, sort_keys=True))
# -----------------------------------------------------------------------------------------------------------------------
# Resources:
# https://aws.amazon.com/blogs/machine-learning/interact-with-an-amazon-lex2v2-bot-with-the-aws-cli-aws-sdk-for-python-and-aws-sdk-dotnet/
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lexv2-runtime.html
# -----------------------------------------------------------------------------------------------------------------------
# Model Building Service API
# -----------------------------------------------------------------------------------------------------------------------
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lexv2-models.html
# -----------------------------------------------------------------------------------------------------------------------
# Firstly create the bot
# -----------------------------------------------------------------------------------------------------------------------
# Only need to create the bot once
client = boto3.client('lexv2-models', region_name='eu-west-2',
aws_access_key_id=AWS_KEY_ID,
aws_secret_access_key=AWS_SECRET)
created_bot_response = client.create_bot(
botName='programmatic_alex',
description='new starter bot',
roleArn='arn:aws:iam::240624597515:role/aws-service-role/lexv2.amazonaws.com/AWSServiceRoleForLexV2Bots_RUVXLDJJZK',
dataPrivacy={
'childDirected': False
},
idleSessionTTLInSeconds=300 # seconds so 5 mins
)
# Amazon Resource Names (ARNs) uniquely identify AWS resources
# https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
# ARN you can construct manually but I just got it from webinterface by clicking around!
print(response)
# -----------------------------------------------------------------------------------------------------------------------
# Create a bot Locale
# -----------------------------------------------------------------------------------------------------------------------
# botid of the new bot : KA6ARFQ5CT
# Only need to create a Bot locale once
response = client.create_bot_locale(
# botId=created_bot_response['botId'],
botId='KA6ARFQ5CT',
botVersion='DRAFT',
localeId='en_GB',
description='Bot locale',
nluIntentConfidenceThreshold=0.8
)
print(response)
# -----------------------------------------------------------------------------------------------------------------------
# Create intent
# The brackets in this are quite frankly a headache - can use a json editor but doesnt massively help tbh
# Shows example of adding one an intent, below is a function that adds multiple at once
response = client.create_intent(
intentName='PYTHON_SETUP',
description='Helps users find out how to setup Python',
sampleUtterances=[
{
'utterance': 'I cant setup PyCharm'
},
{
'utterance': 'I cant setup Python'
},
{
'utterance': 'where can I get help setting up Python'
},
{
'utterance': 'where can I get help using Python'
},
],
dialogCodeHook={
'enabled': False
},
fulfillmentCodeHook={
'enabled': False,
'postFulfillmentStatusSpecification': {
'successResponse': {
'messageGroups': [
{
'message': {
'plainTextMessage': {
'value': 'DACT have Sharepoint pages to offer help and advice'
}
}
}
]
}
}
},
#botId=created_bot_response['botId'],
botId='KA6ARFQ5CT',
botVersion='DRAFT',
localeId='en_GB',
)
print(response)
# -----------------------------------------------------------------------------------------------------------------------
# Write a function that can add a load of intents at once, add functionality to skip ones that are already on there but add new ones
# this is what we want to update each time
import pandas as pd
# Data needs to be in long format
df = pd.read_csv("intents_long.csv")
# Here is a function that could work for it
# Can put this in a functions library and use as a wrapper to make it more user friendly, also user interface
def create_intent_jen(intentname,
desc,
utterances,
fulfillment):
response = client.create_intent(
intentName=intentname,
description=desc,
sampleUtterances=utterances,
dialogCodeHook={
'enabled': False
},
fulfillmentCodeHook={
'enabled': False,
'postFulfillmentStatusSpecification': {
'successResponse': {
'messageGroups': [
{
'message': {
'plainTextMessage': {
'value': fulfillment
}
}
}
]
}
}
},
#botId=created_bot_response['botId'],
botId='KA6ARFQ5CT',
botVersion='DRAFT',
localeId='en_GB'
)
return response
# -----------------------------------------------------------------------------------------------------------------------
# Adding Intents and utterances from the dataset
for i in df['intentname'].unique():
# Get the data in the right format for the create_intent function which is fussy
utterances = df[df['intentname'] == i]['utterances'].tolist()
utterance_list = []
for j in utterances:
thisdict = {"utterance": j}
utterance_list.append(thisdict)
intentname = df[df['intentname'] == i]['intentname'].reset_index(drop=True)[0]
desc = df[df['intentname'] == i]['desc'].reset_index(drop=True)[0]
fulfillment = df[df['intentname'] == i]['fulfillment'].reset_index(drop=True)[0]
response = create_intent_jen(intentname=intentname,
desc=desc,
utterances=utterance_list,
fulfillment=fulfillment)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
print("Intent creation failed :(\n", response)
break
# -----------------------------------------------------------------------------------------------------------------------
# Check it has done it
# Describe the Lex Bot
client.describe_bot(
botId='KA6ARFQ5CT'
)
# -----------------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------------
# Alternative method (have not finished)
import json
with open('LexIntent_Template.json') as f:
LexIntent_Template = f.read()
with open('bot.json') as f:
LexBot_Template = f.read()
with open("LexIntent_Template.json") as fh1:
data = json.load(fh1)
data_int = data['resource']
fh1.close()
# You can use start_import to import a bot from a zip that you uploaded to S3 bucket and use a mergeStrategy which can append onto an existing boy
# i.e. updating it
filename = "LexbotImport.zip"
with open(filename, 'rb') as binary_file:
binary_file_data = binary_file.read()
response = client.start_import(
payload=binary_file_data ,
resourceType='BOT' ,
mergeStrategy='Append'
)
# -----------------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------------
# Not necessarily needed including for completeness
# Create a version? Just using DRAFT for now
# You can get the botID out of the previous response
response = client.create_bot_version(
botId=created_bot_response['botId'],
description='trying out version',
botVersionLocaleSpecification={
'DRAFT': {
'sourceBotVersion': 'version 1'
}
}
)
print(response['botId'])
# -----------------------------------------------------------------------------------------------------------------------
# Create an alias
# Resources
# https://towardsaws.com/getting-started-with-aws-lex-using-a-datafile-and-aws-python-sdk-64517fd751b7
# -----------------------------------------------------------------------------------------------------------------------
# End
# Working
utterances = df[df['intentname'] == "Agile"]['utterances'].tolist()
utterance_list = []
for j in utterances:
thisdict = {"utterance": j}
utterance_list.append(thisdict)
# Adding Intents and utterances from the dataset
# Attempt for wide format data
for idx, row in df.iterrows():
response = create_intent(intentname=row['intentname'],
desc=row['description'],
utterances=row['utterances'],
fulfillment=row['fulfillment'])
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
print("Creating the intents failed :(!\n", response)
break
df['intentname'].unique()
utterances = df[df['intentname'] == 'Agile']['utterances'].values.tolist()
print(utterances)
for key in utterances:
utterances['utterance'] = utterances.pop(key)
dictionary to string
the str.replace()
hello = '0:'
import re
utterances = str(df[df['intentname'] == 'Agile']['utterances'].to_dict())
new = re.sub(
"[0-9]\:",
"utterance",
utterances
)