def clarify(self, keywords):
        """
        Asks the user to specify a certain criteria if it is too broad.
        """

        # if the necessary fields do not exist, then throw an exception
        if 'clarify_cat' not in keywords or 'clarify_list' not in keywords:
            raise NLGException('Not enough information in keywords')

        # the first clause gets the user's attention
        stat1 = SPhraseSpec('Hey ' + random.choice([random.choice([self.tone_str('adjectives') + ' ', '']) + self.tone_str('names'), '']), '')
        # the second clause acknowledges that a specification was given
        stat2 = SPhraseSpec('I', 'know', 'you wanted a type of %s' % (keywords['clarify_cat']))
        # the third clause asks the user to provide a more narrow scope
        stat3 = SPhraseSpec()
        stat3.setCuePhrase('but please specify if')
        stat3.setVerb('meant')
        stat3.setSubject('you')
        uniques = ''
        for unique in keywords['clarify_list']:
            if unique == keywords['clarify_list'][0]:
                uniques += unique
            elif unique == keywords['clarify_list'][-1]:
                uniques += ', or ' + unique
            else:
                uniques += ', ' + unique
        stat3.setPostmodifier(uniques)

        # create the final utterance out of all the parts
        clarification = TextSpec()
        clarification.addSpec(stat1)
        clarification.addSpec(stat2)
        clarification.addSpec(stat3)
        clarification.setListConjunct(',')

        return REALISER.realiseDocument(clarification).strip()
    def summarize_query(self, query):
        """
        Returns an utterance that rewords the inputted query as a form
        of acknowledgement to the user.
        """

        # if no criteria is provided, let the user know that every dish
        # will be searched
        if query == {}:
            return 'I will just look for every recipe we have.'

        summary = SPhraseSpec()
        summary.setSubject('I')
        summary.setVerb(random.choice(self.search_verbs))
        summary.setProgressive(gateway.jvm.java.lang.Boolean.TRUE)

        # add specified cuisines included, if they exist
        if 'include_cuisines' in query:
            for cuisine in query['include_cuisines']:
                if cuisine == query['include_cuisines'][-1]:
                    summary.addComplement(cuisine + ' dishes')
                else:
                    summary.addComplement(cuisine)
        else:
            summary.addComplement('recipes')

        # create phrase to include ingredients
        if 'include_ingredients' in query:
            ing_inc = PPPhraseSpec()
            ing_inc.setPreposition('that contain ')
            for ingredient in query['include_ingredients']:
                ing_inc.addComplement(ingredient)
            summary.addModifier(ing_inc)

        # create phrase to exclude ingredients
        if 'exclude_ingredients' in query:
            ing_exc = PPPhraseSpec()
            ing_exc.setPreposition('but do not contain')
            for ingredient in query['exclude_ingredients']:
                ing_exc.addComplement(ingredient)
            summary.addModifier(ing_exc)

        # create phrase to include recipe times and number of steps
        # and/or ingredients

        steps = SPhraseSpec()
        if 'prep_time' in query or 'cook_time' in query or 'total_time' in query or 'num_steps' in query or 'num_ingredients' in query:
            steps.setSubject('I')
            steps.setVerb(random.choice(self.search_verbs))
            steps.setProgressive(gateway.jvm.java.lang.Boolean.TRUE)
            steps.addPremodifier('also')

            steps_list = []
            if 'prep_time' in query and query['prep_time'] != None:
                steps_list.append('%i minutes to prepare' % query['prep_time'])
            if 'cook_time' in query and query['cook_time'] != None:
                steps_list.append('%i minutes to cook' % (query['cook_time']))
            if 'total_time' in query and query['total_time'] != None:
                steps_list.append('%i total minutes to make' %
                                  (query['total_time']))
            if 'num_steps' in query and query['num_steps'] != None:
                steps_list.append('%i steps to complete' %
                                  (query['num_steps']))
            if 'num_ingredients' in query and query['num_ingredients'] != None:
                steps_list.append('%i ingredients' %
                                  (query['num_ingredients']))
            for step in steps_list:
                if step == steps_list[0]:
                    steps.addComplement('recipes that require ' + step)
                else:
                    steps.addComplement(step)

        # tie everything together into one utterance
        final = TextSpec()
        final.addSpec(summary)
        final.addSpec(steps)
        final.setListConjunct('.')

        return self.clean_str(REALISER.realiseDocument(final).strip())
    def clarify(self, keywords):
        """
        Asks the user to specify a certain criteria if it is too broad.
        """

        # if the necessary fields do not exist, then throw an exception
        if 'clarify_cat' not in keywords or 'clarify_list' not in keywords:
            raise NLGException('Not enough information in keywords')

        # the first clause gets the user's attention
        stat1 = SPhraseSpec(
            'Hey ' + random.choice([
                random.choice([self.tone_str('adjectives') + ' ', '']) +
                self.tone_str('names'), ''
            ]), '')
        # the second clause acknowledges that a specification was given
        stat2 = SPhraseSpec(
            'I', 'know', 'you wanted a type of %s' % (keywords['clarify_cat']))
        # the third clause asks the user to provide a more narrow scope
        stat3 = SPhraseSpec()
        stat3.setCuePhrase('but please specify if')
        stat3.setVerb('meant')
        stat3.setSubject('you')
        uniques = ''
        for unique in keywords['clarify_list']:
            if unique == keywords['clarify_list'][0]:
                uniques += unique
            elif unique == keywords['clarify_list'][-1]:
                uniques += ', or ' + unique
            else:
                uniques += ', ' + unique
        stat3.setPostmodifier(uniques)

        # create the final utterance out of all the parts
        clarification = TextSpec()
        clarification.addSpec(stat1)
        clarification.addSpec(stat2)
        clarification.addSpec(stat3)
        clarification.setListConjunct(',')

        return self.clean_str(REALISER.realiseDocument(clarification).strip())
    def unknown(self):
        """
        Returns an utterance that tells the user the last input was not
        understood.
        """

        output = SPhraseSpec()
        output.setSubject('I')
        output.setComplement('you')
        output.setTense(Tense.PAST)

        choice = random.randint(1, 3)
        if choice == 1:
            output.setVerb('understand')
            output.setComplement('what you')
            output.setNegated(gateway.jvm.java.lang.Boolean.TRUE)
            output.setPostmodifier('just said')
        elif choice == 2:
            output.setInterrogative(InterrogativeType.WHAT)
            output.setVerb('do')
            output.setPostmodifier('say')
        elif choice == 3:
            output.setTense(Tense.PRESENT)
            output.setSubject('please rephrase')
            output.setComplement('what you')
            output.setPostmodifier('just said')

        return self.clean_str(REALISER.realiseDocument(output).strip())
    def generate(self, utter_type, keywords):
        """
        Input: a type of inquiry to create and a dictionary of keywords.
        Types of inquiries include 'what', 'who', 'where', 'why', 'how',
        and 'yes/no' questions. Alternatively, 'none' can be specified to
        generate a declarative statement.

        The dictionary is essentially divided into three core parts: the
        subject, the verb, and the object. Modifiers can be specified to these
        parts (adverbs, adjectives, etc). Additionally, an optional
        prepositional phrase can be specified.

        Example:

        >>> nlg = NaturalLanguageGenerator(logging.getLogger())
        >>> words = {'subject': 'you',
        ...         'verb': 'prefer',
        ...         'object': 'recipes',
        ...         'preposition': 'that contains',
        ...         'objmodifiers': ['Thai'],
        ...         'prepmodifiers': ['potatoes', 'celery', 'carrots'],
        ...         'adverbs': ['confidently'],
        ... }
        >>> nlg.generate('yes_no', words)
        u'Do you confidently prefer Thai recipes that contains potatoes, celery and carrots?'
        >>> nlg.generate('how', words)
        u'How do you confidently prefer Thai recipes that contains potatoes, celery and carrots?'
        """
        if utter_type.lower() == 'greet':
            if 'name' in keywords:
                self.normal_words['names'].append(keywords['name'])
            return 'Hello, %s!' % (self.tone_str('names'))
        utterance = SPhraseSpec()
        subject = NPPhraseSpec(keywords['subject'])
        target = NPPhraseSpec(keywords['object'])
        preposition = PPPhraseSpec()

        if 'preposition' in keywords:
            preposition.setPreposition(keywords['preposition'])

        if 'prepmodifiers' in keywords:
            for modifier in keywords['prepmodifiers']:
                preposition.addComplement(modifier)

        if 'submodifiers' in keywords:
            for modifier in keywords['submodifiers']:
                subject.addModifier(modifier)

        if 'objmodifiers' in keywords:
            for modifier in keywords['objmodifiers']:
                target.addModifier(modifier)

        if utter_type.lower() == 'yes_no':
            utterance.setInterrogative(InterrogativeType.YES_NO)
        elif utter_type.lower() == 'how':
            utterance.setInterrogative(InterrogativeType.HOW)
        elif utter_type.lower() == 'what':
            utterance.setInterrogative(InterrogativeType.WHAT)
        elif utter_type.lower() == 'where':
            utterance.setInterrogative(InterrogativeType.WHERE)
        elif utter_type.lower() == 'who':
            utterance.setInterrogative(InterrogativeType.WHO)
        elif utter_type.lower() == 'why':
            utterance.setInterrogative(InterrogativeType.WHY)

        target.addModifier(preposition)
        utterance.setSubject(keywords['subject'])
        utterance.setVerb(keywords['verb'])
        if 'adverbs' in keywords:
            for modifier in keywords['adverbs']:
                utterance.addModifier(modifier)
        utterance.addComplement(target)

        output = self.clean_str(REALISER.realiseDocument(utterance).strip())
        return output
    def summarize_query(self, query):
        """
        Returns an utterance that rewords the inputted query as a form
        of acknowledgement to the user.
        """

        # if no criteria is provided, let the user know that every dish
        # will be searched
        if query == {}:
            return 'I will just look for every recipe we have.'

        summary = SPhraseSpec()
        summary.setSubject('I')
        summary.setVerb(random.choice(self.search_verbs))
        summary.setProgressive(gateway.jvm.java.lang.Boolean.TRUE)

        # add specified cuisines included, if they exist
        if 'include_cuisines' in query:
            for cuisine in query['include_cuisines']:
                if cuisine == query['include_cuisines'][-1]:
                    summary.addComplement(cuisine + ' dishes')
                else:
                    summary.addComplement(cuisine)
        else:
            summary.addComplement('recipes')

        # create phrase to include ingredients
        if 'include_ingredients' in query:
            ing_inc = PPPhraseSpec()
            ing_inc.setPreposition('that contain')
            for ingredient in query['include_ingredients']:
                ing_inc.addComplement(ingredient)
            summary.addModifier(ing_inc)

        # create phrase to exclude ingredients
        if 'exclude_ingredients' in query:
            ing_exc = PPPhraseSpec()
            ing_exc.setPreposition('but do not contain')
            for ingredient in query['exclude_ingredients']:
                ing_exc.addComplement(ingredient)
            summary.addModifier(ing_exc)

        # create phrase to include recipe times and number of steps
        # and/or ingredients

        steps = SPhraseSpec()
        if 'prep_time' in query or 'cook_time' in query or 'total_time' in query or 'num_steps' in query or 'num_ingredients' in query:
            steps.setSubject('I')
            steps.setVerb(random.choice(self.search_verbs))
            steps.setProgressive(gateway.jvm.java.lang.Boolean.TRUE)
            steps.addPremodifier('also')

            steps_list = []
            if 'prep_time' in query and query['prep_time'] != None:
                steps_list.append('%i minutes to prepare' % query['prep_time'])
            if 'cook_time' in query and query['cook_time'] != None:
                steps_list.append('%i minutes to cook' % (query['cook_time']))
            if 'total_time' in query and query['total_time'] != None:
                steps_list.append('%i total minutes to make' %
                                  (query['total_time']))
            if 'num_steps' in query and query['num_steps'] != None:
                steps_list.append('%i steps to complete' % (query['num_steps']))
            if 'num_ingredients' in query and query['num_ingredients'] != None:
                steps_list.append('%i ingredients' % (query['num_ingredients']))
            for step in steps_list:
                if step == steps_list[0]:
                    steps.addComplement('recipes that require ' + step)
                else:
                    steps.addComplement(step)

        # tie everything together into one utterance
        final = TextSpec()
        final.addSpec(summary)
        final.addSpec(steps)
        final.setListConjunct('.')

        return REALISER.realiseDocument(final).strip()
    def unknown(self):
        """
        Returns an utterance that tells the user the last input was not
        understood.
        """

        output = SPhraseSpec()
        output.setSubject('I')
        output.setComplement('you')
        output.setTense(Tense.PAST)

        choice = random.randint(1, 3)
        if choice == 1:
            output.setVerb('understand')
            output.setComplement('what you')
            output.setNegated(gateway.jvm.java.lang.Boolean.TRUE)
            output.setPostmodifier('just said')
        elif choice == 2:
            output.setInterrogative(InterrogativeType.WHAT)
            output.setVerb('do')
            output.setPostmodifier('say')
        elif choice == 3:
            output.setTense(Tense.PRESENT)
            output.setSubject('please rephrase')
            output.setComplement('what you')
            output.setPostmodifier('just said')

        return REALISER.realiseDocument(output).strip()
    def generate(self, utter_type, keywords):
        """
        Input: a type of inquiry to create and a dictionary of keywords.
        Types of inquiries include 'what', 'who', 'where', 'why', 'how',
        and 'yes/no' questions. Alternatively, 'none' can be specified to
        generate a declarative statement.

        The dictionary is essentially divided into three core parts: the
        subject, the verb, and the object. Modifiers can be specified to these
        parts (adverbs, adjectives, etc). Additionally, an optional
        prepositional phrase can be specified.

        Example:

        >>> nlg = NaturalLanguageGenerator(logging.getLogger())
        >>> words = {'subject': 'you',
        ...         'verb': 'prefer',
        ...         'object': 'recipes',
        ...         'preposition': 'that contains',
        ...         'objmodifiers': ['Thai'],
        ...         'prepmodifiers': ['potatoes', 'celery', 'carrots'],
        ...         'adverbs': ['confidently'],
        ... }
        >>> nlg.generate('yes_no', words)
        u'Do you confidently prefer Thai recipes that contains potatoes, celery and carrots?'
        >>> nlg.generate('how', words)
        u'How do you confidently prefer Thai recipes that contains potatoes, celery and carrots?'
        """
        if utter_type.lower() == 'greet':
            if 'name' in keywords:
                self.normal_words['names'].append(keywords['name'])
            return 'Hello, %s!' % (self.tone_str('names'))
        utterance = SPhraseSpec()
        subject = NPPhraseSpec(keywords['subject'])
        target = NPPhraseSpec(keywords['object'])
        preposition = PPPhraseSpec()

        if 'preposition' in keywords:
            preposition.setPreposition(keywords['preposition'])

        if 'prepmodifiers' in keywords:
            for modifier in keywords['prepmodifiers']:
                preposition.addComplement(modifier)

        if 'submodifiers' in keywords:
            for modifier in keywords['submodifiers']:
                subject.addModifier(modifier)

        if 'objmodifiers' in keywords:
            for modifier in keywords['objmodifiers']:
                target.addModifier(modifier)

        if utter_type.lower() == 'yes_no':
            utterance.setInterrogative(InterrogativeType.YES_NO)
        elif utter_type.lower() == 'how':
            utterance.setInterrogative(InterrogativeType.HOW)
        elif utter_type.lower() == 'what':
            utterance.setInterrogative(InterrogativeType.WHAT)
        elif utter_type.lower() == 'where':
            utterance.setInterrogative(InterrogativeType.WHERE)
        elif utter_type.lower() == 'who':
            utterance.setInterrogative(InterrogativeType.WHO)
        elif utter_type.lower() == 'why':
            utterance.setInterrogative(InterrogativeType.WHY)

        target.addModifier(preposition)
        utterance.setSubject(keywords['subject'])
        utterance.setVerb(keywords['verb'])
        if 'adverbs' in keywords:
            for modifier in keywords['adverbs']:
                utterance.addModifier(modifier)
        utterance.addComplement(target)

        output = REALISER.realiseDocument(utterance).strip()
        return output
Exemplo n.º 9
0
    def generate(self, utter_type, keywords, tense=None):
        """
        Input: a type of inquiry to create and a dictionary of keywords.
        Types of inquiries include 'what', 'who', 'where', 'why', 'how',
        and 'yes/no' questions. Alternatively, 'none' can be specified to
        generate a declarative statement.

        The dictionary is essentially divided into three core parts: the
        subject, the verb, and the object. Modifiers can be specified to these
        parts (adverbs, adjectives, etc). Additionally, an optional
        prepositional phrase can be specified.

        Example:

        nlg = NaturalLanguageGenerator(logging.getLogger())
        words = {'subject': 'you',
                 'verb': 'prefer',
                 'object': 'recipes',
                 'preposition': 'that contains',
                 'objmodifiers': ['Thai'],
                 'prepmodifiers': ['potatoes', 'celery', 'carrots'],
                 'adverbs': ['confidently'],
        }

        nlg.generate('yes_no', words)
        u'Do you confidently prefer Thai recipes that contains potatoes, celery and carrots?'
        nlg.generate('how', words)
        u'How do you confidently prefer Thai recipes that contains potatoes, celery and carrots?'
        """
        utterance = SPhraseSpec()
        subject = NPPhraseSpec(keywords["subject"])
        target = None
        if "object" in keywords:
            target = NPPhraseSpec(keywords["object"])
        preposition = PPPhraseSpec()

        if "preposition" in keywords:
            preposition.setPreposition(keywords["preposition"])

        if "prepmodifiers" in keywords:
            for modifier in keywords["prepmodifiers"]:
                preposition.addComplement(modifier)

        if "submodifiers" in keywords:
            for modifier in keywords["submodifiers"]:
                subject.addModifier(modifier)

        if "objmodifiers" in keywords:
            for modifier in keywords["objmodifiers"]:
                target.addModifier(modifier)

        if utter_type.lower() == "yes_no":
            utterance.setInterrogative(InterrogativeType.YES_NO)
        elif utter_type.lower() == "how":
            utterance.setInterrogative(InterrogativeType.HOW)
        elif utter_type.lower() == "what":
            utterance.setInterrogative(InterrogativeType.WHAT)
        elif utter_type.lower() == "where":
            utterance.setInterrogative(InterrogativeType.WHERE)
        elif utter_type.lower() == "who":
            utterance.setInterrogative(InterrogativeType.WHO)
        elif utter_type.lower() == "why":
            utterance.setInterrogative(InterrogativeType.WHY)

        if target is not None:
            target.addModifier(preposition)
        utterance.setSubject(subject)
        utterance.setVerb(keywords["verb"])
        if "adverbs" in keywords:
            for modifier in keywords["adverbs"]:
                utterance.addModifier(modifier)
        if target is not None:
            utterance.addComplement(target)

        if tense.lower() == "future":
            utterance.setTense(Tense.FUTURE)
        elif tense.lower() == "past":
            utterance.setTense(Tense.PAST)

        realiser = Realiser()
        output = realiser.realiseDocument(utterance).strip()
        return output