Guest User

Untitled

a guest
Jun 11th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.31 KB | None | 0 0
  1. # -- coding: utf-8 --
  2. """
  3. This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
  4. The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well
  5. as testing instructions are located at http://amzn.to/1LzFrj6
  6.  
  7. For additional samples, visit the Alexa Skills Kit Getting Started guide at
  8. http://amzn.to/1LGWsLG
  9. """
  10.  
  11. from __future__ import print_function
  12. import json
  13. import boto3
  14. import datetime
  15. import random
  16. import decimal
  17. import requests
  18.  
  19. #BUCKET_URL = 'http://35.168.209.123:5000'
  20. BUCKET_URL = 'http://54.175.141.247:5000'
  21.  
  22. REGION = "us-east-1"
  23.  
  24. dynamodb = boto3.resource('dynamodb', REGION)
  25. state_table = dynamodb.Table('StateTable')
  26. user_table = dynamodb.Table('UserTable')
  27. confidence_scores = dynamodb.Table("confidence_scores")
  28. convId_table = dynamodb.Table("convid_event")
  29.  
  30. # Set of utterances that get randomly selected when reprompting the user
  31. utterances=["Are you still there?",
  32.             "Cat got your tongue?",
  33.             "Hello? Anyone there?",
  34.             "Houston, we have a problem! I think I lost communication..."]
  35.  
  36. intro_phrases=["How are you doing?",
  37.                    "How are you feeling today?",
  38.                   "How's it going with you?",
  39.                   "How's it going?",
  40.                   "How are you?"]
  41.  
  42.  
  43. # --------------- Helpers that build all of the responses ----------------------
  44.  
  45. def build_speechlet_response(title, output, reprompt_text, should_end_session):
  46.     return {
  47.         'outputSpeech': {
  48.             'type': 'SSML',#'PlainText',
  49.             'ssml':'<speak>'+ output+ '</speak>'
  50.         },
  51.         'reprompt': {
  52.             'outputSpeech': {
  53.                 'type': 'PlainText',
  54.                 'text':reprompt_text
  55.             }
  56.         },
  57.         'shouldEndSession': should_end_session
  58.     }
  59.  
  60.  
  61. def build_response(session_attributes, speechlet_response):
  62.     return {
  63.         'version': '1.0',
  64.         'sessionAttributes': session_attributes,
  65.         'response': speechlet_response
  66.     }
  67.  
  68.  
  69. # --------------- Functions that control the skill's behavior ------------------
  70.  
  71. def get_welcome_response():
  72.     """ If we wanted to initialize the session to have some attributes we could
  73.    add those here
  74.    """
  75.  
  76.     session_attributes = {}
  77.     card_title = "Welcome"
  78.     speech_output = "Hi, This is a development Alexa Prize socialbot... " + random.choice(intro_phrases)
  79.     reprompt_text = select_random_utterance()
  80.     should_end_session = False
  81.     return build_response(session_attributes, build_speechlet_response(
  82.         card_title, speech_output, reprompt_text, should_end_session))
  83.  
  84.  
  85. def handle_session_end_request():
  86.     card_title = "Session Ended"
  87.     speech_output = ""
  88.     # Setting this to true ends the session and exits the skill.
  89.     should_end_session = True
  90.     return build_response({}, build_speechlet_response(
  91.         card_title, speech_output, None, should_end_session))
  92.  
  93.  
  94. def get_answer(intent, session):
  95.  
  96.     """ Sets the color in the session and prepares the speech to reply to the
  97.    user.
  98.    """
  99. #    card_title = intent['intent']['name']
  100.     card_title = session['sessionId']
  101.     session_attributes = {}
  102.     should_end_session = False
  103.  
  104.     utterance = intent['intent']["slots"]["All"]["value"]
  105.     session_id = session['sessionId']
  106.     timestamp = intent['timestamp']
  107.     user_id = session['user']['userId']
  108.     print("utterance: {}, session_id: {}, timestamp: {}, user_id: {}".format(utterance, session_id, timestamp, user_id))
  109.  
  110.     try:
  111.         confidence_list = [x['confidence'] for x in intent['speechRecognition']['hypotheses'][0]['tokens']]
  112.        # confidence_list = [decimal.Decimal(str(x)) for x in confidence_list]
  113.         print(confidence_list)
  114.     except:
  115.         confidence_list = []
  116.  
  117.  
  118.     # write the user utterance to db
  119.     # update_db(session, timestamp, utterance_no_plus, "user", "1", "0", confidence_list
  120.  
  121.     # print('{}?q={}'.format(BUCKET_URL, utterance + '&sid=' + session['sessionId']))
  122.     data = {
  123.         'session_id': session_id,
  124.         'question': utterance,
  125.         'user_id': user_id,
  126.         'avg_conf_score': sum(confidence_list)/len(confidence_list) if confidence_list else 1.0,
  127.         'conf_score_list': confidence_list,
  128.         'timestamp': timestamp
  129.     }
  130.  
  131.     speech_output = 'blah blah'
  132.     try:
  133.         # speech_output = json.loads(urllib2.urlopen('{}?q={}'.format(BUCKET_URL, utterance + '&sid=' + session['sessionId']), timeout=15).read())
  134.         res = requests.post(BUCKET_URL, json=data)
  135.         speech_output = res.json().get('result')
  136.     except Exception as e:
  137. #        speech_output = 'I am sorry I didn\'t catch that. Could you repeat that please?'
  138.         speech_output = str(e)
  139.     print("speech_output: ", speech_output)
  140.  
  141.     if speech_output == 'STOP_INTENT_REQUESTED':
  142.         return build_response(session_attributes, build_speechlet_response(
  143.             card_title, '', None, True))
  144.  
  145.  
  146.     reprompt_text = select_random_utterance()
  147.  
  148.     # write the system utterance to db
  149.     # update_db(session, timestamp, speech_output[1], "system", str(speech_output[0]), speech_output[2])
  150.  
  151.     # if news were selected (with news_id), save that to mt_newsAPI table
  152.     # if len(speech_output) > 3:
  153.     #     update_news_id(session, speech_output[3])
  154.  
  155.     return build_response(session_attributes, build_speechlet_response(
  156.         card_title, speech_output, reprompt_text, should_end_session))
  157.  
  158.  
  159. def select_random_utterance():
  160.     return random.choice(utterances)
  161.  
  162.  
  163. def log(event):
  164.     try:
  165.         if 'conversationId' in json.dumps(event):
  166.             # log_table.put_item(
  167.             #     Item={
  168.             #         'timestamp': event["request"]["timestamp"],
  169.             #         'event': json.dumps(event)
  170.             #     }
  171.             # )
  172.  
  173.             convId_table.put_item(
  174.                 Item={
  175.                     'conv_id': event["request"]["body"]["conversationId"],
  176.                     'event': json.dumps(event)
  177.                 }
  178.             )
  179.     except:
  180.         pass
  181.  
  182. def log_confidence(event):
  183.     try:
  184.         # print(json.dumps(event))
  185.         confidence_scores.put_item(
  186.                 Item={
  187.                     'sessionID': event["session"]["sessionId"],
  188.                     'utterance': json.dumps(event['request']['intent']["slots"]["All"]["value"]),
  189.                     'event': json.dumps(event)
  190.                 }
  191.             )
  192.     except:
  193.         pass
  194.  
  195. # --------------- Events ------------------
  196.  
  197. def on_session_started(session_started_request, session):
  198.     """ Called when the session starts """
  199.  
  200.     print("on_session_started requestId=" + session_started_request['requestId']
  201.           + ", sessionId=" + session['sessionId'])
  202.  
  203.     # create the session db object
  204.     #start_db_session(session)
  205.     #start_db_ner(session)
  206.  
  207.  
  208. def on_launch(launch_request, session):
  209.     """ Called when the user launches the skill without specifying what they
  210.    want
  211.    """
  212.     print("on_launch requestId=" + launch_request['requestId'] +
  213.           ", sessionId=" + session['sessionId'])
  214.     # Dispatch to your skill's launch
  215.     return get_welcome_response()
  216.  
  217.  
  218. def on_intent(intent_request, session):
  219.     """ Called when the user specifies an intent for this skill """
  220.  
  221.     print("on_intent requestId=" + intent_request['requestId'] +
  222.           ", sessionId=" + session['sessionId'])
  223.  
  224.     #intent = intent_request['intent']
  225.     intent_name = intent_request['intent']['name']
  226.  
  227.     # Dispatch to your skill's intent handlers
  228.     if intent_name == "GetAnswer":
  229.         return get_answer(intent_request, session)
  230.     elif intent_name == "StopIntent":
  231.         return handle_session_end_request()
  232.     else:
  233.         raise ValueError("Invalid intent")
  234.  
  235.  
  236. def on_session_ended(session_ended_request, session):
  237.     """ Called when the user ends the session.
  238.  
  239.    Is not called when the skill returns should_end_session=true
  240.    """
  241.     print("on_session_ended requestId=" + session_ended_request['requestId'] +
  242.           ", sessionId=" + session['sessionId'])
  243.     # add cleanup logic here
  244.  
  245.  
  246. # --------------- Main handler ------------------
  247.  
  248. def lambda_handler(event, context):
  249.     """ Route the incoming request based on type (LaunchRequest, IntentRequest,
  250.    etc.) The JSON body of the request is provided in the event parameter.
  251.    """
  252.     print("event.session.application.applicationId=" +
  253.           event['session']['application']['applicationId'])
  254.     log(event)
  255.     log_confidence(event)
  256.  
  257.     """
  258.    Uncomment this if statement and populate with your skill's application ID to
  259.    prevent someone else from configuring a skill that sends requests to this
  260.    function.
  261.    """
  262.     # if (event['session']['application']['applicationId'] !=
  263.     #         "amzn1.echo-sdk-ams.app.[unique-value-here]"):
  264.     #     raise ValueError("Invalid Application ID")
  265.  
  266.     if event['session']['new']:
  267.         on_session_started({'requestId': event['request']['requestId']},
  268.                            event['session'])
  269.  
  270.     if event['request']['type'] == "LaunchRequest":
  271.         return on_launch(event['request'], event['session'])
  272.     elif event['request']['type'] == "IntentRequest":
  273.         return on_intent(event['request'], event['session'])
  274.     elif event['request']['type'] == "SessionEndedRequest":
  275.         return on_session_ended(event['request'], event['session'])
Add Comment
Please, Sign In to add comment