-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlambda_function.py
More file actions
476 lines (396 loc) · 17.7 KB
/
Copy pathlambda_function.py
File metadata and controls
476 lines (396 loc) · 17.7 KB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# -*- coding: utf-8 -*-
# This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python.
# Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management,
# session persistence, api calls, and more.
# This sample is built using the handler classes approach in skill builder.
import logging
import ask_sdk_core.utils as ask_utils
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.handler_input import HandlerInput
#from lambda_session import get_session_data
from ask_sdk_model import Response
from services import order_list_manager as olm
from services import order_item_manager as oim
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
import csv
import pandas as pd
import re
import os
from services import sa
from services import tsp
import boto3
archivo_csv = 'data/products.csv'
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class LaunchRequestHandler(AbstractRequestHandler):
"""Handler for Skill Launch."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Buenas tardes, empieza la jornada laboral. ¿En qué puedo ayudarte?"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class HelpIntentHandler(AbstractRequestHandler):
"""Handler for Help Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "You can say hello to me! How can I help?"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class CancelOrStopIntentHandler(AbstractRequestHandler):
"""Single handler for Cancel and Stop Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or
ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input))
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Goodbye!"
return (
handler_input.response_builder
.speak(speak_output)
.response
)
class FallbackIntentHandler(AbstractRequestHandler):
"""Single handler for Fallback Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("AMAZON.FallbackIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In FallbackIntentHandler")
speech = "Hmm, I'm not sure. You can say Hello or Help. What would you like to do?"
reprompt = "I didn't catch that. What can I help you with?"
return handler_input.response_builder.speak(speech).ask(reprompt).response
class SessionEndedRequestHandler(AbstractRequestHandler):
"""Handler for Session End."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("SessionEndedRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
# Any cleanup logic goes here.
return handler_input.response_builder.response
class IntentReflectorHandler(AbstractRequestHandler):
"""The intent reflector is used for interaction model testing and debugging.
It will simply repeat the intent the user said. You can create custom handlers
for your intents by defining them above, then also adding them to the request
handler chain below.
"""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("IntentRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
intent_name = ask_utils.get_intent_name(handler_input)
speak_output = "You just triggered " + intent_name + "."
return (
handler_input.response_builder
.speak(speak_output)
# .ask("add a reprompt if you want to keep the session open for the user to respond")
.response
)
class CatchAllExceptionHandler(AbstractExceptionHandler):
"""Generic error handling to capture any syntax or routing errors. If you receive an error
stating the request handler chain is not found, you have not implemented a handler for
the intent being invoked or included it in the skill builder below.
"""
def can_handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> bool
return True
def handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> Response
logger.error(exception, exc_info=True)
speak_output = "Sorry, I had trouble doing what you asked. Please try again."
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class KarakuloHandler(AbstractRequestHandler):
"""Handler for agregar item {nombre} Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("Karakulo")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
slots = handler_input.request_envelope.request.intent.slots
contenido_slot = slots.get('contenido')
if contenido_slot and contenido_slot.value:
best_match = find_medication(contenido_slot.value)
handler_input.attributes_manager.session_attributes['contenido'] = best_match
speak_output = f"Orden creada: {handler_input.attributes_manager.session_attributes['contenido']}"
else:
speak_output = "No se encontró el valor de 'contenido'"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class MakakinoHandler(AbstractRequestHandler):
"""Handler for lugar {prod_nombre} Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("Makakino")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
try:
slots = handler_input.request_envelope.request.intent.slots
nombre_slot = slots.get('nombre')
if nombre_slot and nombre_slot.value:
best_match = find_medication(nombre_slot.value)
df = pd.read_csv("data/products1.csv", delimiter=';')
var = df[df["name"] == best_match]["localizacion"]
localizacion = var.values
speak_output = f"La localización de {best_match} es {localizacion}"
else:
speak_output = "No se encontró el producto"
except Exception as e:
speak_output = f"{e}"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class KrisafelHandler(AbstractRequestHandler):
"""Handler for importar lista {nombre} Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("Krisafel")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
try:
slots = handler_input.request_envelope.request.intent.slots
nombre_slot = slots.get('nombre')
if nombre_slot and nombre_slot.value:
list_manager = olm.OrderListManager()
splitted_contenido = nombre_slot.value.split(" ")
join_file_path = "_".join(splitted_contenido)
list_manager.load_order_list(join_file_path)
speak_output = f"Lista {join_file_path} cargada!"
except Exception as e:
speak_output = f"{e}"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class KruchucHandler(AbstractRequestHandler):
"""Handler for guardar lista {nombre} Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("Kruchuc")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
try:
slots = handler_input.request_envelope.request.intent.slots
nombre_slot = slots.get('nombre')
if nombre_slot and nombre_slot.value:
list_manager = olm.OrderListManager()
splitted_contenido = nombre_slot.value.split(" ")
join_file_path = "_".join(splitted_contenido)
list_manager.save_order_list(join_file_path)
speak_output = f"Lista {join_file_path} guardada!"
except Exception as e:
speak_output = f"{e}"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class KaraQttHandler(AbstractRequestHandler):
"""Handler for cantidad {numero} Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
#return handler_input.attributes_manager.session_attributes.get('contenido') is not None
return ask_utils.is_intent_name("KaraQtt")(handler_input)
def handle(self, handler_input):
try:
contenido = handler_input.attributes_manager.session_attributes['contenido']
slots = handler_input.request_envelope.request.intent.slots
cantidad = slots.get('cantidad').value
df = pd.read_csv("data/products.csv", delimiter=';')
var = df[df["name"] == contenido]
var1 = var.values[0].tolist()
var1.append(cantidad)
item_manager = oim.OrderItemManager()
item_manager.add_item(str(var1[0]), str(var1[1]), str(var1[2]), str(var1[3]))
# speak_output = f"Orden creada con éxito: con {cantidad} unidades"
speak_output = f"Orden creada: {cantidad} unidades de {contenido}"
except Exception as e:
speak_output = f"{e}"
# Implementar la lógica para guardar la orden en S3
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class KrakrikraHandler(AbstractRequestHandler):
"""Handler for Crear Lista Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
#return handler_input.attributes_manager.session_attributes.get('contenido') is not None
return ask_utils.is_intent_name("Krakrikra")(handler_input)
def handle(self, handler_input):
list_manager = olm.OrderListManager()
list_manager.create_order_list()
speak_output = "Lista creada con exito!"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class KaraBlaBlaHandler(AbstractRequestHandler):
"""Handler for TEST Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
#return handler_input.attributes_manager.session_attributes.get('contenido') is not None
return ask_utils.is_intent_name("KaraBlaBla")(handler_input)
def handle(self, handler_input):
list_manager = olm.OrderListManager()
item_manager = oim.OrderItemManager()
list_manager.create_order_list()
item_manager.add_item("hola","CALIERCORTIN 4mg/ml- 50ml iny", "adios", "10")
item_manager.add_item("hola","CRCORTIN 4mg/ml- 50ml iny", "adios", "10")
item_manager.add_item("hola","CALIERTIN 4mg/ml- 50ml iny", "adios", "10")
item_manager.add_item("hola","CALIERCfdsafsdjofadsoORTIN 4mg/ml- 50ml iny", "adios", "10")
item_manager.add_item("adios","ADTAB GATO 12mg 0,5-2kg 1cp", "adios", "15")
#df = pd.read_csv("data/products.csv", delimiter=';')
#contenido = "CALIERCORTIN 4mg/ml- 50ml iny"
#var = df[df["name"] == contenido]
#var1 = var.values[0].tolist()
#var1.append("5")
#item_manager.add_item(str(var1[0]), str(var1[1]), str(var1[2]), str(var1[3]))
#contenido = "ADTAB GATO 12mg 0,5-2kg 1cp"
#var = df[df["name"] == contenido]
#var1 = var.values[0].tolist()
#var1.append("8")
#item_manager.add_item(str(var1[0]), str(var1[1]), str(var1[2]), str(var1[3]))
#speak_output = f"{var1}"
speak_output = "hola"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class KaraPlinHandler(AbstractRequestHandler):
"""Handler for Eliminar Item Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("KaraPlin")(handler_input)
def handle(self, handler_input):
try:
slots = handler_input.request_envelope.request.intent.slots
contenido_slot = slots.get('contenido')
#speak_output = f"{contenido_slot}"
if contenido_slot and contenido_slot.value:
best_match = find_medication(contenido_slot.value)
item_manager = oim.OrderItemManager()
item_manager.delete_item(best_match)
speak_output = f"Item {best_match} eliminado"
else:
speak_output = "No se encontró el valor de 'contenido'"
except Exception as e:
speak_output = f"{e}"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class JaramikoHandler(AbstractRequestHandler):
"""Handler for "Dame la ruta de la lista {nombre}" Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("Jaramiko")(handler_input)
def handle(self, handler_input):
s3 = boto3.client("s3")
download_file_path = "/tmp/data.csv"
bucket_name = "f35e4180-5bc7-4810-9403-95ab49618c83-eu-west-1"
object_key = "data.csv"
speak_output = ""
try:
s3.download_file(bucket_name, object_key, download_file_path)
nombres = []
df = pd.read_csv(download_file_path)
if len(df) < 16:
nombres = tsp.obtener_nombres_camino(download_file_path)
else:
nombres = sa.obtener_nombres_camino(download_file_path)
for nom in nombres:
speak_output += nom
except Exception as e:
speak_output = f"{e}"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
medications = []
with open(archivo_csv, newline='', encoding='utf-8') as csvfile:
# Leer el archivo CSV
lector_csv = csv.reader(csvfile, delimiter=';')
# Iterar sobre cada fila del archivo
for fila in lector_csv:
# Agregar el elemento de la segunda columna a la lista
medications.append(fila[1])
# Eliminar el encabezado
medications = medications[1:]
#print("Medications:", medications)
def find_medication(input_text):
max_similarity = 0
best_match = None
print("Input text:", input_text)
for medication in medications:
similarity = fuzz.ratio(input_text, medication.lower())
if similarity > max_similarity:
print("Similarity:", similarity, "Medication:", medication)
max_similarity = similarity
best_match = medication
return best_match
# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.
sb = SkillBuilder()
sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(KarakuloHandler())
sb.add_request_handler(KaraQttHandler())
sb.add_request_handler(KrakrikraHandler())
sb.add_request_handler(KaraBlaBlaHandler())
sb.add_request_handler(KaraPlinHandler())
sb.add_request_handler(JaramikoHandler())
sb.add_request_handler(KrisafelHandler())
sb.add_request_handler(KruchucHandler())
sb.add_request_handler(MakakinoHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(FallbackIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
sb.add_exception_handler(CatchAllExceptionHandler())
lambda_handler = sb.lambda_handler()