Merge pull request #2297 from ChanceNCounter/prevent-repeating-dialog-lines

Cycle through dialog files to avoid repeating the same line
pull/2336/head
Åke 2019-09-26 16:23:08 +02:00 committed by GitHub
commit bf38812ddf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 29 additions and 0 deletions

View File

@ -35,6 +35,19 @@ class MustacheDialogRenderer:
def __init__(self):
self.templates = {}
self.recent_phrases = []
# TODO magic numbers are bad!
self.max_recent_phrases = 3
# We cycle through lines in .dialog files to keep Mycroft from
# repeating the same phrase over and over. However, if a .dialog
# file only contains a few entries, this can cause it to loop.
#
# This offset will override max_recent_phrases on very short .dialog
# files. With the offset at 2, .dialog files with 3 or more lines will
# be managed to avoid repetition, but .dialog files with only 1 or 2
# lines will be unaffected. Dialog should never get stuck in a loop.
self.loop_prevention_offset = 2
def load_template_file(self, template_name, filename):
"""
@ -67,6 +80,8 @@ class MustacheDialogRenderer:
Given a template name, pick a template and render it using the context.
If no matching template exists use template_name as template.
Tries not to let Mycroft say exactly the same thing twice in a row.
Args:
template_name (str): the name of a template group.
context (dict): dictionary representing values to be rendered
@ -84,14 +99,28 @@ class MustacheDialogRenderer:
# "record not found" literal.
return template_name.replace(".", " ")
# Get the .dialog file's contents, minus any which have been spoken
# recently.
template_functions = self.templates.get(template_name)
if index is None:
template_functions = ([t for t in template_functions
if t not in self.recent_phrases] or
template_functions)
line = random.choice(template_functions)
else:
line = template_functions[index % len(template_functions)]
# Replace {key} in line with matching values from context
line = line.format(**context)
line = random.choice(expand_options(line))
# Here's where we keep track of what we've said recently. Remember,
# this is by line in the .dialog file, not by exact phrase
self.recent_phrases.append(line)
if (len(self.recent_phrases) >
min(self.max_recent_phrases, len(self.templates.get(
template_name)) - self.loop_prevention_offset)):
self.recent_phrases.pop(0)
return line