Пример #1
0
def main():
    serializer = DefaultSerializer()
    request_envelope = serializer.deserialize(request.data, RequestEnvelope)
    response_envelope = SKILL.invoke(request_envelope=request_envelope,
                                     context=None)

    return jsonify(serializer.serialize(response_envelope))
Пример #2
0
def response_from_dict(response_dict) -> ResponseEnvelope:
    """
    Deserialize a response dictionary to a Response object
    Args:
        response_dict(dict): The response dictionary
    Returns: The deserialized response
    """
    serializer = DefaultSerializer()
    response_json = json.dumps(serializer.serialize(response_dict))
    return serializer.deserialize(response_json, ResponseEnvelope)
Пример #3
0
def operator_intent_handler(handler_input: HandlerInput):
    op = get_slot_value(handler_input, "operand")
    stack = DZ.deserialize(
        handler_input.attributes_manager.session_attributes["stack"],
        'list[float]')
    handler_input.attributes_manager.session_attributes[
        "stack"] = DZ.serialize([despatch[op](stack)])

    text = f"Operator intent, {op}"
    handler_input.response_builder.speak(text).set_card(
        SimpleCard("Calculator", text)).set_should_end_session(False)
    return handler_input.response_builder.response
Пример #4
0
def send_request(endpoint_url: str,
                 request_envelope: RequestEnvelope) -> ResponseEnvelope:
    """Sends a request to the endpoint and returns the response."""
    serializer = DefaultSerializer()
    r = requests.post(
        endpoint_url,
        json=serializer.serialize(request_envelope),
    )
    response_envelope = serializer.deserialize(payload=r.text,
                                               obj_type=ResponseEnvelope)

    return response_envelope
Пример #5
0
def operand_intent_handler(handler_input: HandlerInput):
    val = float(get_slot_value(handler_input, "operand"))
    stack = []
    try:
        stack = DZ.deserialize(
            handler_input.attributes_manager.session_attributes['stack'],
            'List[float]')
    except:
        pass
    stack.append(val)
    handler_input.attributes_manager.session_attributes[
        'stack'] = DZ.serialize(stack)
    text = f"Operand intent, {val}"

    handler_input.response_builder.speak(text).set_card(
        SimpleCard("Calculator", text)).set_should_end_session(False)
    return handler_input.response_builder.response
    def handle(self, handler_input):
        obj_serializer = DefaultSerializer()
        current_intent = handler_input.request_envelope.request.intent

        reprompt = "what is the stop name you looking for?"
        speech = "Can you provide me the stop name you are looking for?"

        # Receive the slot that was stored when the user uttered the bus number
        bus_number = get_slot_value(slot_name=SLOT_ROUTE_NUMBER,
                                    handler_input=handler_input)
        current_intent.confirmation_status = IntentConfirmationStatus.NONE

        route = validate_route(
            bus_number)  # Says if the route is a vlid route of UMD or not
        if route:
            handler_input.attributes_manager.session_attributes[
                R.DEFAULT_ROUTE] = obj_serializer.serialize({
                    R.ROUTE_TITLE:
                    route.route_title,
                    R.ROUTE_TAG:
                    route.route_tag
                })

            # Confirm the route just for the workflow
            current_intent.slots[
                SLOT_ROUTE_NUMBER].confirmation_status = SlotConfirmationStatus.CONFIRMED
            return handler_input.response_builder.add_directive(
                ElicitSlotDirective(
                    current_intent,
                    SLOT_STOP_NAME)).speak(speech).ask(reprompt).response
        else:
            # Set the slot to None so that if Delegation were to be used,
            # Alexa can know to ask for this slot automatically
            current_intent.slots[SLOT_ROUTE_NUMBER].value = None
            wrong_route_speech = "The bus number is incorrect. Please provide me with a valid bus number. What is the " \
                                 "bus number?"
            wrong_route_reprompt = "What is the bus number?"
            return handler_input.response_builder.add_directive(
                ElicitSlotDirective(current_intent, SLOT_ROUTE_NUMBER)).speak(
                    wrong_route_speech).ask(wrong_route_reprompt).response
 def handle(self, handler_input):
     current_intent = handler_input.request_envelope.request.intent
     obj_serializer = DefaultSerializer()
     stop_val = get_slot(slot_name=SLOT_STOP_NAME,
                         handler_input=handler_input)
     default_route = handler_input.attributes_manager.session_attributes.get(
         R.DEFAULT_ROUTE)
     current_intent.confirmation_status = IntentConfirmationStatus.NONE
     matches = stop_val.resolutions.resolutions_per_authority
     # If the stop was matched with a valid name
     if matches[0].status.code == StatusCode.ER_SUCCESS_MATCH:
         matched_stop = matches[0].values[0]
         route = RouteConfig.get_data_route_and_agency_tag(
             agency_tag="umd", route_tag=default_route[R.ROUTE_TAG])
         stop_id = matched_stop.value.id
         if route.has_stop(stop_id):
             stop = route.get_stop_by_id(stop_id)
             handler_input.attributes_manager.session_attributes[
                 R.DEFAULT_STOP] = obj_serializer.serialize({
                     R.STOP_ID:
                     stop.stop_id,
                     R.DIRECTION:
                     stop.direction,
                     R.STOP_TITLE:
                     stop.stop_title
                 })
         else:
             current_intent.slots[SLOT_STOP_NAME].value = None
             current_intent.slots[
                 SLOT_STOP_NAME].confirmation_status = SlotConfirmationStatus.NONE
             return handler_input.response_builder.add_directive(
                 ElicitSlotDirective(current_intent, SLOT_STOP_NAME)
             ).speak(
                 "The stop while confirming is not a stop for this route. Please try again with a stop name or stop number "
                 "that is in this route").ask(
                     "Provide a stop name or stop number").response
     return handler_input.response_builder.add_directive(
         ConfirmIntentDirective(current_intent)).speak(
             "I am setting these defaults. Is that okay?").response
class TestSerialization(unittest.TestCase):
    def setUp(self):
        self.test_serializer = DefaultSerializer()

    def test_none_obj_serialization(self):
        test_obj = None
        assert self.test_serializer.serialize(test_obj) is None, \
            "Default Serializer serialized None object incorrectly"

    def test_primitive_obj_serialization(self):
        test_obj = "test"
        assert self.test_serializer.serialize(test_obj) == test_obj, \
            "Default Serializer serialized str object incorrectly"

        test_obj = 123
        assert self.test_serializer.serialize(test_obj) == test_obj, \
            "Default Serializer serialized int object incorrectly"

        test_obj = u"test"
        assert self.test_serializer.serialize(test_obj) == test_obj, \
            "Default Serializer serialized unicode object incorrectly"

        test_obj = b"test"
        assert self.test_serializer.serialize(test_obj) == test_obj, \
            "Default Serializer serialized bytes object incorrectly"

        test_obj = False
        assert self.test_serializer.serialize(test_obj) == test_obj, \
            "Default Serializer serialized bool object incorrectly"

    def test_list_obj_serialization(self):
        test_obj_inst = data.ModelTestObject2(int_var=123)
        test_list_obj = ["test", 123, test_obj_inst]

        expected_list = ["test", 123, {"var4Int": 123}]
        assert self.test_serializer.serialize(test_list_obj) == expected_list, \
            "Default Serializer serialized list object incorrectly"

    def test_tuple_obj_serialization(self):
        test_obj_inst = data.ModelTestObject2(int_var=123)
        test_tuple_obj = ("test", 123, test_obj_inst)

        expected_tuple = ("test", 123, {"var4Int": 123})
        assert self.test_serializer.serialize(test_tuple_obj) == expected_tuple, \
            "Default Serializer serialized tuple object incorrectly"

    def test_datetime_obj_serialization(self):
        test_obj = datetime.datetime(2018, 1, 1, 10, 20, 30)
        expected_datetime = "2018-01-01T10:20:30"
        assert self.test_serializer.serialize(test_obj) == expected_datetime, \
            "Default Serializer serialized datetime object incorrectly"

    def test_date_obj_serialization(self):
        test_obj = datetime.date(2018, 1, 1)
        expected_date = "2018-01-01"
        assert self.test_serializer.serialize(test_obj) == expected_date, \
            "Default Serializer serialized datetime object incorrectly"

    def test_dict_obj_serialization(self):
        test_obj_inst = data.ModelTestObject2(int_var=123)
        test_dict_obj = {
            "test_str": "test",
            "test_int": 123,
            "test_obj": test_obj_inst
        }

        expected_dict = {
            "test_str": "test",
            "test_obj": {
                "var4Int": 123
            },
            "test_int": 123,
        }
        assert self.test_serializer.serialize(test_dict_obj) == expected_dict, \
            "Default Serializer serialized dict object incorrectly"

    def test_model_obj_serialization(self):
        test_model_obj_2 = data.ModelTestObject2(int_var=123)
        test_model_obj_1 = data.ModelTestObject1(
            str_var="test", datetime_var=datetime.datetime(
                2018, 1, 1, 10, 20, 30), obj_var=test_model_obj_2)

        expected_serialized_obj = {
            "var1": "test",
            "var2Time": "2018-01-01T10:20:30",
            "var3Object": {
                "var4Int": 123
            }
        }
        assert self.test_serializer.serialize(test_model_obj_1) == expected_serialized_obj, \
            "Default Serializer serialized model object incorrectly"

    def test_enum_obj_serialization(self):
        test_model_obj_2 = data.ModelTestObject2(int_var=123)
        test_enum_obj = data.ModelEnumObject("ENUM_VAL_1")
        test_model_obj_1 = data.ModelTestObject1(
            str_var="test", datetime_var=datetime.datetime(
                2018, 1, 1, 10, 20, 30), obj_var=test_model_obj_2,
            enum_var=test_enum_obj)

        expected_serialized_obj = {
            "var1": "test",
            "var2Time": "2018-01-01T10:20:30",
            "var6Enum": "ENUM_VAL_1",
            "var3Object": {
                "var4Int": 123
            }
        }
        assert self.test_serializer.serialize(test_model_obj_1) == expected_serialized_obj, \
            "Default Serializer serialized enum object incorrectly"

    def test_decimal_obj_without_decimals_serialization(self):
        test_decimal_obj = decimal.Decimal(10)
        expected_obj = 10
        actual_obj = self.test_serializer.serialize(test_decimal_obj)

        assert actual_obj == expected_obj, (
            "Default Serializer serialized decimal object containing no "
            "decimals incorrectly")
        assert type(actual_obj) == int, (
            "Default Serializer serialized decimal object containing no "
            "decimals to incorrect type")

    def test_decimal_obj_with_decimals_serialization(self):
        test_decimal_obj = decimal.Decimal(10.5)
        expected_obj = 10.5
        actual_obj = self.test_serializer.serialize(test_decimal_obj)

        assert actual_obj == expected_obj, (
            "Default Serializer serialized decimal object containing "
            "decimals incorrectly")
        assert type(actual_obj) == float, (
            "Default Serializer serialized decimal object containing "
            "decimals to incorrect type")
Пример #9
0
def parse_handler_input(
        handler_input: HandlerInput,
) -> Tuple[UserMessage, Dict[str, Any]]:
    """Parses the ASK-SDK HandlerInput into Slowbro UserMessage.

    Returns the UserMessage object and serialized SessionAttributes.
    """

    request_envelope = handler_input.request_envelope

    text: str
    asr_hypos: List[AsrHypothesisUtterance] = []
    if is_request_type("LaunchRequest")(handler_input):
        # This is a launch request.
        text = ''
    elif is_request_type("IntentRequest")(handler_input):
        slots = request_envelope.request.intent.slots
        slot_text = slots.get('Text', None)
        if slot_text is not None:
            text = slot_text.value
        else:
            text = ''

        if hasattr(request_envelope.request, 'speechRecognition'):
            hypotheses = request_envelope.request.speechRecognition.get('hypotheses', [])
            asr_hypos.extend([
                AsrHypothesisUtterance(
                    [
                        AsrHypothesisToken(
                            token['value'],
                            token['confidence'],
                            token['startOffsetInMilliseconds'],
                            token['endOffsetInMilliseconds']
                        )
                        for token in hypo['tokens']
                    ],
                    hypo['confidence']
                )
                for hypo in hypotheses
            ])
        elif text:
            # NOTE: create a fake ASR hypo using the text field.
            asr_hypos.extend([
                AsrHypothesisUtterance(
                    [
                        AsrHypothesisToken(
                            token,
                            -1,
                            -1,
                            -1
                        )
                        for token in text.split(' ')
                    ],
                    -1
                )
            ])

        if not text:
            # Try to recover the text using asr_hypos.
            # Otherwise, raise an exception.
            if asr_hypos:
                text = asr_hypos[0].__str__()
            else:
                raise Exception('Unable to find "text" from handler input:',
                                handler_input)
    else:
        raise Exception('Unable to parse handler input:',
                        handler_input)


    serializer = DefaultSerializer()
    user_message = UserMessage(
        payload=serializer.serialize(request_envelope),
        channel='alexaprize',
        request_id=request_envelope.request.request_id,
        session_id=request_envelope.session.session_id,
        user_id=request_envelope.session.user.user_id,
        text=text,
        asr_hypos=asr_hypos
    )

    attributes_manager = handler_input.attributes_manager
    ser_session_attributes = attributes_manager.session_attributes

    return (user_message, ser_session_attributes)
Пример #10
0
def main():
    cmdline_parser = argparse.ArgumentParser(
        description=__doc__
    )
    cmdline_parser.add_argument(
        '--endpoint_url',
        default='http://localhost:8080',
        help='endpoint_url'
    )
    cmdline_parser.add_argument(
        '--logdir',
        required=True,
        help='log directory'
    )
    args = cmdline_parser.parse_args()

    serializer = DefaultSerializer()

    if not os.path.exists(args.logdir):
        os.mkdir(args.logdir)


    curr_request = create_launch_request()
    curr_session_attributes: Dict[str, Any] = {}
    round_index = 1
    while True:
        request_envelope = create_request_envelope(
            curr_session_attributes,
            curr_request
        )

        request_json = os.path.join(
            args.logdir,
            'request.round_{}.json'.format(round_index)
        )
        fp = codecs.open(
            request_json,
            'w',
            encoding='utf-8'
        )
        fp.write(json.dumps(serializer.serialize(request_envelope)))
        fp.write('\n')
        fp.close()

        response_envelope = send_request(
            args.endpoint_url,
            request_envelope
        )
        response = response_envelope.response
        if response.should_end_session:
            print('=' * 8, 'Session Ended', '=' * 8)
            print(curr_session_attributes)
            break

        print('=' * 8, 'Round Index:', round_index, '=' * 8 )
        print('Bot Utterance: ',
              unescape_ssml(response.output_speech.ssml[7:-8]))
        if response.reprompt:
            print('Bot Reprompt: ',
                  unescape_ssml(response.reprompt.output_speech.ssml[7:-8]))


        round_index += 1
        user_utterance = input('User Utterance: ')
        curr_session_attributes = response_envelope.session_attributes
        curr_request = create_intent_request(
            round_index=round_index,
            user_utterance=user_utterance,
        )