def test_serialization(): df1 = DialogueFlow('A', initial_speaker=DialogueFlow.Speaker.USER) df1.add_state('A', 'X') df1.add_state('X') df1.add_state('C', 'D') df1.add_state('D') df1.add_user_transition('A', 'D', '$fruit=apple dog') df1.add_system_transition('X', 'C', 'banana catfish') df1.add_system_transition('D', 'A', 'dog apple') #df1.add_system_transition('X', ('movie', 'Y'), 'movie') #df1.run(debugging=True) df2 = DialogueFlow('A', initial_speaker=DialogueFlow.Speaker.USER) df2.add_state('A', 'X') df2.add_state('X') df2.add_state('C', 'D') df2.add_state('D') df2.add_user_transition('A', 'D', '$state=alaska down') df2.add_state(('SYSTEM', 'topic_err'), global_nlu='back') df2.add_state(('one', 'X'), global_nlu='dog') cdf = CompositeDialogueFlow('start', 'topic_err', 'topic', initial_speaker=DialogueFlow.Speaker.USER) cdf.add_component(df1, 'one') cdf.add_component(df2, 'two') cdf.add_state('start', 'greet') cdf.add_state('greet') cdf.add_state('topic', 'topic_err') cdf.add_state('topic_err') cdf.add_system_transition('topic_err', 'topic', 'what do you want to discuss') cdf.add_system_transition('greet', 'topic', 'hello') cdf.add_user_transition('topic', ('one', 'X'), '$animal={catfish, dog}') cdf.add_user_transition('topic', ('two', 'X'), '$item={alaska, bark, down}') cdf.add_user_transition(('one', 'A'), ('SYSTEM', 'topic_err'), 'back') cdf.new_turn() cdf.user_turn('hello') assert cdf.system_turn() == 'hello' s = cdf.serialize() cdf.new_turn() cdf.deserialize(s) cdf.user_turn('bark') assert cdf.controller_name() == 'two' assert cdf.system_turn().strip() == 'what do you want to discuss' s = cdf.serialize() cdf.new_turn() cdf.deserialize(s) cdf.user_turn('catfish') assert cdf.controller_name() == 'one'
def test_serialization(): df1 = DialogueFlow("A", initial_speaker=DialogueFlow.Speaker.USER) df1.add_state("A", "X") df1.add_state("X") df1.add_state("C", "D") df1.add_state("D") df1.add_user_transition("A", "D", "$fruit=apple dog") df1.add_system_transition("X", "C", "banana catfish") df1.add_system_transition("D", "A", "dog apple") # df1.add_system_transition('X', ('movie', 'Y'), 'movie') # df1.run(debugging=True) df2 = DialogueFlow("A", initial_speaker=DialogueFlow.Speaker.USER) df2.add_state("A", "X") df2.add_state("X") df2.add_state("C", "D") df2.add_state("D") df2.add_user_transition("A", "D", "$state=alaska down") df2.add_state(("SYSTEM", "topic_err"), global_nlu="back") df2.add_state(("one", "X"), global_nlu="dog") cdf = CompositeDialogueFlow( "start", "topic_err", "topic", initial_speaker=DialogueFlow.Speaker.USER ) cdf.add_component(df1, "one") cdf.add_component(df2, "two") cdf.add_state("start", "greet") cdf.add_state("greet") cdf.add_state("topic", "topic_err") cdf.add_state("topic_err") cdf.add_system_transition("topic_err", "topic", "what do you want to discuss") cdf.add_system_transition("greet", "topic", "hello") cdf.add_user_transition("topic", ("one", "X"), "$animal={catfish, dog}") cdf.add_user_transition("topic", ("two", "X"), "$item={alaska, bark, down}") cdf.add_user_transition(("one", "A"), ("SYSTEM", "topic_err"), "back") cdf.new_turn() cdf.user_turn("hello") assert cdf.system_turn() == "hello" s = cdf.serialize() cdf.new_turn() cdf.deserialize(s) cdf.user_turn("bark") assert cdf.controller_name() == "two" assert cdf.system_turn().strip() == "what do you want to discuss" s = cdf.serialize() cdf.new_turn() cdf.deserialize(s) cdf.user_turn("catfish") assert cdf.controller_name() == "one"
def test_composite_df_with_error_in_composite(): #NOT A VALID TEST: MODIFY TO MAKE ERROR IN COMPOSITE DIALOGUE FLOW df1 = DialogueFlow('A', initial_speaker=DialogueFlow.Speaker.USER) df1.add_state('A', 'X') df1.add_state('X') df1.add_state('C', 'D') df1.add_state('D') df1.add_user_transition('A', 'D', '$fruit=apple dog') df1.add_system_transition('X', 'C', 'banana catfish') df1.add_system_transition('D', 'A', 'dog apple') #df1.add_system_transition('X', ('movie', 'Y'), 'movie') #df1.run(debugging=True) df2 = DialogueFlow('A', initial_speaker=DialogueFlow.Speaker.USER) df2.add_state('A', 'X') df2.add_state('X') df2.add_state('C', 'D') df2.add_state('D') df2.add_user_transition('A', 'D', '$state=alaska down') df2.add_state(('SYSTEM', 'topic_err'), global_nlu='back') df2.add_state(('one', 'X'), global_nlu='dog') cdf = CompositeDialogueFlow('start', 'topic_err', 'topic', initial_speaker=DialogueFlow.Speaker.USER) cdf.add_component(df1, 'one') cdf.add_component(df2, 'two') cdf.add_state('start', 'greet') cdf.add_state('greet') cdf.add_state('topic', 'topic_err') cdf.add_state('topic_err') cdf.add_system_transition('topic_err', 'topic', 'what do you want to discuss') cdf.add_system_transition('greet', 'topic', 'hello') cdf.add_user_transition('topic', ('one', 'X'), '$animal={catfish, dog}') cdf.add_user_transition('topic', ('two', 'X'), '$item={alaska, bark, down}') cdf.add_user_transition(('one', 'A'), ('SYSTEM', 'topic_err'), 'back') cdf.user_turn('hello') assert cdf.system_turn() == 'hello' cdf.user_turn('bark') assert cdf.controller_name() == 'two' assert cdf.system_turn().strip() == 'what do you want to discuss' cdf.user_turn('catfish') assert cdf.controller_name() == 'one'
def test_composite_df_with_error_in_composite(): # NOT A VALID TEST: MODIFY TO MAKE ERROR IN COMPOSITE DIALOGUE FLOW df1 = DialogueFlow("A", initial_speaker=DialogueFlow.Speaker.USER) df1.add_state("A", "X") df1.add_state("X") df1.add_state("C", "D") df1.add_state("D") df1.add_user_transition("A", "D", "$fruit=apple dog") df1.add_system_transition("X", "C", "banana catfish") df1.add_system_transition("D", "A", "dog apple") # df1.add_system_transition('X', ('movie', 'Y'), 'movie') # df1.run(debugging=True) df2 = DialogueFlow("A", initial_speaker=DialogueFlow.Speaker.USER) df2.add_state("A", "X") df2.add_state("X") df2.add_state("C", "D") df2.add_state("D") df2.add_user_transition("A", "D", "$state=alaska down") df2.add_state(("SYSTEM", "topic_err"), global_nlu="back") df2.add_state(("one", "X"), global_nlu="dog") cdf = CompositeDialogueFlow( "start", "topic_err", "topic", initial_speaker=DialogueFlow.Speaker.USER ) cdf.add_component(df1, "one") cdf.add_component(df2, "two") cdf.add_state("start", "greet") cdf.add_state("greet") cdf.add_state("topic", "topic_err") cdf.add_state("topic_err") cdf.add_system_transition("topic_err", "topic", "what do you want to discuss") cdf.add_system_transition("greet", "topic", "hello") cdf.add_user_transition("topic", ("one", "X"), "$animal={catfish, dog}") cdf.add_user_transition("topic", ("two", "X"), "$item={alaska, bark, down}") cdf.add_user_transition(("one", "A"), ("SYSTEM", "topic_err"), "back") cdf.user_turn("hello") assert cdf.system_turn() == "hello" cdf.user_turn("bark") assert cdf.controller_name() == "two" assert cdf.system_turn().strip() == "what do you want to discuss" cdf.user_turn("catfish") assert cdf.controller_name() == "one"
"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}]') df.add_user_transition(State.U1, State.S2b, r'[{no, not really, nah}]') df.add_system_transition(State.S2a, State.U2a, r'"Cool, what car do you have?"') df.add_system_transition( State.S2b, State.U2b, r'"Do you plan to learn driving at some point in the future?"') df.add_user_transition(State.U2a, State.S3a, r'#NOT(tesla)') df.add_user_transition(State.U2a, State.S3b, r'[{tesla, tesla}]') df.add_user_transition( State.U2b, State.S3c, r'[{yes, yeah, yep, yea, ye, of course, sure, why not}]') df.add_user_transition(State.U2b, State.S3d, r'[{no, not really, nah, /don\'t/}]')
'sorry to hear that':{ 'error': 'root' } } } }, '[how, you]': { 'good': { 'error': 'root' } } } } df.load_transitions(flow, DialogueFlow.Speaker.SYSTEM) df.state_settings('root').update(system_multi_hop=True) df.add_state('recovery_question', global_nlu='[!{do, who, what, when, where, why, how, is, can, should}, /.*/]') df.add_system_transition('recovery_question', 'root', '"Hmm.. I\'m not sure."') df.add_user_transition('x', 'y', '#ANY($myvar=something, $other=somethingelse) [hello]') while True: df.system_turn() v = input() var, val = v.split('=') df.vars().update({var: val}) df.user_turn(input()) if __name__ == '__main__': df.run(debugging=True)
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, '"I see. How do you think Instagram can improve?"') ##4 different states depending on what part of speech the feature is df.add_user_transition(State.WHYLIKE, State.FEATN, "[$feat=#ONT(feature_noun)]") df.add_system_transition( State.FEATN, State.YN, 'Do you like the [! $feat "feature more than on Facebook?"]')
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
"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? df.add_system_transition(State.S0, State.gU0, '"Do you play video games?" $empty=""') df.add_user_transition(State.gU0, State.gS1d, '[$word=#ONT(dislike), $dislike=/.*/]') df.add_user_transition(State.gU0, State.gS1a, '[#ONT(positive)]', score=2.0) df.add_user_transition(State.gU0, State.gS1b, '{[#ONT(negative), -#ONT(positive)], dontknow}', score=3.0) df.add_user_transition(State.gU0, State.gS1c, '[[$word=#ONT(like), $like=/.*/], -#ONT(positive)]') df.add_user_transition(State.gU0, State.fS1b, general, score=3.0) df.add_user_transition(State.gU0, State.fS1d, '[{$specG=#ONT(specificGame)}]', score=3.0) df.set_error_successor(State.gU0, State.mS0) ### Negative Response
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) df.add_user_transition(State.INTRO, State.REC_POET, poet_name) df.add_user_transition(State.INTRO, State.NONE, none) df.set_error_successor(State.INTRO, State.UNREC_POET) # Turn 2 # Natex alienation = r"[$theme=#ONT(alienation)]" love = r"[$theme=#ONT(love)]" death = r"[$theme=#ONT(death)]" time = r"[$theme=#ONT(time)]" nature = r"[$theme=#ONT(nature)]" happy = r"[$theme=#ONT(happy)]" unknown = r"[#ONT(ambiguous)]" more = r"[#ONT(more-themes)]" identity = r"[#ONT(identity)]"
}, "[how, you]": { "good": { "error": "root" } }, }, } df.load_transitions(flow, DialogueFlow.Speaker.SYSTEM) df.state_settings("root").update(system_multi_hop=True) df.add_state( "recovery_question", global_nlu= "[!{do, who, what, when, where, why, how, is, can, should}, /.*/]", ) df.add_system_transition("recovery_question", "root", '"Hmm.. I\'m not sure."') df.add_user_transition("x", "y", "#ANY($myvar=something, $other=somethingelse) [hello]") while True: df.system_turn() v = input() var, val = v.split("=") df.vars().update({var: val}) df.user_turn(input()) if __name__ == "__main__": df.run(debugging=True)
knowledge = KnowledgeBase() knowledge.load_json(ontology) df = DialogueFlow(State.START, initial_speaker=DialogueFlow.Speaker.SYSTEM, kb=knowledge, macros={ 'appCheck': appCheck(), 'providerInfo': providerInfo() }) # System (1) df.add_system_transition( State.START, State.Knowledge, r'[!"Hi, do you know anything about cloud computing?"]') # transition for no or kinda: User (1) df.add_user_transition(State.Knowledge, State.Knowledge_No, "[#ONT(disagree)]") df.add_user_transition(State.Knowledge, State.Knowledge_Kinda, "[#ONT(kinda)]") # System (2) df.add_system_transition( State.Knowledge_No, State.Explain, r'[! "Oh thats okay. Cloud computing just means that the storage, ' r'management, and processing of your app data happens offsite"]') df.add_system_transition( State.Knowledge_Kinda, State.Explain, r'[! "Oh dont worry, Ill give you a quick refresher. Cloud computing just means that the storage, ' r'management, and processing of your app data happens offsite"]') # user responses to the basics of cloud computing, split b/w some response vs disinterested response : User (2) df.add_user_transition(State.Explain, State.Explain_Response, "-{#ONT(disinterested)}") df.add_user_transition(State.Explain, State.Explain_Response_Disint, "[#ONT(disinterested)]")
# natex expression for final statement natex_evaluation = NatexNLG( '[!"well, I had a great time. i\'ll see you some other time then. bye bye..." #MacroPrintNumberQuestions()]', macros={'MacroPrintNumberQuestions': MacroPrintNumberQuestions()}) knowledge = KnowledgeBase() knowledge.load_json(ontology) df = DialogueFlow(State.START, initial_speaker=DialogueFlow.Speaker.SYSTEM, kb=knowledge) df.add_system_transition(State.START, State.PROMPT, '"hows your day going?"') df.add_user_transition(State.PROMPT, State.GOOD_DAY, '[$response=#ONT(ontgoodday)]', rank=2) df.add_user_transition(State.PROMPT, State.BAD_DAY, '[$response=#ONT(ontbadday)]', rank=2) df.add_user_transition(State.PROMPT, State.GOOD_DAY_Q, '<$r=#ONT(ontgoodday) {how, hows, is, are, you, your}>', rank=1) df.add_user_transition(State.PROMPT, State.BAD_DAY_Q, '<$r=#ONT(ontbadday) {how, hows, is, are, you, your}>', rank=1) # responses when user is asked about their day
knowledge = KnowledgeBase() knowledge.load_json(ontology) df = DialogueFlow(State.START, initial_speaker=DialogueFlow.Speaker.SYSTEM, kb=knowledge) #Turn 1 #Natex yes_nlu = r"[$answer={[yes], [yeah], [yep], [yup], [definitely], [of course]}]" no_nlu = r"[$answer={[no], [not], [nah], [nope], [little], [maybe]}]" #Transitions df.add_system_transition(State.START, State.PROMPT, '"Are you familiar with Uber and Lyft?"') df.add_user_transition(State.PROMPT, State.INFORMED, yes_nlu) df.add_user_transition(State.PROMPT, State.UNINFORMED, no_nlu) df.add_system_transition(State.ERR1, State.PROMPT, r'[!Sorry, was that yes or no"?"]') #Turn 2a - INFORMED #Natex never_nlu = r"[$answer={[never], [do not], [have not], [havent], [I dont], [none], [bus], [cab]}]" infr_nlu = r"[$answer={[sometimes], [occasionally], [not much], [once], [few], [month], [monthly], [hardly], [rarely], [not sure], [dont know]}]" freq_nlu = r"[$answer={[often], [a lot], [always], [too much], [daily], [weekly], [regularly], [day], [week], [all]}]" #Transitions df.add_system_transition(State.INFORMED, State.FREQUENCY, '"How often do you use ride sharing apps?"') df.add_user_transition(State.FREQUENCY, State.NEVER, never_nlu)
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]}]" df.add_system_transition( State.START, State.INTRO, '"Hi, I\'m a chatbot and I\'m designed to talk about poetry with humans. Enough about me now though, tell me, who is your favorite poet?"' ) df.add_user_transition(State.INTRO, State.POUND, favorite) df.add_user_transition(State.INTRO, State.REC_POET, poet_name) df.set_error_successor(State.INTRO, State.UNREC_POET) # Turn 2 # Natex alienation = r"[$theme=#ONT(alienation)]" love = r"[$theme=#ONT(love)]" death = r"[$theme=#ONT(death)]" time = r"[$theme=#ONT(time)]" nature = r"[$theme=#ONT(nature)]" df.add_system_transition( State.POUND, State.THEME, '"Incredible! Ezra Pound is my favorite poet too! I love imagist poetry; so brief yet so powerful! Pound wrote quite a bit, what did he write about that you like the best?"' )
"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)]") # ask if the user like the phone df.add_system_transition(State.iphone, State.turn_2a, '[! "Do you like your"$phone"?"]') df.add_system_transition(State.samsung, State.turn_2b, '[! "Do you like your"$phone"?"]') df.add_system_transition(State.android, State.turn_2c, '[! "Do you like your"$phone"?"]') # get yes from the user
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) df.add_user_transition(State.USED_PROMPT, State.USED_Y, "[$response=#ONT(ontyes)]", score=1) df.add_user_transition(State.USED_PROMPT, State.USED_N, "[$response=#ONT(ontno)]", score=1) df.add_system_transition(State.USED_Y, State.GAME_PROMPT, '[!"What games have you played?"]') df.add_user_transition(State.PLATFORM_GAME_PROMPT, State.BRAND, "[$brand=#ONT(ontbrand)]")
"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( State.PROMPT, State.SYSRESNO, '<{no, nah, nope, never, not}, {what, whats, you, your}>') df.add_system_transition( State.SYSRESNO, State.WHATEV, '"I use Spotify to stream music. What other music streaming services do you use?"' ) df.add_system_transition(State.ERR1, State.PROMPT,
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( State.S1, State.U1, '[! I think $cuisine food is quite tasty as "well." Do you have any $cuisine food that you "like?"]' ) df.add_user_transition(State.U1, State.S2, '[$dish=#ONT(#DISHES)]') df.set_error_successor(State.U1, State.S1ERR) df.add_system_transition(State.S1ERR, State.U2, '#RANDFOOD') # S2 df.add_system_transition( State.S2, State.U2,
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)]') df.add_user_transition(State.ROCKDYING, State.ROCKDISAGREE, '[#ONT(no)]') # Error df.set_error_successor(State.ROCKDYING, State.ROCK_ERROR3) df.add_system_transition(State.ROCK_ERROR3, State.ROCKDYING2, '"Sorry, I didn\'t catch that. Don\'t you agree?"')
rent = r"[!-[#ONT(ownTVPirate)], [#ONT(rentLibs)]]" cheap = r"[!-[#ONT(variety)], [#ONT(cheap)]]" variety = r"[!-[#ONT(cheap)], [#ONT(variety)]]" tv_movie = r"[!-[#ONT(conjunction)], {[$mediaType=#ONT(tv show)], [$mediaType=#ONT(movie)]}]" # End State df.add_system_transition(State.ENDF, State.ENDF, 'Conversation Ended') df.set_error_successor(State.ENDF, error_successor=State.ENDF) # Turn 0 df.add_system_transition(State.S0, State.S1, '"Do you use any movie streaming services?"') df.add_user_transition( State.S1, State.U1a, '[!-{[#ONT(streamServices)], [#ONT(multiple)], [#ONT(negative)]}, [#ONT(positive)]]' ) df.add_user_transition(State.S1, State.U1b, netflix_prime) df.add_user_transition( State.S1, State.U1c, '[!-{[#ONT(streamServices)], [#ONT(negative)]}, <[#ONT(multiple)], #ONT(positive)>]' ) df.add_user_transition(State.S1, State.U1e, hulu) df.add_user_transition(State.S1, State.U1f, dplus) df.add_user_transition( State.S1, State.U1d, "[!-{[#ONT(watch)], [#ONT(positive)], [#ONT(streamServices)]} [#ONT(negative)]]" ) df.add_user_transition( State.S1, State.END1, "[!-{[#ONT(streamServices)],[#ONT(positive)]}, [#ONT(negative)], [#ONT(watch)]]"
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"?"]') df.add_system_transition(State.S2d, State.U3a, '[!$comp is a great consulting firm"." What position in $comp are you interested in"?"]') df.add_system_transition(State.S2e, State.U3a, '[!$comp is a great technology company"." What position in $comp are you interested in"?"]') df.add_system_transition(State.S2f, State.U3a, '[!$comp is a great company to work for"." What position in $comp are you interested in"?"]')
} } ################################ 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"]') df.add_system_transition(State.ERR, State.PROMPT, '"i dont know that one, enter another animal"') df.set_error_successor(State.PROMPT, State.ERR) ################################ # Add Quiz2 Task 2 below
# df.add_system_transition(State.LIKE_GAME_Y, State.GAME_TYPE, '[!oh #MyMacro(there) how are you]') df.add_system_transition( State.LIKE_GAME_Y, State.GAME_TYPE, '"cool beans. are you into strategy games? i love strategy games."') df.add_system_transition( State.LIKE_GAME_N, State.SMART_PERSON, '"thats crazy! you should try playing some. maybe i can recommend some. are you a smart person?"' ) # df.add_user_transition(State.GAME_TYPE, State.GAME_TYPE_REPLY, "<$response={/(?:^|\s)(yea|ye|ya|yes|yeah|i do|i like)(?:\s|,|\.|$)/, #ONT(game_type)}>") # df.add_user_transition(State.GAME_TYPE, State.GAME_TYPE_REPLY_N, "<$response={/(?:^|\s)(no|not|nah|i dont like|i nope|i dislike)(?:\s|,|\.|$)/, #ONT(game_type)}>") df.add_system_transition(State.GAME_TYPE_REPLY_N, State.GENRE, '"well what genre of games do you like?"') df.add_user_transition(State.GENRE, State.GENRE_REPLY, "<$genre={horror, fps, rpg}>") df.set_error_successor(State.GENRE, State.GENRE_REDIR) df.add_system_transition( State.GENRE_REDIR, State.GAME_TYPE_OK, '"hmmm...sorry i dont play too many games of that genre but might i suggest league of legends? its my favorite game"' ) df.add_system_transition( State.GENRE_REPLY, State.GENRE_DISCUSS, '[! $genre " games huh? i know a couple of good ones. have you tried" #MyMacro($genre)]' ) df.add_user_transition(State.GENRE_DISCUSS, State.GENRE_REC, '/.*/') df.add_system_transition( State.GENRE_REC, State.GENRE_AFFIRM, '"its a super game!but do you know what my favorite game is?"') df.add_user_transition(State.GENRE_AFFIRM, State.GAME_TYPE_REPLY, '/.*/')
################################ # 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, '[! $animal "is a reptile, enter another animal"]') df.add_system_transition( State.AMPHIBIAN, State.PROMPT, '[! $animal "is an amphibian, enter another animal"]')
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."') #USER DOESNT LISTEN TO MUSIC df.add_system_transition(State.NO, State.NO_ANS, '"That\'s a shame. Why do you not listen to music?"')
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, '[!#NOT(#EXP(negation)) [{$related_type={#ONT(person),#EXP(roommate),family},people, someone, anyone, guys, girls}]]' ) df.add_user_transition( 'opening live with', 'live alone', '{[no one], [alone], [none], [myself], [#EXP(negation), {#EXP(roommate), people, someone, anyone}]}' ) df.add_state('live alone response', error_successor=root) df.add_system_transition('live alone', 'live alone response', '"Sometimes it is nice to live by yourself."') # S: Who are you close to? root = 'root' df.add_state('opening close to', system_multi_hop=True) df.add_system_transition('opening close to', root, '') df.add_system_transition(
# df.add_user_transition(State.TURN0, State.TURN0DK1S, dont_know) # dont knows section # df.add_system_transition(State.TURN0DK1S, State.TURN0DK1U, r'[! "No worries, if you dont know, I can just talk about trades! Is that okay?"]') # df.add_user_transition(State.TURN0DK1U, State.TURNTRADE1S, "[#ONT(agree)]") # df.set_error_successor(State.TURN0DK1U, State.TURN0ERR) # # df.add_system_transition(State.TURN0S, State.TURN0, r'[! "I do not know how to talk about that yet"]') # df.set_error_successor(State.TURN0, State.TURN0ERR) # df.add_system_transition(State.TURN0ERR, State.TURNTRADE1U, r'[! "Honestly, Im only really good at talking about trades right now. If thats okay then listen to this! " #tradeNews() ". Doesnt that sound interesting?"]') # df.add_system_transition(State.TURNTRADE1S2, State.EARLYEND, r'[! "Oh, thats a shame. I cant really talk about other news right now unfortunately. Maybe next time we can talk some more"]') #turn 1 df.add_system_transition( State.START, State.TURNTRADE1U, r'[!"Hi I’m NBA chatbot. I heard that " {#tradeNews()} "this season. Do you want to talk about this trade?"]' ) df.add_user_transition(State.TURNTRADE1U, State.TURNTRADE2S, '[#ONT(agree)]') df.add_user_transition( State.TURNTRADE1U, State.TURNTRADE1AS, '[#ONT(disagree)]') #goes to talk about a different trade df.add_system_transition( State.TURNTRADE1AS, State.TURNTRADE1U, r'[! {[! "How about this:"],I found this other trade article.,[! "What about this trade? I heard that"]} {#tradeNews()}]' ) df.add_user_transition(State.TURNTRADE1U, State.END, end) #terminates conversation #df.add_system_transition(State.TURNTRADE1BS, State.TURNTRADE1BU, r'[! "We can also talk about playoffs or stop talking. Which would you prefer?"]') #df.add_user_transition(State.TURNTRADE1BU, State.TURNPF1S, playoffs) #df.add_user_transition(State.TURNTRADE1BU, State.END, '[/[a-z A-Z]+/]') df.set_error_successor(State.TURNTRADE1U, State.TURNTRADE1ERR) df.add_system_transition( State.TURNTRADE1ERR, State.TURNTRADE2U,
] } } # 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' '\n www.apple.com' '\n www.microsoft.com' '\nS: Do you have a computer now?"') df.add_user_transition( State.COM_Q, State.COM_YES, '[{Yes,Yeah,yes,yeah,sure,of course,Of course,I do,i do}]') df.add_system_transition(
"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?"') df.add_system_transition( State.a0, State.a2, '"One and done, huh? I hope you do bake! Baking helps me calm down, \n' 'what are some things that help calm you down?"') df.add_system_transition( State.a1, State.a3, '"I won\'t keep throwing these at you, but I hope you try it! \n'