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))
    def __init__(self, serializer=None, output_type=None):
        # type: (Serializer, Union[T, str]) -> None
        """Initializing the default serializer to deserialize rendered content
        to skill response output.

        If no serializer is specified, default serializer from
        :py:class:`ask_sdk_core.serialize.DefaultSerializer` is set also if the
        output type is not specified default value of
        :py:class:`ask_sdk_model.response.Response` is set.

        The ``output_type`` parameter can be a primitive type, a generic
        model object or a list / dict of model objects.

        :param serializer: Serializer to deserialize template content
        :type serializer: :py:class:`ask_sdk_model.services.Serializer`
        :param output_type: resolved class name for deserialized object
        :type output_type: Union[object, str]
        """
        if serializer is None:
            serializer = DefaultSerializer()

        if output_type is None:
            output_type = 'ask_sdk_model.response.Response'

        self.serializer = serializer
        self.output_type = output_type
Exemple #3
0
    def test(self, test_items):
        """
        Test the sequence of TestItems against self.validators
        Args:
            test_items(list of TestItem): the sequence of TestItems
        """
        if len(test_items) == 0:
            raise AttributeError("test_items must not be empty")
        handler = self.handler
        session_attributes = {}
        session_id = test_items[0].request.session.session_id.format(
            uuid.uuid4())
        for i, item in enumerate(test_items):
            item.request.session.new = i == 0
            item.request.session.attributes = session_attributes
            item.request.session.session_id = session_id

            if item.session_attributes:
                for k, v in item.session_attributes.items():
                    item.request.session.attributes[k] = v

            context = item.request.context
            if item.user_access_token is not None:
                context.system.api_access_token = item.user_access_token

            if item.profile_info is not None:
                handler = responses.activate(self.handler)
                add_profile_mock(context, item.profile_info)

            response_dict = handler(
                DefaultSerializer().serialize(item.request), context)
            response = response_from_dict(response_dict)
            for validator in self.validators:
                validator.validate(item, response)
            session_attributes = response.session_attributes
Exemple #4
0
    def get_recent_response(handler_input):
        """Returns last response object sent."""
        attr = handler_input.attributes_manager.session_attributes

        cached_response_str = json.dumps(attr['recent_response'])
        cached_response = DefaultSerializer().deserialize(
            cached_response_str, Response)
        return cached_response
 def handle(self, handler_input):
     session_attr = handler_input.attributes_manager.session_attributes
     logger.debug("Session Attr: {}".format(session_attr))
     # get the last response stored in session_attributes and return it
     cached_response_str = json.dumps(session_attr["recent_response"])
     cached_response = DefaultSerializer().deserialize(
         cached_response_str, Response)
     return cached_response
Exemple #6
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)
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
 def handle(self, handler_input):
     # type: (HandlerInput) -> Response
     logger.info("In RepeatHandler")
     attr = handler_input.attributes_manager.session_attributes
     response_builder = handler_input.response_builder
     if "recent_response" in attr:
         cached_response_str = json.dumps(attr["recent_response"])
         cached_response = DefaultSerializer().deserialize(
             cached_response_str, Response)
         return cached_response
     else:
         response_builder.speak(data.FALLBACK_ANSWER).ask(data.SET_MESSAGE)
         return response_builder.response
    def test_primitive_obj_deserialization_raising_type_error(self):
        test_serializer = DefaultSerializer()
        mocked_primitive_type = mock.Mock(side_effect=TypeError())

        test_serializer.PRIMITIVE_TYPES = [mocked_primitive_type]

        test_payload = "test"
        test_obj_type = mocked_primitive_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, \
                "Default Serializer deserialized primitive type which raises TypeError incorrectly"
    def test_primitive_obj_deserialization_raising_unicode_exception(self):
        test_serializer = DefaultSerializer()
        mocked_primitive_type = mock.Mock(
            side_effect=UnicodeEncodeError('hitchhiker', u"", 42, 43, 'the universe and everything else'))

        test_serializer.PRIMITIVE_TYPES = [mocked_primitive_type]

        test_payload = u"√"
        test_obj_type = mocked_primitive_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert test_serializer.deserialize(
                test_payload, test_obj_type) == u"\u221a", \
                "Default Serializer deserialized primitive type which raises UnicodeEncodeError incorrectly"
    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
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,
        )
Exemple #14
0
import logging.handlers
import uuid

from ask_sdk_core.skill_builder import CustomSkillBuilder
from ask_sdk_core.api_client import DefaultApiClient
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.serialize import DefaultSerializer

from ask_sdk_model.interfaces.custom_interface_controller import (
    StartEventHandlerDirective, EventFilter, Expiration, FilterMatchAction,
    StopEventHandlerDirective, SendDirectiveDirective, Header, Endpoint)

logger = logging.getLogger()
logger.setLevel(logging.INFO)
serializer = DefaultSerializer()
skill_builder = CustomSkillBuilder(api_client=DefaultApiClient())


@skill_builder.request_handler(can_handle_func=is_request_type("LaunchRequest")
                               )
def launch_request_handler(handler_input: HandlerInput):
    logger.info("== Launch Intent ==")

    response_builder = handler_input.response_builder

    system = handler_input.request_envelope.context.system

    # Get connected gadget endpoint ID.
    endpoints = get_connected_endpoints(handler_input)
    logger.debug("Checking endpoint..")
Exemple #15
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)
Exemple #16
0
import sys, os
import importlib

from ask_sdk_core.serialize import DefaultSerializer
from ask_sdk_model.request_envelope import RequestEnvelope
from ask_sdk_model.context import Context

sd = DefaultSerializer()

# TODO: I think the smart thing to build a test bench would be to go through all
# the handlers and just look for a file in some predetermined location and a
# file with the name of the function with a json extension.
#   e.g., def LaunchRequestHandler: ==> ../sampleEvents/LaunchRequest.json
# Then if someone wanted different names for the files they would have to
# specify a dictionry below. To quickly get the that information I think it
# would be able to come from the generated language model that the online
# creator makes. But there is away to do it by going through the model and
# looking at it's parent class. 

samples_path = 'utils/sampleEvents'
sample_events = {
    'LaunchRequest': '/LaunchRequestEvent.json',
    'HelpIntent': '/helpIntent.json',
    'GetNextMatchIntent': '/getNextMatchEvent.json',
    'GetNextTeamMatchIntent': '',
    'GetTeamRecordIntent': '/getTeamRecordEvent.json',
    'GetTodaysMatchesIntent': '/getTodaysMatchesEvent.json',
    'GetTomorrowsMatchesIntent': '/getTomorrowsMatchesEvent.json',
    'GetStandingsIntent': '/getStandingsEvent.json',
    'GetTopTeamIntent': '/getTopTeamEven.json',
    'GetNextTeamMatchIntent': '/getNextTeamMatchEvent.json'
 def setUp(self):
     self.test_serializer = DefaultSerializer()