Example #1
0
#!/usr/bin/env python
"""Generates a response"""

from semantics.lexical_constants import ACTION_ALIASES

# Semantics constants
KNOWN_ACTIONS = set(ACTION_ALIASES.values())

# Response constants
DUNNO = "Sorry, I don't know how to%s."
GOTIT = "Got it. I'll%s."
MISUNDERSTAND = "Sorry, I didn't understand that at all."

def make_response(new_commands, kb_response):
    """Make a response based on the new commands
    and the knowledge base response."""
    if not new_commands:
        # Use knowledge base response if available, otherwise give up
        if kb_response:
            return kb_response
        else:
            return MISUNDERSTAND

    # Split into good and bad commands, futher filtering the good ones
    good_commands = []
    bad_commands = []
    # TODO: handle unknown entities

    for c in new_commands:
        if c.action in KNOWN_ACTIONS:
            good_commands.append(c)
Example #2
0
def create_semantic_structures(frame_semantic_list):
    """Take in the list of VerbNet frames and generate the semantic
    representation structures from them."""
    semantic_representation_list = []
    isConditionalNext = False
    # Whether there is a conditional in the semantic representation list waiting to be picked up
    hasConditional = False

    # Frame semantic list is a list of conjunction strings and tuples, where the
    # first element of the tuple is the frame semantics, the second element is
    # the original tree branch it came from, the third is a list of tags, and
    # the fourth is the sense.
    for frame in frame_semantic_list:
        # Check that this is a VerbNet frame and not a conjunction
        try:
            frame_items = frame[0].items()
        except AttributeError:
            if 'if' in str(frame):
                isConditionalNext = True
            frame_items = None
            #semantic_representation_list.append(frame)
            continue

        sense = frame[3].split('-')[0]
        # Get the action associated with the sense
        # If such a mapping does not exist, use the original verb
        action = ACTION_ALIASES.get(sense, frame[4])

        item_to_entity = {
            key: extract_entity(value, key)
            for key, value in frame_items
        }

        wh_question_type = get_wh_question_type(str(frame[1]))

        # If it's a WH-question, find the type of question it is and add the object
        if wh_question_type is not None:
            if wh_question_type == 'Status':
                semantic_representation_list.append(StatusQuery())
            elif 'Theme' in item_to_entity:
                if wh_question_type == 'Location':
                    semantic_representation_list.append(
                        LocationQuery(item_to_entity['Theme']))
                elif wh_question_type in ('People', 'Entity'):
                    semantic_representation_list.append(
                        EntityQuery(item_to_entity['Location']))

        # If it's a yes-no question, add the theme and location of the question
        elif is_yn_question(str(frame[1])):
            if 'Theme' in item_to_entity and 'Location' in item_to_entity:
                semantic_representation_list.append(
                    YNQuery(item_to_entity['Theme'],
                            item_to_entity['Location']))
        # If it's a conditional statement, it is modifying
        # either the previous or next structure
        elif isConditionalNext:
            if 'Stimulus' in item_to_entity:
                condition = Event(item_to_entity['Stimulus'], action)
            else:
                condition = Assertion(item_to_entity.get('Theme', None),
                                      item_to_entity.get('Location', None),
                                      'ex' in frame[2])

            if len(semantic_representation_list) > 0 and isinstance(
                    semantic_representation_list[-1], Command):
                # Found the command to which this condition belongs
                semantic_representation_list[-1].condition = condition
            else:
                # Save it for later
                semantic_representation_list.append(condition)
                hasConditional = True
            # Consume the conditional
            isConditionalNext = False
        # It's a regular command
        elif action is not None and action not in ('is', 'are', 'be'):
            theme = item_to_entity.get('Theme', None)
            agent = item_to_entity.get('Agent', None)
            patient = item_to_entity.get('Patient', None)
            if patient is None:
                patient = item_to_entity.get('Recipient', None)
            location = item_to_entity.get('Location', None)
            source = item_to_entity.get('Source', None)
            destination = item_to_entity.get('Destination', None)
            current_command = Command(agent,
                                      theme,
                                      patient,
                                      location,
                                      source,
                                      destination,
                                      action,
                                      negation=frame[5])
            # Try to pick up the previous condition
            if hasConditional:
                current_command.condition = semantic_representation_list.pop()
                hasConditional = False
            semantic_representation_list.append(current_command)
        # It's an assertion
        else:
            semantic_representation_list.append(
                Assertion(item_to_entity.get('Theme', None),
                          item_to_entity.get('Location', None), 'ex'
                          in frame[2]))
    if EXTRACT_DEBUG:
        print 'Semantic representation list:'
        print semantic_representation_list
    return semantic_representation_list
Example #3
0
#!/usr/bin/env python
"""Generates a response"""

from semantics.lexical_constants import ACTION_ALIASES

# Semantics constants
KNOWN_ACTIONS = set(ACTION_ALIASES.values())

# Response constants
DUNNO = "Sorry, I don't know how to%s."
GOTIT = "Got it. I'll%s."
MISUNDERSTAND = "Sorry, I didn't understand that at all."


def make_response(new_commands, kb_response):
    """Make a response based on the new commands
    and the knowledge base response."""
    if not new_commands:
        # Use knowledge base response if available, otherwise give up
        if kb_response:
            return kb_response
        else:
            return MISUNDERSTAND

    # Split into good and bad commands, futher filtering the good ones
    good_commands = []
    bad_commands = []
    # TODO: handle unknown entities

    for c in new_commands:
        if c.action in KNOWN_ACTIONS:
Example #4
0
def create_semantic_structures(frame_semantic_list):
    """Take in the list of VerbNet frames and generate the semantic
    representation structures from them."""
    semantic_representation_list = []
    isConditionalNext = False
    # Whether there is a conditional in the semantic representation list waiting to be picked up
    hasConditional = False

    # Frame semantic list is a list of conjunction strings and tuples, where the
    # first element of the tuple is the frame semantics, the second element is
    # the original tree branch it came from, the third is a list of tags, and
    # the fourth is the sense.
    for frame in frame_semantic_list:
        # Check that this is a VerbNet frame and not a conjunction
        try:
            frame_items = frame[0].items()
        except AttributeError:
            if 'if' in str(frame):
                isConditionalNext = True
            frame_items = None
            #semantic_representation_list.append(frame)
            continue

        sense = frame[3].split('-')[0]
        # Get the action associated with the sense
        # If such a mapping does not exist, use the original verb
        action = ACTION_ALIASES.get(sense, frame[4])

        item_to_entity = {key: extract_entity(value, key) for key, value in frame_items}

        wh_question_type = get_wh_question_type(str(frame[1]))

        # If it's a WH-question, find the type of question it is and add the object
        if wh_question_type is not None:
            if wh_question_type == 'Status':
                semantic_representation_list.append(StatusQuery())
            elif 'Theme' in item_to_entity:
                if wh_question_type == 'Location':
                    semantic_representation_list.append(LocationQuery(item_to_entity['Theme']))
                elif wh_question_type in ('People', 'Entity'):
                    semantic_representation_list.append(EntityQuery(item_to_entity['Location']))

        # If it's a yes-no question, add the theme and location of the question
        elif is_yn_question(str(frame[1])):
            if 'Theme' in item_to_entity and 'Location' in item_to_entity:
                semantic_representation_list.append(YNQuery(item_to_entity['Theme'], item_to_entity['Location']))
        # If it's a conditional statement, it is modifying
        # either the previous or next structure
        elif isConditionalNext:
            if 'Stimulus' in item_to_entity:
                condition = Event(item_to_entity['Stimulus'], action)
            else:
                condition = Assertion(item_to_entity.get('Theme', None),
                                      item_to_entity.get('Location', None),
                                      'ex' in frame[2])

            if len(semantic_representation_list) > 0 and isinstance(semantic_representation_list[-1], Command):
                # Found the command to which this condition belongs
                semantic_representation_list[-1].condition = condition
            else:
                # Save it for later
                semantic_representation_list.append(condition)
                hasConditional = True
            # Consume the conditional
            isConditionalNext = False
        # It's a regular command
        elif action is not None and action not in ('is', 'are', 'be'):
            theme = item_to_entity.get('Theme', None)
            agent = item_to_entity.get('Agent', None)
            patient = item_to_entity.get('Patient', None)
            if patient is None:
                patient = item_to_entity.get('Recipient', None)
            location = item_to_entity.get('Location', None)
            source = item_to_entity.get('Source', None)
            destination = item_to_entity.get('Destination', None)
            current_command = Command(agent, theme, patient, location, source, destination, action, negation=frame[5])
            # Try to pick up the previous condition
            if hasConditional:
                current_command.condition = semantic_representation_list.pop()
                hasConditional = False
            semantic_representation_list.append(current_command)
        # It's an assertion
        else:
            semantic_representation_list.append(Assertion(item_to_entity.get('Theme', None),
                                                          item_to_entity.get('Location', None),
                                                          'ex' in frame[2]))
    if EXTRACT_DEBUG:
        print 'Semantic representation list:'
        print semantic_representation_list
    return semantic_representation_list
Example #5
0
def create_semantic_structures(frame_semantic_list):
    """Take in the list of VerbNet frames and generate the semantic
    representation structures from them."""
    semantic_representation_list = []

    # Frame semantic list is a list of conjunction strings and tuples, where the
    # first element of the tuple is the frame semantics, the second element is
    # the original tree branch it came from, the third is a list of tags, and
    # the fourth is the sense.
    for frame in frame_semantic_list:

        #ADDED
        if not isinstance(frame, FrameMatch):
            if frame in ["and", "if"]:
                continue
            else:
                raise Exception(
                    "Unrecognized format for frame {}. Frame must be an instance of FrameMatch"
                    .format(frame))

        # Get the action associated with the sense
        # If such a mapping does not exist, use the original verb
        action = ACTION_ALIASES.get(frame.sense, frame.verb)

        #DEBUG
        #print "RECOGNIZED VERB ACTION:-----------------"
        #print action

        item_to_entity = _framearg_entities(frame.args)

        # TODO: Make this more robust
        wh_question_type = get_wh_question_type(str(frame.tree))

        # If it's a WH-question, find the type of question it is and add the
        # object
        if wh_question_type is not None:
            if wh_question_type == 'Status':
                semantic_representation_list.append(StatusQuery())
            elif 'Theme' in item_to_entity:
                if wh_question_type == 'Location':
                    semantic_representation_list.append(
                        LocationQuery(item_to_entity['Theme']))
                elif wh_question_type in ('People', 'Entity'):
                    semantic_representation_list.append(
                        EntityQuery(item_to_entity['Location']))

        # If it's a yes-no question, add the theme and location of the question
        elif is_yn_question(str(frame.tree)):
            if 'Theme' in item_to_entity and 'Location' in item_to_entity:
                semantic_representation_list.append(
                    YNQuery(item_to_entity['Theme'],
                            item_to_entity['Location']))
        # It's a regular command
        elif action is not None and action not in ASSERTION_VERBS:

            #ADDED
            if frame.condition:
                #Verbs like "detect", "sense" return a frame
                #where the condition part has the key 'Stimulus' in it
                #while verbs like 'see' return a frame where the condition
                #has a key named 'Theme'. We want to make everything
                #homogeneous since these verbs have the same meaning
                if 'Stimulus' in frame.condition.args:
                    theme = frame.condition.args['Stimulus']
                    frame.condition.args.pop('Stimulus')
                    frame.condition.args['Theme'] = theme
                if 'Experiencer' in frame.condition.args:
                    agent = frame.condition.args['Experiencer']
                    frame.condition.args.pop('Experiencer')
                    frame.condition.args['Agent'] = agent

            current_command = _make_command(action, frame)
            # TODO: Figure out how to save the condition_head

            #CHANGED
            if frame.condition:
                frameaction = ACTION_ALIASES.get(frame.condition.sense,
                                                 frame.condition.verb)
                current_command.condition = _make_command(frameaction,
                                                          frame.condition,
                                                          condition=True)
            semantic_representation_list.append(current_command)
        # It's an assertion
        else:
            # TODO: Give a real value for whether it's an existential
            semantic_representation_list.append(
                Assertion(item_to_entity.get('Theme', None),
                          item_to_entity.get('Location', None), False))

    return semantic_representation_list