Beispiel #1
0
    def match_generic_templates(self, da, svs):
        """\
        Find a matching template for a dialogue act using substitutions
        for slot values.

        Returns a matching template and a dialogue act where values of some
        of the slots are substituted with a generic value.
        """
        tpl = None
        # try to find increasingly generic templates
        # limit the complexity of the search
        if len(svs) == 0:
            rng = []
        elif len(svs) == 1:
            rng = [1]
        elif len(svs) == 2:
            rng = [1, 2]
        else:
            rng = [1, len(svs) - 1, len(svs)]

        for r in rng:
            for cmb in itertools.combinations(svs, r):
                generic_da = self.get_generic_da_given_svs(da, cmb)
                try:
                    gda, tpls = self.gtemplates[unicode(generic_da)]
                    tpl = self.random_select(tpls)
                except KeyError:
                    continue
                return tpl, gda

        # I did not find anything
        raise TemplateNLGException("No match with generic templates.")
Beispiel #2
0
 def __init__(self, cfg):
     """\
     Initialization, checking configuration, loading
     templates and NLG rules.
     """
     super(TectoTemplateNLG, self).__init__(cfg)
     # check that the configuration contains everything we need
     if not 'NLG' in self.cfg or not 'TectoTemplate' in self.cfg['NLG']:
         raise TemplateNLGException('No configuration found!')
     mycfg = self.cfg['NLG']['TectoTemplate']
     if not 'model' in mycfg or not 'scenario' in mycfg or \
             not 'data_dir' in mycfg:
         raise TemplateNLGException('NLG scenario, data directory ' +
                                    'and templates must be defined!')
     # load templates
     self.load_templates(mycfg['model'])
     # load NLG system
     self.nlg_rules = Scenario(mycfg)
     self.nlg_rules.load_blocks()
Beispiel #3
0
def nlg_factory(nlg_type, cfg):
    nlg = None

    # do not forget to maintain all supported dialogue managers
    if nlg_type == 'Template':
        nlg = TemplateNLG(cfg)
    elif nlg_type == 'TectoTemplate':
        nlg = TectoTemplateNLG(cfg)
    else:
        try:
            nlg = nlg_type(cfg)
        except NameError:
            raise TemplateNLGException('Unsupported NLG: %s' % nlg_type)

    return nlg
Beispiel #4
0
    def load_templates(self, file_name):
        """\
        Load templates from an external file, which is assumed to be a
        Python source which defines the variable 'templates' as a dictionary
        containing stringified dialog acts as keys and (lists of) templates
        as values.
        """
        try:
            templates = load_as_module(file_name, force=True).templates
            # normalize the templates
            self.templates = {}
            # generalised templates
            self.gtemplates = {}
            for k, v in templates.iteritems():
                da = DialogueAct(k)
                # k.sort()
                self.templates[unicode(da)] = v
                self.gtemplates[unicode(self.get_generic_da(da))] = (da, v)

        except Exception as e:
            raise TemplateNLGException('No templates loaded from %s -- %s!' % (file_name, e))
Beispiel #5
0
    def random_select(self, tpl):
        """\
        Randomly select alternative templates for generation.

        The selection process is modeled by an embedded list structure
        (a tree-like structure).
        In the first level, the algorithm selects one of N.
        In the second level, for every item it selects one of M,
        and joins them together.
        This continues toward the leaves which must be non-list objects.

        There are the following random selection options (only the first
        three):

        (1)
            {
            'hello()' : u"Hello",
            }

            This will return the "Hello" string.

        (2)
            {
            'hello()' : (u"Hello",
                         u"Hi",
                        ),
            }

            This will return one of the "Hello" or "Hi" strings.


        (2)
            {
            'hello()' : (
                         [
                          (u"Hello.",
                           u"Hi.",
                          )
                          (u"How are you doing?",
                           u"Welcome".,
                          ),
                          u"Speak!",
                         ],

                         u"Hi my friend."
                        ),
            }

            This will return one of the following strings:
                "Hello. How are you doing? Speak!"
                "Hi. How are you doing? Speak!"
                "Hello. Welcome. Speak!"
                "Hi. Welcome. Speak!"
                "Hi my friend."
        """
        if isinstance(tpl, basestring):
            return tpl
        elif isinstance(tpl, tuple):
            tpl_rc_or = random.choice(tpl)

            if isinstance(tpl_rc_or, basestring):
                return tpl_rc_or
            elif isinstance(tpl_rc_or, list):
                tpl_rc_and = []

                for t in tpl_rc_or:
                    tpl_rc_and.append(self.random_select(t))

                return u" ".join(tpl_rc_and).replace(u'  ', u' ')
            elif isinstance(tpl_rc_or, tuple):
                raise TemplateNLGException("Unsupported generation type. " +
                                           "At this level, the template" +
                                           "cannot be a tuple: template = %s" %
                                           unicode(tpl))
        elif isinstance(tpl, list):
            raise TemplateNLGException("Unsupported generation type. " +
                                       "At this level, the template cannot " +
                                       "be a list: template = %s" %
                                       unicode(tpl))
        else:
            raise TemplateNLGException("Unsupported generation type.")