Exemplo n.º 1
0
 def __init__(self, *json_files):
     DialogueFlow.__init__(self,
                           'sr',
                           initial_speaker=DialogueFlow.Speaker.SYSTEM)
     self.add_state('sr', system_multi_hop=True)
     #self.add_state('shortcut', system_multi_hop=True)
     self.add_state('ur', 'ur_error', user_multi_hop=True)
     self.add_state('ur_error', 'ur_error_statement', user_multi_hop=True)
     self.add_user_transition('ur_error', 'ur_error_question',
                              natexes.question)
     self.add_state('ur_error_statement')
     self.add_system_transition(
         'ur_error_statement',
         'sr',
         '{"Yeah." "For sure." "Yep." "Right." "Sure." "Gotcha."}',
         score=1.0)
     #self.add_system_transition('ur_error_statement', 'shortcut', '#TOKLIMIT(2)', score=2.0)
     #self.add_system_transition('shortcut', 'sr', '""')
     self.add_system_transition(
         'ur_error_question', 'sr',
         '{"I\'m not sure about that." "That\'s a tough one." "I\'m not sure actually." "Huh, I don\'t know."}'
     )
     self.add_state('dinit', system_multi_hop=True)
     self.add_system_transition('dinit', 'sr', '')
     for json_file in json_files:
         DialogueFlow.knowledge_base(self).load_json_file(json_file)
Exemplo n.º 2
0
 def __init__(
     self,
     initial_state: Union[Enum, str, tuple] = "",
     initial_speaker=DialogueFlow.Speaker.USER,
     macros: Dict[str, Macro] = None,
     kb: Union[KnowledgeBase, str, List[str]] = None,
     default_system_state=None,
     end_state="__end__",
     all_multi_hop=True,
     wordnet=False,
     dialogflow=None,
 ):
     if dialogflow:
         self.df = dialogflow
     else:
         assert initial_state
         self.df = DialogueFlow(
             initial_state,
             initial_speaker,
             macros,
             kb,
             default_system_state,
             end_state,
             all_multi_hop,
             wordnet,
         )
     self.local_user_transitions = collections.defaultdict(dict)
     self.global_user_transitions = {}
     self.error_transitions = {}
     self.states = set()
     if initial_state:
         self._add_states(initial_state)
Exemplo n.º 3
0
            "exit", "stop", "nothing", "else", "bye", "good bye", "goodbye",
            "not sure"
        ],
        "ontconvenience":
        ["easy", "simple", "convenient", "good", "install", "installed"],
        "ontselection": [
            "variety", "selection", "lots", "many", "songs", "diverse",
            "options", "any", "favorite", "song", "favorites"
        ]
    }
}

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge)

# intro, spotify or not?
df.add_system_transition(State.START, State.PROMPT,
                         '"hi, do you use spotify for music streaming?"')
df.add_user_transition(State.PROMPT, State.SPOTIFY,
                       '[{yes, yea, yup, yep, i do, yeah, sometimes, sure}]')
df.add_user_transition(
    State.PROMPT, State.SYSRESYES,
    '<{yes, yea, yup, yep, i do, yeah, sometimes, sure}, {what, whats, you, your}>'
)
df.add_system_transition(
    State.SYSRESYES, State.VERSION,
    '"I use Spotify too! do you use the free version or do you use premium?"')
df.add_user_transition(
Exemplo n.º 4
0
from emora_stdm import DialogueFlow

system = DialogueFlow("start",
                      end_state="end",
                      initial_speaker=DialogueFlow.Speaker.USER)
system.load_transitions({
    "state": "start",
    "[{hi, hello}]": {
        "`Hi!`": {
            "score": 3.0,
            "error": {
                "`Bye.`": "end"
            }
        }
    },
    "error": {
        "`Bye`": "end"
    },
})

system.load_update_rules({
    "[news]": "`Coronavirus, argh!` (4.0)",
    "[{movie, movies}]": "`Avengers is a good one.` (4.0)",
    "/.*/ (0.1)": "`I'm not sure I understand.` (2.0)",
})

if __name__ == "__main__":
    system.run(debugging=True)
from emora_stdm import DialogueFlow


system = DialogueFlow('start', end_state='end', initial_speaker=DialogueFlow.Speaker.USER)
system.load_transitions({
    'state': 'start',

    '[{hi, hello}]': {

         '`Hi!`':{
             'score': 3.0,

             'error': { '`Bye.`': 'end' }
         }
    },

    'error': { '`Bye`': 'end' }
})

system.load_update_rules({
    '[news]': '`Coronavirus, argh!` (4.0)',
    '[{movie, movies}]': '`Avengers is a good one.` (4.0)',
    '/.*/ (0.1)': '`I\'m not sure I understand.` (2.0)',
})

if __name__ == '__main__':
    system.run(debugging=True)
from emora_stdm import DialogueFlow


df = DialogueFlow('root', initial_speaker=DialogueFlow.Speaker.SYSTEM)

flow = {
    'state': 'root',

    'hello': {
        '[hi]': {
            'have you seen a good movie recently':{
                '[yes]': {
                    'cool what is it':{
                        'error': 'root'
                    }
                },
                '[no]':{
                    'ok then': {
                        'error': 'root'
                    }
                }
            },
            'how are you': {
                '[good]': {
                    'thats good': {
                        'error': 'root'
                    }
                },
                '[bad]': {
                    'sorry to hear that':{
Exemplo n.º 7
0
        "dislike_adj": ["superficial", "fake", "vain", "basic", "unoriginal"],
        "time": [
            "wastes time", "waste of time", "time", "hours", "all day",
            "addictive"
        ],
        "likable":
        ["apps", "fads", "technology", "socializing", "social media"]
    }
}

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge,
                  macros={
                      "NUMBERCOMP": NUMBERCOMP(),
                      "HOURSCOMP": HOURSCOMP()
                  })

#start
df.add_system_transition(State.START, State.PROMPT, '"Do you like Instagram?"')

#if user says yes (likes Instagram)
df.add_user_transition(State.PROMPT, State.YES, "[#ONT(ontaffirmative)]")
df.add_system_transition(State.YES, State.WHYLIKE,
                         'What features do you like"?"')

# error handler for first prompt
df.set_error_successor(State.PROMPT, State.ERR_PROMPT)
df.add_system_transition(State.ERR_PROMPT, State.IMPROVE_Q,
        "thriller": [
            "creepy",
            "spooky",
            "scary",
            "exhilarating",
            "horror",
        ]
    }
}

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.S0,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge,
                  macros={
                      "SPECIFIC": SPECIFIC(),
                      "TVorMovie": TVorMovie(),
                      "REC": REC()
                  })

#  NaTex
netflix_prime = r"[!-{[#ONT(hulu)], [#ONT(disney plus)], " \
                r"[#ONT(negative)]}, {[$stream=#ONT(netflix)], [$stream=#ONT(amazon prime)]}]"
hulu = r"[!-{[#ONT(amazon prime)], [#ONT(disney plus)], [#ONT(netflix)], [#ONT(negative)]}, [$stream=#ONT(hulu)]]"
dplus = r"[!-{[#ONT(amazon prime)], [#ONT(hulu)], [#ONT(netflix)], [#ONT(negative)]}, [$stream=#ONT(disney plus)]]"

affirm = r"[!-[#ONT(negative)],[#ONT(positive)]]"
deny = r"[!-[#ONT(positive)],[#ONT(negative)]]"

pirate_own = r"[!-[#ONT(rentLibs)], [#ONT(ownTvPirate)]]"
rent = r"[!-[#ONT(ownTVPirate)], [#ONT(rentLibs)]]"
Exemplo n.º 9
0
            str += "I just don't see how he would suddenly get better."
            if (player('2019-20').minutes_played /
                    player('2019-20').games_played < 12
                    or player('2019-20').minutes_played == None):
                str += "Besides, who is this player anyways because I've never heard of him."
            return str


knowledge = KnowledgeBase()
knowledge.load_json_file("teams.json")
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge,
                  macros={
                      'news': news(),
                      'newsPlayer': newsPlayer(),
                      'newsTeam': newsTeam(),
                      'teamStats': teamStats(),
                      'playerRating': playerRating(),
                      'goodBadTrade': goodBadTrade(),
                      'tradeNews': tradeNews()
                  })

#########################
# THIS DOCUMENT IS THE SOURCE OF TRUTH FOR WHAT WE ARE DOING: https://docs.google.com/document/d/15N6Xo60IipqOknUGHxXt-A17JFOXOhMCZSMcOAyUEzo/edit
##########################

# natex expressions
dont_know = '[{' \
            'dont know,do not know,unsure,maybe,[not,{sure,certain}],hard to say,no idea,uncertain,i guess,[!no {opinion,opinions,idea,ideas,thought,thoughts,knowledge}],' \
            '[{dont,do not}, have, {opinion,opinions,idea,ideas,thought,thoughts,knowledge}],' \
            '[!{cant,cannot,dont} {think,remember,recall}]' \
Exemplo n.º 10
0
from emora_stdm import DialogueFlow

system = DialogueFlow("start", initial_speaker=DialogueFlow.Speaker.USER)
system.load_transitions({
    "state": "start",
    "error": {
        "` `": {
            "score": -1,
            "state": "start"
        }
    }
})

system.load_update_rules({
    "[news]": "`Coronavirus, argh!` (1)",
    "[{movie, movies}]": "`Avengers is a good one.` (1)",
    "/.*/ (0.1)": "`I'm not sure I understand.` (1)",
})

if __name__ == "__main__":
    system.run()
Exemplo n.º 11
0
            query_first_result = requester.search_for_artist(fav_artist_name)[0]
            artist_id = query_first_result['id']
            artist_features = requester.get_artist_avg_features(artist_id)
            # these next two lines are for testing. Remove once macro is up and running
            for key, val in artist_features:
                print(""+key+""+val)

            # TODO: build a way to turn artist feature metrics into qualitative descriptives

# TODO: create the ontology as needed
ontology = json.loads(open('ontology.json').read())

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START, initial_speaker=DialogueFlow.Speaker.SYSTEM, kb=knowledge,
                  macros={"ARTIST_QUALITIES": ARTIST_QUALITIES(),
                          "ARTIST_GENRE": ARTIST_GENRE()})

df.add_system_transition(State.START, State.RES, '"Do you listen to music?"')

df.add_user_transition(State.RES, State.YES, '[#ONT(yes)]')
df.add_user_transition(State.RES, State.NO, '[#ONT(no)]')


# Error
df.set_error_successor(State.RES, State.RES_ERROR)
df.add_system_transition(State.RES_ERROR, State.RES2, '"Sorry, I didn\'t catch that. Do you listen to music?"')
df.add_user_transition(State.RES2, State.YES, '[#ONT(yes)]')
df.add_user_transition(State.RES2, State.NO, '[#ONT(no)]')
df.set_error_successor(State.RES2, State.RES_ERROR2)
df.add_system_transition(State.RES_ERROR2, State.ERR, '"Sorry, I still didn\'t catch that. Let\'s start over."')
Exemplo n.º 12
0
                  in the natex
                  returning a set of strings replaces macro with a disjunction
                  returning a boolean will replace the macro with wildcards (True)
                  or an unmatchable character sequence (False)
                  returning an arbitrary object is only used to pass data to other macros
        """
        temp = ont_dict["ontology"]
        return random.choice(temp[args[0]])


# In[713]:

knowledge = KnowledgeBase()
knowledge.load_json(ont_dict)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge,
                  macros={'MyMacro': MyMacro(1)})

# Function to add user transition states that uses "yes" regex
yes_add()
no_add()

df.add_system_transition(
    State.START, State.START_REPLY,
    '"hi! my name is roko. i love playing video games, and its kind of the only thing i do. do you like games?"'
)
# df.add_user_transition(State.START_REPLY, State.LIKE_GAME_Y, "<$response=/(?:^|\s)(yea|ya|ye|yes|yeah|i do|i like)(?:\s|,|\.|$)/>")
# df.add_user_transition(State.START_REPLY, State.LIKE_GAME_N, "<$response={no, nope, nah, no way, i dont}>")
df.set_error_successor(State.START_REPLY, State.ERR)
df.add_system_transition(State.ERR, State.START_REPLY,
                         '"Hmm.. i only like video games"')
Exemplo n.º 13
0
        if 'industry' in vars:
            for key, value in industry_company.items():
                if key in vars['industry']:
                    return value

class posSkill(Macro):
    def run(self, ngrams, vars, args):
        if 'pos' in vars:
            for key, value in pos_skill.items():
                if key in vars['pos']:
                    return value

knowledge = KnowledgeBase()
knowledge.load_json(ind_pos)
knowledge.load_json(ind_comp)
df = DialogueFlow(State.S1, initial_speaker=DialogueFlow.Speaker.SYSTEM, kb=knowledge, macros={"placeInd": placeInd(),"indComp":indComp(),"posSkill":posSkill()})

df.add_system_transition(State.S1, State.U1, '"Where do you want to work?"')
df.add_user_transition(State.U1, State.S2a, '[$loc={new york,ny,la,los angeles,chicago,dallas,washington dc,dc,west,east,bay,san francisco,sf,houston,boston,bos,atl,atlanta,seattle,sea,san jose}]', score=1)
df.add_user_transition(State.U1, State.S2b, '[$loc={new york,ny,la,los angeles,chicago,dallas,washington dc,dc,west,east,bay,san francisco,sf,houston,boston,bos,atl,atlanta,seattle,sea,san jose}]')
df.add_user_transition(State.U1, State.S2c, '[$comp=#ONT(ontfinanc)]', score = 2)
df.add_user_transition(State.U1, State.S2d, '[$comp=#ONT(ontconsultin)]', score = 2)
df.add_user_transition(State.U1, State.S2e, '[$comp=#ONT(onttechnolog)]', score = 2)
df.add_user_transition(State.U1, State.S2f, '[$comp=#NER(org)]', score = 1)
df.add_user_transition(State.U1, State.S2g, '[{dont know,do not know,unsure,[not,{sure,certain,considered,consider,thought}],hard to say,no idea,uncertain,[!no {opinion,opinions,idea,ideas,thought,thoughts,knowledge}]}]')
df.set_error_successor(State.U1, error_successor=State.ERR1)

df.add_system_transition(State.S2a, State.U2a, '[!Sure"." $loc is a great place to work"!" There are a lot of #placeInd companies there"." What industry are you interested in"?"]')
df.add_system_transition(State.S2b, State.U2a, '[!I also think $loc is a great place to work"!" There are a lot of #placeInd companies there"." What industry are you interested in"?"]')
df.add_system_transition(State.S2g, State.U2a, '"Oh it is fine that you have not decide where to work at. Do you have an industry that you are interested in?"')
df.add_system_transition(State.S2c, State.U3a, '[!$comp is a great bank"." What position in $comp are you interested in"?"]')
Exemplo n.º 14
0
from emora_stdm import DialogueFlow
import json

df = DialogueFlow('start')
df.knowledge_base().load_json_file('ontology_example.json')
df.load_transitions({
    'state': 'start',
    '`What is your favorite animal?`': {
        '[#ONT(mammal)]': {
            '`I think mammals are cool too!`': 'start'
        },
        '[#ONT(reptile)]': {
            '`Reptiles are cool.`': 'start'
        },
        '[$animal=#ONT(animal)]': {
            'score': 0.5,
            '`I like` $animal `too.`': 'start'
        },
        'error': {
            '`I\'ve never heard of that animal.`': 'start'
        }
    }
})

if __name__ == '__main__':
    df.run()
Exemplo n.º 15
0
    SONGARTIST1 = auto()
    ROCKCONCERT = auto()
    ROCKTICKETS = auto()



sp_requester = requester()
ontology = json.loads(open('ontology.json').read())



knowledge = KnowledgeBase()
knowledge.load_json(ontology)


df = DialogueFlow(State.START, initial_speaker=DialogueFlow.Speaker.SYSTEM, kb=knowledge)

df.add_system_transition(State.START, State.GENREQUESTION, '"What\'s your favorite music genre?"')

df.add_user_transition(State.GENREQUESTION, State.ROCK, '[{rock, Rock}]')
df.set_error_successor(State.GENREQUESTION, State.ROCK_ERROR)
# Error
df.add_system_transition(State.ROCK_ERROR, State.GENREQUESTION2, '"Sorry, I didn\'t catch that. What\'s your favorite music genre?"')
df.add_user_transition(State.GENREQUESTION2, State.ROCK, '[{rock, Rock}]')
df.set_error_successor(State.GENREQUESTION2, State.ROCK_ERROR2)
df.add_system_transition(State.ROCK_ERROR2, State.ERR, '"Sorry, I still didn\'t catch that. Let\'s start over."')

# Turn 1
df.add_system_transition(State.ROCK, State.ROCKDYING, '"So you like rock music?! I don\'t know about that."'
                                                      '"I heard the genre is dying out; wouldn\'t you agree?"')
df.add_user_transition(State.ROCKDYING, State.ROCKAGREE, '[#ONT(yes)]')
Exemplo n.º 16
0
from emora_stdm import DialogueFlow, CompositeDialogueFlow

A = DialogueFlow("start")
A.load_transitions({
    "state": "start",
    "`Let's talk about books!`": {
        "error": {
            "`What's your favorite book?`": {
                "error": {
                    "`Cool!`": "end",
                    "`Okay.`": "movies:movie_question"
                }
            }
        }
    },
})

B = DialogueFlow("start")
B.load_transitions({
    "`Let's talk about movies!`": {
        "state": "start",
        "error": {
            "state": "movie_question",
            "`What is your favorite movie?`": {
                "error": {
                    "`That's a good one!`": {}
                }
            },
        },
    }
})
Exemplo n.º 17
0
from emora_stdm import DialogueFlow

chatbot = DialogueFlow('start')
transitions = {
    'state': 'start',
    '"Hello. How are you?"': {
        '[{good, okay, fine}]': {
            '"Good. I am doing well too."': {
                'error': {
                    '"See you later!"': 'end'
                }
            }
        },
        'error': {
            '"Well I hope your day gets better!"': {
                'error': {
                    '"Bye!"': 'end'
                }
            }
        }
    }
}
chatbot.load_transitions(transitions)

chatbot = DialogueFlow('start')
transitions = {
    '"Hello."': {
        '#INT(Hi! How are you?)': {
            '"Good. How are you?"': {
                '[{good, great, okay}]': {
Exemplo n.º 18
0
            "puzzle", "puzzling", "strange"
        ],
        "philosophical": ["philosophical", "philosophy", "think"],
        "political": ["political", "politics", "governments"],
        "satire": ["satire", "satirical", "ironic", "irony", "parody"],
        "science fiction": ["science fiction", "sci-fi"],
        "thriller": ["thriller", "scary"],
        "western": ["western", "old west", "cowboy", "desert"],
        "kids": ["kids", "children", "family", "innocent"]
    }
}

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge)

df.add_system_transition(
    State.START, State.t0,
    '"Would you like to hear some suggestions of fun activities to try?"')

df.add_user_transition(State.t0, State.t1, r"[#ONT(yes)]")
df.add_user_transition(State.t0, State.a0, r"[#ONT(no)]")
df.set_error_successor(State.t0, State.a1)

df.add_system_transition(
    State.t1, State.t2,
    '"You should try making some focaccia bread! I recommend topping it with '
    'roasted red pepper and garlic. Would you like to hear another '
    'suggestion?"')
Exemplo n.º 19
0
class DFEasyFilling:
    def __init__(
        self,
        initial_state: Union[Enum, str, tuple] = "",
        initial_speaker=DialogueFlow.Speaker.USER,
        macros: Dict[str, Macro] = None,
        kb: Union[KnowledgeBase, str, List[str]] = None,
        default_system_state=None,
        end_state="__end__",
        all_multi_hop=True,
        wordnet=False,
        dialogflow=None,
    ):
        if dialogflow:
            self.df = dialogflow
        else:
            assert initial_state
            self.df = DialogueFlow(
                initial_state,
                initial_speaker,
                macros,
                kb,
                default_system_state,
                end_state,
                all_multi_hop,
                wordnet,
            )
        self.local_user_transitions = collections.defaultdict(dict)
        self.global_user_transitions = {}
        self.error_transitions = {}
        self.states = set()
        if initial_state:
            self._add_states(initial_state)

    def get_dialogflow(self):
        df_backup = copy.deepcopy(self.df)
        self._compile_dialogflow()
        result_df = self.df
        self.df = df_backup
        return result_df

    def add_global_user_transition(self, state_to, intent, importance=1.0):
        if not utils.check_intent(intent):
            raise Exception("Unknown intent type")
        elif state_to in self.global_user_transitions:
            raise Exception(f"{state_to} is already defined")
        else:
            self._add_states(state_to)
            self.global_user_transitions[state_to] = {
                "intent": intent,
                "importance": importance
            }

    def add_user_transition(self,
                            state_from,
                            state_to,
                            intent,
                            importance=1.0):
        if not utils.check_intent(intent):
            raise Exception("Unknown intent type")
        elif state_to in self.local_user_transitions[state_from]:
            raise Exception(f"{state_to} is already defined")
        else:
            self._add_states(state_from, state_to)
            self.local_user_transitions[state_from][state_to] = {
                "intent": intent,
                "importance": importance
            }

    def add_system_transition(self, state_from, state_to, nlg):
        self._add_states(state_from, state_to)
        if isinstance(nlg, (str, NatexNLG)):
            self.df.add_system_transition(state_from, state_to, nlg)

        elif isinstance(nlg, (set, list)):
            nlg = utils.strs2natex_nlg(nlg)
            self.df.add_system_transition(state_from, state_to, nlg)

        elif callable(nlg):  # nlg(vars=vars) -> str

            class NLGMacro(Macro):
                def run(self, ngrams, vars, args):
                    try:
                        text = nlg(vars=vars)
                        text = utils.clean_text(text)
                        return text
                    except Exception as exc:
                        sentry_sdk.capture_exception(exc)
                        logger.exception(exc)
                        return ""

            macros_name = uuid.uuid4().hex

            self.df.add_system_transition(
                state_from,
                state_to,
                NatexNLG(
                    f"#{macros_name}()",
                    macros={f"{macros_name}": NLGMacro()},
                ),
            )

        else:
            raise Exception("Unknown nlg type")

    def set_error_successor(self, state_from, state_to):
        # self._add_states(state_from, state_to)
        # self.df.set_error_successor(state_from, state_to)
        self.error_transitions[state_from] = state_to
        pass

    def add_user_serial_transitions(self,
                                    state_from,
                                    states_to,
                                    default_importance=1.0):
        # order in states_to is important
        for state_to, condition in states_to.items():
            intent, importance = ((condition[0], condition[1]) if isinstance(
                condition, (list, tuple)) else (condition, default_importance))
            self.add_user_transition(
                state_from,
                state_to,
                intent,
                importance,
            )

    def add_global_user_serial_transitions(self,
                                           states_to,
                                           default_importance=1.0):
        # order in states_to is important
        for state_to, condition in states_to.items():
            intent, importance = ((condition[0], condition[1]) if isinstance(
                condition, (list, tuple)) else (condition, default_importance))
            self.add_global_user_transition(
                state_to,
                intent,
                importance,
            )

    def _add_user_transitions(self, state_from, states_to):
        # order in states_to is important
        condition_sequence = []
        for state_to, condition in states_to.items():
            condition_sequence += [condition]
            self._add_user_transition(
                state_from,
                state_to,
                utils.create_intent_sequence(condition_sequence[:-1],
                                             condition_sequence[-1:]),
            )

    def _add_user_transition(self, state_from, state_to, intent):
        if isinstance(intent, (str, NatexNLU)):
            self.df.add_user_transition(state_from, state_to, intent)

        elif isinstance(intent, (set, list)):
            intent = utils.disjunction_natex_nlu_strs(intent)
            self.df.add_user_transition(state_from, state_to, intent)

        elif callable(intent):
            if isinstance(intent,
                          MindfulDataFileBot):  # using programy as intent

                def handler(ngrams, vars):
                    # TODO: n turns
                    return intent([ngrams.text()])

            else:
                handler = intent  # intent(ngrams=ngrams, vars=vars) -> bool

            class IntentMacro(Macro):
                def run(self, ngrams, vars, args):
                    try:
                        is_match = handler(ngrams=ngrams, vars=vars)
                    except Exception as exc:
                        sentry_sdk.capture_exception(exc)
                        logger.exception(exc)
                        is_match = False
                    if is_match:
                        return ngrams.text()
                    else:
                        return ""

            macros_name = uuid.uuid4().hex
            self.df.add_user_transition(
                state_from,
                state_to,
                NatexNLU(
                    f"#{macros_name}()",
                    macros={f"{macros_name}": IntentMacro()},
                ),
            )

        else:
            raise Exception("Unknown intent type")

    def _compile_dialogflow(self):
        transitions = {
            state_from: copy.deepcopy(self.global_user_transitions)
            for state_from in self._get_usr_states()
        }
        logger.debug(f"transitions={transitions}")
        logger.debug(f"self.states={self.states}")
        logger.debug(
            f"self.local_user_transitions={self.local_user_transitions}")
        logger.debug(f"self._get_usr_states()={self._get_usr_states()}")

        for state_from in transitions:
            user_transition_from = transitions[state_from]
            user_transition_from.update(
                self.local_user_transitions.get(state_from, {}))
            ordered_states_to = sorted(
                user_transition_from,
                key=lambda state_to: -user_transition_from[state_to].get(
                    "importance", 1.0),
            )
            state_to2intent = {
                state_to: user_transition_from[state_to]["intent"]
                for state_to in ordered_states_to
            }
            self._add_user_transitions(state_from, state_to2intent)

        for state_from, state_to in self.error_transitions.items():
            self.df.set_error_successor(state_from, state_to)

    def _add_states(self, *args):
        for state in args:
            text_state = str(state[1]) if isinstance(state,
                                                     (tuple,
                                                      list)) else str(state)
            text_prefix = "State."
            prefix_len = len(text_prefix)
            if not (text_prefix == text_state[:prefix_len]):
                raise Exception(f"state {state} has to be from State class")
            if not (text_state[prefix_len:prefix_len + 3] in [
                    "SYS",
                    "USR",
            ]):
                raise Exception(
                    f"state {state} has to contain SYS or USR in of the begining"
                )
            self.states.add(state)

    def _get_usr_states(self):
        text_prefix = "State.USR"
        prefix_len = len(text_prefix)
        sys_states = []
        for state in self.states:
            text_state = str(state[1]) if isinstance(state,
                                                     (tuple,
                                                      list)) else str(state)
            if text_state[:prefix_len] == text_prefix:
                sys_states.append(state)
        return sys_states
Exemplo n.º 20
0
            "price", "affordable"
        ],
        "macbook air_ft": ["display", "keyboard", "trackpad", "thin", "sleek"],
        "hp laptop": ["hp"],
        "surface laptop": ["surface"],
        "phone_types":
        ["iphone", "apple", "pixel", "android", "blackberry", "samsung"],
        "chromebook laptop": ["chromebook"],
        "apple laptop": ["mac", "macbook", "apple"]
    }
}

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge)

# ask what phone does the user have
df.add_system_transition(State.START, State.turn_1,
                         '"Hi, what phone do you have?"')

# get answer from the user
df.add_user_transition(State.turn_1, State.iphone,
                       r"[$phone=#ONT(apple phone)]")
df.add_user_transition(State.turn_1, State.samsung,
                       r"[$phone=#ONT(samsung phone)]")
df.add_user_transition(State.turn_1, State.android,
                       r"[$phone=#ONT(google phone)]")
df.add_user_transition(State.turn_1, State.nophone, r"[#ONT(n)]")
Exemplo n.º 21
0
################################
# Modify ont_dict for Quiz2 Task 3
################################
ont_dict = {
    "ontology": {
        "ontamphibian": ["frog", "salamander"],
        "ontyes": ["yea", "yeah"]
    }
}

################################
knowledge = KnowledgeBase()
knowledge.load_json(ont_dict)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge,
                  macros={"VERSION": VERSION()})

df.add_system_transition(State.START, State.PROMPT, '"Enter an animal"')

#df.add_user_transition(State.PROMPT, State.MAMMAL, '[$reason=/.*/]')

df.add_user_transition(State.PROMPT, State.MAMMAL, time_natex)

df.add_system_transition(State.MAMMAL, State.BIRD,
                         r'[!oh are you using #VERSION"?"]')

df.add_system_transition(State.MAMMAL, State.PROMPT,
                         '[! $animal " is a mammal, enter another animal"]')
df.add_system_transition(State.BIRD, State.PROMPT,
                         '[! $animal "is a bird, enter another animal"]')
Exemplo n.º 22
0
        device_ages = {
            "vive":"3",
            "cardboard":"5",
            "index":"1",
            "rift":"3",
        }

        model = args[0]

        return device_ages.get(model)

natex_device_age = NatexNLG('[!$device "is" #MyMacro2($device) "years old. Have you tried other brands?"]', macros={'MyMacro2': MyMacro2()})

knowledge = KnowledgeBase()
knowledge.load_json(ont_dict)
df = DialogueFlow(State.START, initial_speaker=DialogueFlow.Speaker.SYSTEM, kb=knowledge)

df.add_system_transition(State.START, State.USED_PROMPT, '"Let\'s talk about virtual reality! Have you used VR before?"')

df.add_system_transition(State.USED_N, State.UNFAMILIAR, '[!"VR is a new immersive video game technology. Do you play video games?"]')

df.add_user_transition(State.UNFAMILIAR, State.PLAY_VG, "[$response=#ONT(ontyes)]")
df.add_user_transition(State.UNFAMILIAR, State.NO_VG, "[$response=#ONT(ontno)]")
df.add_system_transition(State.PLAY_VG, State.FAVE_GAME_NOVR, '[!"Awesome! What\'s your favorite game?"]')
df.add_user_transition(State.FAVE_GAME_NOVR, State.ACCEPT_GAME, "[$game=#ONT(ontgame)]")
df.add_system_transition(State.ACCEPT_GAME, State.END, '"Nice choice! Since you like games I suggest you try VR. Bye for now!"')

df.add_user_transition(State.FAVE_GAME_Q, State.FAV_GAME_Y, "[$game=#ONT(ontgame)]")

df.add_user_transition(State.USED_PROMPT, State.BRAND, "[$brand=#ONT(ontbrand)]", score=2)
df.add_user_transition(State.USED_PROMPT, State.GAME, "[$game=#ONT(ontgame)]", score=2)
Exemplo n.º 23
0

################################

################################
# Modify ont_dict for Quiz2 Task 3
################################

ont_dict = {"ontology": {"amphibian": ["frog", "salamander"]}}

################################

knowledge = KnowledgeBase()
knowledge.load_json(ont_dict)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge)

df.add_system_transition(State.START, State.PROMPT, '"Enter an animal"')
df.add_user_transition(State.PROMPT, State.MAMMAL, "[$animal={cat,dog}]")
df.add_user_transition(State.PROMPT, State.BIRD,
                       "[$animal={parrot,dove,crow}]")
df.add_user_transition(State.PROMPT, State.REPTILE,
                       "[$animal={snake,lizard,turtle,alligator}]")
df.add_user_transition(State.PROMPT, State.AMPHIBIAN,
                       "[$animal=#ONT(amphibian)]")
df.add_system_transition(State.MAMMAL, State.PROMPT,
                         '[! $animal " is a mammal, enter another animal"]')
df.add_system_transition(State.BIRD, State.PROMPT,
                         '[! $animal "is a bird, enter another animal"]')
df.add_system_transition(State.REPTILE, State.PROMPT,
Exemplo n.º 24
0
            "limericks", "Limericks", "acrostic poem", "Acrostic poem",
            "Acrostic poetry", "acrostic poetry", "epic", "Epic", "epics",
            "Epics", "ode", "Ode", "odes", "Odes", "sonnet", "Sonnet",
            "sonnets", "Sonnets", "song", "Songs", "Song", "songs", "rap",
            "Rap", "quatrain", "Quatrain", "quatrains", "Quatrains", "monody",
            "Monody", "monodies", "Monodies", "slam", "slam poem",
            "slam poetry", "funny", "Funny", "humorous", "Humorous", "love",
            "Love", "longing", "Lust", "about", "About", "on", "On"
        ]
    }
}

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge)

# Turn 1
# Natex
poet_name = r"[$fave_poet=#ONT(poets)]"
favorite = r"[$fave_poet={[Ezra Pound], [ezra pound], [pound], [Pound]}]"
none = r"[#ONT(ambiguous)]"

df.add_system_transition(
    State.START, State.INTRO,
    '"Hi, I\'m a chatbot and I\'m designed to talk about poetry '
    'with humans. \n'
    'Enough about me now though, tell me, who is your '
    'favorite poet?"')
df.add_user_transition(State.INTRO, State.POUND, favorite)
Exemplo n.º 25
0
        ],
        "outgoing":
        ["outgoing", "extraverted", "sociable", "social", "friendly", "warm"],
        "shy": ["shy", "intraverted", "guarded", "loner"],
        "polite": ["polite", "manners", "decent"],
        "conceited": [
            "conceited", "overconfident", "arrogant", "full of",
            "narcissistic", "egotistic", "egotistical", "selfish"
        ],
        "beautiful": ["gorgeous", "pretty", "hot", "sexy"]
    }
}

kb = KnowledgeBase()
kb.load_json(kb_dict)
df = DialogueFlow(initial_state="root", kb=kb)

root = 'root'
end = 'end'
df.add_state(root, error_successor=root, memory=0)
df.add_state(end, error_successor=end)
df.add_system_transition(root, end, 'I have no nonrepetitive options', score=0)

# S: Who do you live with?
root = 'root'
df.add_state('opening live with', error_successor=root)
df.add_system_transition(root, 'opening live with',
                         '[!#GATE() "So, who do you live with?"]')

df.add_user_transition(
    'opening live with', root,
Exemplo n.º 26
0
            "quesadilla", "enchilada", "fajita", "gordita", "pozole", "kmchi",
            "bulgogi", "japchae", "bibimbap", "ddukbokki", "samgyeopsal",
            "jjajangmyeon", "kimbap", "doenjang jjigae"
        ],
        "sour": ["gelato", "sweet and sour pork", "caldo de queso", "kimchi"]
    }
}

knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge,
                  macros={
                      "RANDCUISINE": RANDCUISINE(),
                      "CHECK": CHECK(),
                      "INFLUENCE": INFLUENCE(),
                      "REASON": REASON(),
                      'DISHES': DISHES(),
                      'RANDFOOD': RANDFOOD()
                  })

# S0
df.add_system_transition(State.START, State.U0,
                         '"What kind of cuisine do you like?"')
df.add_user_transition(State.U0, State.S1, '$cuisine=[#ONT(ontCuisines)]')
df.set_error_successor(State.U0, State.S0ERR)
df.add_system_transition(State.S0ERR, State.U1, '#RANDCUISINE')

# S1
df.add_system_transition(
Exemplo n.º 27
0
class COMPCHAR(Macro):
    def run(self, ngrams, vars, args):
        if 'notchosen' in vars:
            a = ""
            for key in comp_char_dict:
                if key in vars['notchosen']:
                    a = comp_char_dict[key]
        return a


df = DialogueFlow(State.S1,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  macros={
                      "elabCon": elabCon(),
                      "elabPro": elabPro(),
                      "EXPLfield": EXPLfield(),
                      "YEAR": YEAR(),
                      "company": company(),
                      "choosecomp": chooseComp(),
                      "COMPCHAR": COMPCHAR()
                  })

pro = r"[$pro={secure,security,safe,safety, [{accident,accidents}, /reduce[sd]?|decrease[sd]?/], [{few,fewer,reduce,reduces,reduced}, {accident,accidents}], /disable[d]?|disability/, traffic,traffics, environment,environmental,free,attention,attentions}]"
con = "[$con={</more|increase[d]?|increasing|/, /car[s]?|people/>,hack,hacked,hacker,crash,crashed,crashing,moral,morality,immoral,immorality,ethic, expensive,price,job,jobs, /like[s]?\sdriving/, /regulate[s]?|regulation|law[s]?|act[s]?/,insecure,insecurity,danger,dangerous,not secure,not safe}]"
con1 = r'[{no, not really, nah}, [$con={danger, not safe}]]'
procon = "{[$pro={/economic[s]?|economy\s?(benefit[s]?)?/, /secure|security/, [/accident[s]?/, /reduce[d]?|decrease[sd]?|cut\sdown/], [/few|fewer/, /accident[s]?/], /disable[d]?|disability/, </traffic|traffics/, /quick|quicker|fast|faster|better|good|improve[d]?|solve[d]?/>, /environment|environmental/, free}], $con={</more|increase[d]?|increasing|/, /car[s]?|people/>, {hack,hacked,hacker,crash,crashed,crashing}, {moral,morality,immoral,immorality}, {expensive,price}, {job,jobs}, /like[s]?\sdriving/, /regulate[s]?|regulation|law[s]?|act[s]?/}]}"

df.add_system_transition(State.S1, State.U1, r'"Do you drive?"')

df.add_user_transition(State.U1, State.S2a,
                       r'[{yes, yeah, yep, yea, ye, of course}]')
Exemplo n.º 28
0
knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.S0,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge,
                  macros={
                      "syn_det": syn_det(),
                      "fave_games": fave_games(),
                      "SPECIFIC1a": SPECIFIC1a(),
                      "SPECIFIC2a": SPECIFIC2a(),
                      "SPECIFIC2b": SPECIFIC2b(),
                      "SPECIFIC3a": SPECIFIC3a(),
                      "SPECIFIC3b": SPECIFIC3b(),
                      "GENRE_OPINION": GENRE_OPINION(),
                      "GENRE_RECOMMENDER": GENRE_RECOMMENDER(),
                      "like_macro": like_macro(),
                      "dislike_macro": dislike_macro(),
                      "game_desc": game_desc(),
                      "game_catcher": game_catcher(),
                      "game_catcher_parttwo": game_catcher_parttwo(),
                      "list_items_one": list_items_one(),
                      "list_items_two": list_items_two(),
                      "explain_response": explain_response(),
                      "genre_pivot": genre_pivot(),
                      "genre_pivot_learning": genre_pivot_learning(),
                      "list_items_two": list_items_two(),
                      "explain_response": explain_response(),
                      "genre_pivot": genre_pivot(),
                      "metaComp": metaComp()
                  })

### Main Prompt - Do you play video games?
Exemplo n.º 29
0

# ontology
ontology = {
    "ontology": {
        "non_home_locations": [
            "work", "office", "lab", "class", "lecture", "meeting", "travel",
            "school"
        ]
    }
}
# start
knowledge = KnowledgeBase()
knowledge.load_json(ontology)
df = DialogueFlow(State.START,
                  initial_speaker=DialogueFlow.Speaker.SYSTEM,
                  kb=knowledge)

# desktop or laptop
df.add_system_transition(
    State.START, State.NAME_Q,
    '"hello, I am Emily, a virtual chatbot, what is your name? (Please simply type your name.)"'
)
df.add_user_transition(State.NAME_Q, State.NAME_R, '[$name=/.*/]')
df.add_system_transition(State.NAME_R, State.COM_Q,
                         '[!"Hi"$name", do you have a computer?"]')
df.add_user_transition(State.COM_Q, State.COM_NO, '[{No,no,not,nah,Nah,N,n}]')
df.add_system_transition(
    State.COM_NO, State.COM_Q, '"Well, you should get a computer.'
    '\n   Here are some websites where you can buy a comptuer:'
    '\n   www.bestbuy.com'
Exemplo n.º 30
0
from emora_stdm import DialogueFlow, CompositeDialogueFlow

A = DialogueFlow('start')
A.load_transitions({
    'state': 'start',
    '`Let\'s talk about books!`': {
        'error': {
            '`What\'s your favorite book?`': {
                'error': {
                    '`Cool!`': 'end',
                    '`Okay.`': 'movies:movie_question'
                }
            }
        }
    }
})

B = DialogueFlow('start')
B.load_transitions({
    '`Let\'s talk about movies!`': {
        'state': 'start',
        'error': {
            'state': 'movie_question',
            '`What is your favorite movie?`': {
                'error': {
                    '`That\'s a good one!`': {}
                }
            }
        }
    }
})