dream

Форк
0
130 строк · 6.0 Кб
1
#!/usr/bin/env python
2

3
import random
4
import re
5

6

7
class Teller:
8
    def __init__(self, stories, phrases, status_constants, logger):
9
        """
10
        The one that tells tales...
11
        """
12
        self.history = []
13
        self.phrases = phrases
14
        self.stories = stories
15
        self.status_constants = status_constants
16
        self.logger = logger
17

18
    def get_story(self, sentence):
19
        """
20
        Determine what type of story user requested
21
        """
22
        sentence = sentence.lower()
23
        if re.search("fun((ny)|(niest)){0,1}", sentence):
24
            return "funny"
25
        elif re.search("(horror)|(scary)|(frightening)|(spooky)", sentence):
26
            return "scary"
27
        elif re.search("(bedtime)|(good)|(kind)|(baby)|(children)|(good night)|(for kid(s){0,1})", sentence):
28
            return "bedtime"
29
        else:
30
            return None
31

32
    def choose_story(self, attributes, story_type):
33
        """
34
        Choose a story.
35
        """
36
        already_told_stories = attributes.get("already_told_stories", [])
37
        try:  # Try to get a story that haven't been told already
38
            story = random.choice(list(set(self.stories[story_type].keys()) - set(already_told_stories)))
39
        except IndexError:  # We run out of stories
40
            phrase = "Oh, I am sorry, but I've run out of stories. Maybe you have any to share with me?"
41
            status = self.status_constants["cannot"]
42
        else:  # Tell a story setup
43
            already_told_stories += [story]
44
            phrase = self.stories[story_type][story]["setup"] + "..." + random.choice(self.phrases["what_happend_next"])
45
            status = self.status_constants["must"]
46
            attributes["state"] = "setup"
47
            attributes["story"] = story
48
            attributes["already_told_stories"] = already_told_stories
49
        return phrase, status, attributes
50

51
    def tell_punchline(self, story_name):
52
        for story_type in self.stories:
53
            for story in self.stories[story_type]:
54
                if story == story_name:
55
                    return self.stories[story_type][story_name]["punchline"]
56
        return "Oh, sorry, i lost the track of what I was talking about."
57

58
    def tell(self, human_sentence, intents, state):
59
        """
60
        Basic logic of story teller
61
        """
62
        phrase = ""
63
        status = self.status_constants["can"]
64
        confidence = 0.999
65
        # Set attributes
66
        attributes = {}
67
        # Get intent values
68
        tell_me_a_story = bool(intents.get("tell_me_a_story", {}).get("detected", False))
69
        yes = bool(intents.get("yes", {}).get("detected", False))
70
        no = bool(intents.get("no", {}).get("detected", False))
71
        # Logging
72
        self.logger.info(f"Human sentence: {human_sentence}")
73
        self.logger.info(f"tell_me_a_story: {tell_me_a_story}")
74
        self.logger.info(f"yes: {yes}")
75
        self.logger.info(f"no: {no}")
76
        self.logger.info(f"state: {state}")
77

78
        # Skill logic
79
        # We detected an intent firsthand
80
        if tell_me_a_story or state.get("state", "") == "asked_for_a_story":
81
            story_type = self.get_story(human_sentence)
82
            # User didn't specify the type of story
83
            if story_type is None:
84
                if state.get("state", "") == "asked_for_a_story":
85
                    phrase = random.choice(self.phrases["which_story"])
86
                else:
87
                    phrase = random.choice(self.phrases["sure"]) + " " + random.choice(self.phrases["which_story"])
88
                status = self.status_constants["must"]
89
                attributes["state"] = "which_story"
90
            else:  # The type of story is already specified in intial intent
91
                phrase, status, attributes = self.choose_story(attributes, story_type)
92
        elif state.get("state", "") == "do_you_mind" and yes:  # Want a story -> yes
93
            confidence = 1.0
94
            phrase = random.choice(self.phrases["which_story"])
95
            status = self.status_constants["must"]
96
            attributes["state"] = "which_story"
97
        elif state.get("state", "") == "do_you_mind" and no:  # Want a story -> no
98
            phrase = random.choice(self.phrases["no"])
99
            status = self.status_constants["can"]
100
        elif state.get("state", "") == "do_you_mind":  # Didn't get the answer
101
            phrase = random.choice(self.phrases["which_story"])
102
            status = self.status_constants["can"]
103
            attributes["state"] = "which_story"
104
            confidence = 0.75
105
        elif state.get("state", "") == "which_story":  # Already asked about which story
106
            story_type = self.get_story(human_sentence)
107
            # If we couldn't determine the type of story (don't have such stories)
108
            if story_type is None:
109
                phrase = random.choice(self.phrases["no_stories"])
110
                status = self.status_constants["can"]
111
            else:  # Start telling the story
112
                phrase, status, attributes = self.choose_story(attributes, story_type)
113
        elif state.get("state", "") == "setup" and yes:  # User is still intrigued -> continue
114
            story_name = state.get("story", "")
115
            phrase = self.tell_punchline(story_name)
116
            status = self.status_constants["can"]
117
        elif state.get("state", "") == "setup" and no:  # User is not interested
118
            phrase = random.choice(self.phrases["no"])
119
            status = self.status_constants["cannot"]
120
        elif state.get("state", "") == "setup":  # Don't know if user is still interested
121
            story_name = state.get("story", "")
122
            phrase = self.tell_punchline(story_name)
123
            status = self.status_constants["can"]
124
            confidence = 0.8
125
        else:  # Start of a dialog
126
            phrase = random.choice(self.phrases["start_phrases"])
127
            status = self.status_constants["must"]
128
            confidence = 0.5
129
            attributes["state"] = "do_you_mind"
130
        return phrase, confidence, {}, {"short_story_skill_attributes": attributes}, {"can_continue": status}
131

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.