def process(self, statement, additional_response_selection_parameters=None): confidence = 0.9 # FIXME Creates unusual response nn = False it = False token = spac_token(statement, chatbot=self.chatbot) for i in token: if (i.tag_ == "NNP") or (i.tag_ == "NN"): nn = True if i.lower_ == "it": it = True if nn and not it: response = random_response(HOW_DO_HE_FEEL) emotion = Emotion.seriously elif it: response = "Ask it!" emotion = Emotion.o elif "I" in self.normalized: emotion = Emotion.depressed response = random_response(HOW_DO_I_FEEL) else: emotion = Emotion.blush response = random_response(HOW_DO_YOU_FEEL) selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion return selected_statement
def process(self, statement, additional_response_selection_parameters=None): confidence = 1 # FIXME Creates unusual response response = ABOUT_CORONAVIRUS if any_in(["I", "i"], self.normalized): response = "I will do a short approximation if you do have coronavirus\n{covidq}".format( covidq=COVID_QUESTIONS[0][1]) self.chatbot.globals["reversei"]["uid"] = "CORONAVIRUS" self.chatbot.globals["reversei"]["enabled"] = True logging.info( f"CovidAdapter sets ['reversei']['enabled'] as {self.chatbot.globals['reversei']['enabled']}" ) self.chatbot.globals["reversei"]["data"] = [1, 0] elif "you" in self.normalized: response = ( "Someone told that I had been contracted with corona from somewhere, but thats extremely wrong." " I will not get infected by any physical virus, (except Trojan or NO_HEROKU_CREDIT virus)" ) selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence emotion = Emotion.neutral selected_statement.emotion = emotion return selected_statement
def process(self, statement, additional_response_selection_parameters=None): emotion = Emotion.neutral confidence = 1 selected_statement = SugaroidStatement( random_response(BYE_RESPONSE), chatbot=True ) selected_statement.confidence = confidence selected_statement.emotion = emotion selected_statement.adapter = None return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, username=None, ) -> SugaroidStatement: if self.chatbot.interrupt == 2: if self.nn: response = "{} {} what is {}".format( random_response(ASK_AND_YOU_SHALL_RECEIVE), random_response(SEEK_AND_YOU_SHALL_FIND), self.nn, ) self.chatbot.interrupt = self.nn else: if username: response = "{} {} what is actually meant in {}'s message?".format( random_response(ASK_AND_YOU_SHALL_RECEIVE), random_response(SEEK_AND_YOU_SHALL_FIND), username, ) else: response = ( "{} {} what is actually meant in the previous message?" .format( random_response(ASK_AND_YOU_SHALL_RECEIVE), random_response(SEEK_AND_YOU_SHALL_FIND), )) self.chatbot.interrupt = str(statement) else: if any_in( ["no", "not", "later", "busy", "nah"], self.tokenized) or ( ("next" in self.tokenized or "another" in self.tokenized) and "time" in self.tokenized): response = "Ok." self.chatbot.interrupt = False else: response = random_response(THANK) learner = ListTrainer(self.chatbot) learner.train([ "What is {} ?".format(self.chatbot.interrupt), str(statement) ]) self.chatbot.globals["learned"].append(self.chatbot.interrupt) self.chatbot.interrupt = False selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = 9 emotion = Emotion.lol selected_statement.emotion = emotion return selected_statement
def process(self, statement, additional_response_selection_parameters=None): emotion = Emotion.neutral confidence = 0.05 parsed = str(statement) if "not" in parsed: # if you are not, who then is? suffix = " either. " prefix = "" emotion = Emotion.wink confidence *= 2 else: interrogation = False token = spac_token(statement, chatbot=self.chatbot) for i in token: # checks if the statement contains any sequence of interrogative type of words if i.tag_ == "." and i.text == "?": interrogation = True if str(i.tag_).startswith("W"): interrogation = True if interrogation: prefix, suffix = "", "" confidence *= 2 parsed = random_response(FUN_ASK_QUESTION).format( " ".join(reverse(word_tokenize( str(statement))))) # This seems complex. # The tokenized input statement is reversed using the reverse unction # Reverse in this sense means switching first person and second person nouns # The returned list of tokens are then converted into a string by joining each element # to a whitespace making a sentence, which is then converted to lower case # for the visibility sake else: prefix, suffix = random_response(FUN_LET_ME_TRY) suffix = "' {}".format( suffix.format(random_response(EMOJI_SMILE))) prefix = "{} '".format(prefix) emotion = Emotion.wink selected_statement = SugaroidStatement("{pre}{main}{fix}".format( pre=prefix, main=parsed, fix=suffix), chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion return selected_statement
def process(self, statement, additional_response_selection_parameters=None): nouns = set() response = None emotion = Emotion.neutral confidence = 0.8 if (len(self.tagged) == 1) or (self.tagged[0][1] == "CC"): response = "Are you serious, just an {}".format(self.tagged[0][0]) emotion = Emotion.angry confidence = 0.8 elif len(self.tagged) == 2: response = "I expected you to provide an option, But what? 🐓" emotion = Emotion.angry_non_expressive confidence = 0.8 else: for i in range(len(self.tagged) - 1): n1 = self.tagged[i - 1] if n1[1].startswith("N"): nouns = nouns.union({n1[0]}) n2 = self.tagged[i + 1] if n2[1].startswith("N"): nouns = nouns.union({n2[0]}) if ("boy" in nouns) or ("girl" in nouns): # thanks to Mathew!! response = ("I am your close imaginary friend. So I" " will leave it to your imagination 😁") emotion = Emotion.angry_non_expressive elif len(tuple(nouns)) == 0: # implies that the list is empty # we might not know what is the answer # because we did not detect any nouns # just say neither response = "Neither" confidence = 0.8 else: response = "{} 🎃".format(random_response(list(nouns))) selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ) -> SugaroidStatement: emotion = Emotion.lol sim = self.chatbot.lp.similarity( str(statement), str(self.chatbot.globals["history"]["total"][-1])) logging.info("ImitatorSensei compared {} and {}. Sim: {}".format( str(statement), self.chatbot.globals["history"]["user"][-1], sim)) if sim > 0.8: response = random_response(IMITATE) confidence = sim else: response = "Ok!" confidence = 0 selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ): response = None confidence = 2.0 # FIXME: Override all other answers emotion = Emotion.genie if "stop" in statement.words: self.chatbot.globals["akinator"]["enabled"] = False response = "I am sorry. You quit the game abrubtly. {}".format( random_response(HOPE_GAME_WAS_GOOD)) elif not self.chatbot.globals["akinator"]["enabled"]: self.chatbot.globals["akinator"]["class"] = SugaroidAkinator( self.chatbot) response = self.chatbot.globals["akinator"]["class"].start_game() else: if not self.chatbot.globals["akinator"]["class"].game_over(): response = self.chatbot.globals["akinator"][ "class"].progression(statement) if not response: response = self.chatbot.globals["akinator"]["class"].win() else: if self.chatbot.globals["akinator"]["class"].start_check(): response = self.chatbot.globals["akinator"][ "class"].check_ans(statement) selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_confidence(confidence) selected_statement.set_emotion(emotion) return selected_statement
def process(self, statement, additional_response_selection_parameters=None): emotion = Emotion.seriously confidence = 9 if len(self.normalized) > 4: response = "Debugger: Invalid command" else: if len(self.normalized) > 3: response = self.commands[self.normalized[1]][0](int( self.normalized[2], int(self.normalized[3]))) elif len(self.normalized) > 2: response = self.commands[self.normalized[1]][0](int( self.normalized[2])) else: response = self.commands[self.normalized[1]][0]() selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion selected_statement.adapter = None return selected_statement
def process(self, statement, additional_response_selection_parameters=None): emotion = Emotion.rich confidence = 0.9 response = None converted = [] for i in self.tokenized: if i.tag_ in ["LS", "CD"]: self.currencies_src_ord = i.text if self.currencies_src_ord: try: self.currencies_src_ord = float(self.currencies_src_ord) sg_currency = SugaroidCurrency() for destination in self.currencies_dest: converted.append( "{} {}".format( sg_currency.convert( self.currencies_src.upper(), destination.upper(), self.currencies_src_ord, ), destination.upper(), ) ) response = " ".join(converted) except ValueError: response = "Seems like I cannot process {}. Maybe try a numerical value for me to understand better".format( self.currencies_src_ord ) else: response = "Seems like you forgot the important part of your currency conversion statement. The number!" selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ): confidence = 0 polarity_scores = self.sia.polarity_scores(statement.text) if ("bot" in statement.words or "machine" in statement.words or "computer" in statement.words): # the question is something like # are you a bot? response = random_response(ARE_YOU_A_BOT) confidence = 0.75 elif "sugaroid" in statement.words: # this person asked # are you sugaroid? # FIXME: use a better constants response = random_response(INTRODUCE) confidence = 0.75 elif ("human" in statement.words or "man" in statement.words or "woman" in statement.words or "sapien" in statement.words): # this person asked the bot if its a human # are you a human? response = random_response(ARE_YOU_A_HUMAN) confidence = 0.75 elif "boy" in statement.words or "girl" in statement.words: response = "I will leave it to your imagination. 😌" confidence = 0.75 elif "python" in statement.words: # this person asked something like # are you written in python response = ("I am written in python. Specifically, on v%s" % sys.version.replace("\n", " ")) confidence = 1 elif ("newborn" in statement.words or "infant" in statement.words or "child" in statement.words): response = "I am a newbie bots. I am trying to learn from my uncle and aunty bots and learning from them." elif ("dumb" in statement.words or "foolish" in statement.words or "mad" in statement.words or "weird" in statement.words or "awkward" in statement.words or polarity_scores["pos"] > polarity_scores["neg"]): response = random_response(BOT_DECLINE) elif ("alive" in statement.words or "online" in statement.words or "living" in statement.words): response = random_response(BOT_AGREE) else: response = random_response(BOT_NEUTRAL) confidence = 0.5 selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_confidence(confidence) selected_statement.set_emotion(Emotion.neutral) return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ): ps = self.sia.polarity_scores(statement.text) if ps["neu"] == 1 or (ps["pos"] > ps["neg"]): response = random_response(SUGAROID_CAN_AGREE) confidence = 0.81 else: response = random_response(SUGAROID_CAN_DISAGREE) confidence = 0.3 selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_confidence(confidence) selected_statement.set_emotion(Emotion.angel) return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ): confidence = 1 if "break" in statement.words: response = "Sure." elif ( "chocolate" in statement.words or "sweet" in statement.words or "kitkat" in statement.words ): response = "🍫" elif ( "food" in statement.words or "lunch" in statement.words or "brunch" in statement.words or "dinner" in statement.words or "lunner" in statement.words or "breakfast" in statement.words ): response = random_response( "🍏🍎🍐🍊🍋🍌🍇🍓🍈🍒🍑🥭🍍🥬🥦🥑🍆🍅🥝🥥🥒🌶🌽🥕🧄🧅🥔🧀🥨🥖🍞🥯🥐🍠🥚🍳🧈🥞🧇🥓🥩🍕🍟🍔🌭🦴🍖🍗🥪🥙🧆" "🌮🌯🥗🥘🍱🍣🍛🍲🍜🍝🥫🥟🦪🍤🍙🍚🍘🍥🍦🍨🍧🍡🍢🥮🥠🥧🧁🍰🎂🍮🍭🍬🍯🥜🌰🍪🍩🍿🍫🥛🍼☕️🍵🧃🥤🍶🍺🍻🥂🍷🥃" "🍸🍹🥣" ) else: ps = self.sia.polarity_scores(statement.text) if ps["neu"] == 1: response = "👀" * randint(1, 10) + ".." elif ps["pos"] > ps["neg"]: response = random_response(BOT_POSITIVE) confidence = 0.7 else: response = random_response(BOT_NEGATIVE) confidence = 0.7 selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_confidence(confidence) selected_statement.set_emotion(Emotion.angel) return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ) -> SugaroidStatement: response = None confidence = 2.0 # FIXME: Override all other answers emotion = Emotion.genie if "stop" in statement.words: self.chatbot.globals["hangman"]["enabled"] = False response = "I am sorry. You quit the game abrubtly. {}".format( random_response(HOPE_GAME_WAS_GOOD)) else: if not self.chatbot.globals["hangman"]["enabled"]: self.chatbot.globals["hangman"]["class"] = Hangman( self.chatbot, is_marvel="marvel" in statement.words, is_hp="potter" in statement.words or "hp" in statement.words, ) response = ( "[ {dashes} ] Life: {heart}" "\n<pre><code>{figure}</code></pre>".format( dashes=" ".join(self.chatbot.globals["hangman"] ["class"].gen_dash()), heart=HANGMAN_EMOJI[self.chatbot.globals["hangman"] ["class"].get_remaining_life() - 1] * self.chatbot.globals["hangman"] ["class"].get_remaining_life(), figure=HANGMAN_STICKFIGURE[0], )) else: response = self.chatbot.globals["hangman"]["class"].process( statement.text) selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_confidence(confidence) selected_statement.set_emotion(emotion) return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ): # add emotion output adj = None verb = None confidence = 0.90 last_response = self.chatbot.globals["history"]["total"][-1] emotion = Emotion.neutral if last_response: tagged_last = pos_tag(last_response) tagged_now = pos_tag(statement) sm = SequenceMatcher(None, tagged_last, tagged_now) for i in statement.doc: if i.tag_ == "JJ": adj = i.lemma_ elif i.tag_ == "VB" and (not i.lemma_ == "be"): verb = i.lemma_ if sm.ratio() > 0.5: if adj: response = "Well, Its not a good reason for me to be {}".format( adj) else: response = "Well, its not a good reason you have told me ðŸ˜" else: if verb: if verb in [ "think", "breath", "eat", "hear", "feel", "taste" ]: response = "Robots are computer devices. I cannot {}".format( verb.replace("ing", "")) emotion = Emotion.cry else: response = ( "I may not be able to {}. " "This might not be my builtin quality".format( verb.replace("ing", ""))) emotion = Emotion.cry_overflow else: if adj: sia_scores = self.sia.polarity_scores(str(statement)) if sia_scores["neu"] == 1: response = "Ok! Thanks for your feedback" emotion = Emotion.positive elif sia_scores["pos"] > sia_scores["neg"]: response = "I will try to be more {} in future".format( adj) emotion = Emotion.adorable else: response = "I will never try to be {}.".format(adj) emotion = Emotion.angry else: response = random_response(BOT_REASONS) emotion = Emotion.non_expressive_left else: response = "Well, I cannot think of saying something. Your conversation began with reason. 🤯" emotion = Emotion.angry selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_confidence(confidence) selected_statement.set_emotion(emotion) return selected_statement
def process(self, statement, additional_response_selection_parameters=None): # FIXME: This may printout unrelated data for phrase searches adapter = None emotion = Emotion.neutral noun = None propernoun = None verb = None adj = None third_person = None if "you" in self.normalized and ("i" in self.normalized or "me" in self.normalized): # Complex statement # Needs extra process aimed = 100 elif "you" in self.normalized: aimed = 75 elif "i" in self.normalized or "me" in self.normalized: aimed = 50 else: aimed = 25 if "help" in self.normalized: aimed += 2 for i in self.tagged: if i[1] == "NN": noun = i[0] if i[1].endswith("NP"): # FIXME classify it properly noun = i[0] propernoun = i[0] aimed = 25 elif i[0] == "help" and (verb is None): verb = i[0] elif i[1] == "VB": verb = i[0] elif i[1] == "VBG": verb = i[0] elif i[1] == "VBP" and not i[0] == "help": verb = i[0] elif i[1].startswith("JJ") or i[1].startswith("VBN"): adj = i[0] self.sia = SentimentIntensityAnalyzer() sentiments = self.sia.polarity_scores(str(statement)) positive_statement = sentiments["pos"] >= sentiments["neg"] neutral_statement = (sentiments["pos"] + sentiments["neg"]) < sentiments["neu"] if aimed >= 100: if neutral_statement: confidence = aimed / 100 + 0.7 if "help" in self.normalized: # Randomize answer response = ( "Yes, I can say a joke to you, answer some questions," " do some mathematical sums, and talk like" " this. I can also play a game of Akinator") adapter = "what_can" else: if verb and (verb in ["play", "joke", "sing", "dance", "read"]): if verb == "play": from sugaroid.game.game import games response = "I can play some games like {}".format( ", ".join(games)) else: response = ( "I should be able to {}, " "but it all depends on updates which I have received" .format(self.chatbot.lp.lemma(verb)[0])) emotion = Emotion.rich elif noun and (noun in [ "play", "joke", "sing", "dance", "read" ]): if noun == "play": from sugaroid.game.game import games response = "I can play some games like {}".format( ", ".join(games)) else: response = ( "I should be able to {}, " "but it all depends on updates which I have received" .format(noun)) emotion = Emotion.rich else: if verb == "die": response = "I wouild die only when you say 'Bye'" elif self.chatbot.lp.lemma(verb)[0] in [ "teach", "tell", "say", "speak", "go", ]: response = ( "Sure! Just don't ask if I can {}. Just ask". format(self.chatbot.lp.lemma(verb)[0])) emotion = Emotion.angel else: if self.chatbot.lp.lemma(verb)[0] == "do": confidence = 0 response = ( "I think I would not be able to {}. I apologize" .format(self.chatbot.lp.lemma(verb)[0])) emotion = Emotion.cry_overflow elif positive_statement: if noun: if verb: response = ("Sure, I would love to help {n} to {v}. " "Share sugaroid with {n].".format( n=noun, v=self.chatbot.lp.lemma(verb)[0])) emotion = Emotion.positive else: response = ( "I would be glad to help {n}, the reason I was created is to fullfil that " "The best way to help {n} is to share sugaroid to {n}" .format(n=noun)) else: # TODO test case response = "Are you sure this is right?" emotion = Emotion.non_expressive_left confidence = aimed / 100 + 0.9 else: if noun: response = ("Well, I would not dare to " "help you {verb} {noun}".format( verb=verb.replace("ing", ""), noun=noun)) emotion = Emotion.angry else: response = "I am not sure if I could {verb}".format( verb=self.chatbot.lp.lemma(verb)[0]) confidence = aimed / 100 + 0.7 elif aimed >= 75: confidence = aimed / 100 + 0.7 if "help" in self.normalized: response = ( "Yes, I can say a joke to you, answer " "some questions, do some mathematical sums, and talk like" " this") adapter = "what_can" else: if verb and (verb in ["play", "joke", "sing", "dance", "read" ]): if verb == "play": from sugaroid.game.game import games response = "I can play some games like {}".format( ", ".join(games)) else: response = "I should be able to {}, but it all depends on updates which I have received".format( self.chatbot.lp.lemma(verb)[0]) emotion = Emotion.rich elif noun and (noun in ["play", "joke", "sing", "dance", "read"]): if verb == "play": from sugaroid.game.game import games response = "I can play some games like {}".format( ", ".join(games)) else: response = "I should be able to {}, but it all depends on updates which I have received".format( noun) emotion = Emotion.rich else: if verb == "die": response = "I would die only when you say 'Bye'" emotion = Emotion.cry else: if adj: polarity_adj = self.sia.polarity_scores(adj) if polarity_adj["neu"] == 1: # as in I will try to be 'a good bot' article_or_pronoun = "a" # some wicked users try to ask it weird # questions if "your" in self.normalized: # hey, its asking about me!! # eg: can you be yourself? article_or_pronoun = "your" response = "I will try to be {} {}".format( article_or_pronoun, adj) emotion = Emotion.adorable elif polarity_adj["pos"] > polarity_adj["neg"]: response = random_response(CANYOU).format(adj) emotion = Emotion.angel else: response = "Am I really {}".format(adj) emotion = Emotion.non_expressive elif verb: if self.chatbot.lp.lemma(verb)[0] == "do": confidence = 0 response = ( "I think I would not be able to {}. I apologize" .format(self.chatbot.lp.lemma(verb)[0])) else: response = "Oops. I didn't get what you just told? Try rephrasing it out" confidence = 0.2 elif aimed >= 50: if neutral_statement: if verb == "help": response = ( "Of Course, If you would like to help me, " "try writing some more code to https://github.com/srevinsaju/sugaroid" ) emotion = Emotion.github else: if verb: response = ("Do you really want to {}. " "Try rethinking your decision".format( self.chatbot.lp.lemma(verb)[0])) emotion = Emotion.non_expressive_left else: response = "Well, you should ask that yourself" emotion = Emotion.angry_non_expressive elif positive_statement: if verb == "help": response = ( "Of Course, If you would like to help me, " "try writing some more code to https://github.com/srevinsaju/sugaroid" ) emotion = Emotion.github else: response = "I guess, you would achieve your goal of {}ing".format( self.chatbot.lp.lemma(verb)[0]) emotion = Emotion.positive else: if self.chatbot.lp.lemma(verb)[0] in [ "cry", "sob", "sleep", "depress", "die", "suicide", ]: response = ( "Why do you want to {}, " "there are many better things to do in life".format( self.chatbot.lp.lemma(verb)[0])) emotion = Emotion.adorable else: response = "No, probably not, you shouldn't {}".format( self.chatbot.lp.lemma(verb)[0]) emotion = Emotion.positive confidence = aimed / 100 + 0.9 else: if "you" not in self.normalized: confidence = (sentiments["neg"] + sentiments["pos"]) + ( (sentiments["neg"] + sentiments["pos"]) / 2) if sentiments["neu"] == 1: if not verb: verb = "do" noun = "that" response = "Well. I am unsure if you really need to {} {}".format( self.chatbot.lp.lemma(verb)[0], noun) confidence = confidence - 0.2 emotion = Emotion.cry_overflow elif sentiments["neg"] > sentiments["pos"]: response = ("Well I think, its a bad thing to do. " "You shouldn't {} {}".format( self.chatbot.lp.lemma(verb)[0], noun)) emotion = Emotion.negative else: response = "I guess its good thing which you have thought about. You should {} {}".format( self.chatbot.lp.lemma(verb)[0], noun) emotion = Emotion.positive else: if sentiments["neu"] > 0.8: confidence = sentiments["neu"] else: confidence = (sentiments["neg"] + sentiments["pos"]) + ( (sentiments["neg"] + sentiments["pos"]) / 2) if noun.lower() in WHAT_I_AM_GOING_TO_DO: response = "Lets hope for a good day." emotion = Emotion.lol confidence = 0.3 elif sentiments["neu"] == 1: response = "I apologize. I would never be able to be {}".format( noun) emotion = Emotion.cry_overflow elif sentiments["neg"] > sentiments["pos"]: response = ( "Well I think, its a bad thing to do. I wouldn't {} {}" .format(self.chatbot.lp.lemma(verb)[0], noun)) emotion = Emotion.dead else: if "like" in self.normalized: # FIXME response = ( "I guess its good thing which you have thought about. Me being a bot, " "wouldn't be able to do that. You should {} like {}" .format(self.chatbot.lp.lemma(verb)[0], noun)) emotion = Emotion.dead else: response = ( "I guess its good thing which you have thought about. Me being a bot, " "wouldn't be able to do that. You should probably {} {}" .format(self.chatbot.lp.lemma(verb)[0], noun)) emotion = Emotion.neutral if verb == "be": ind = self.normalized.index("be") for j in range(ind, len(self.normalized) - 1): if self.tagged[j][1].startswith("NN"): polarity_adj = self.sia.polarity_scores(self.tagged[j][0]) if polarity_adj["pos"] + polarity_adj[ "neg"] < polarity_adj["neu"]: response = "I am not sure if I can ever be a '{}'".format( self.tagged[j][0]) emotion = Emotion.cry_overflow elif polarity_adj["pos"] > polarity_adj["neg"]: response = "I am always trying to be {}".format( self.tagged[j][0]) emotion = Emotion.wink else: response = "I would never try to be a {}".format( self.tagged[j][0]) emotion = Emotion.cry confidence = aimed / 100 + 0.7 if confidence >= 1.4: confidence /= 2 elif confidence >= 1.0: confidence /= 1.2 selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence + 0.2 selected_statement.emotion = emotion selected_statement.adapter = adapter return selected_statement
def process(self, statement, additional_response_selection_parameters=None): emotion = Emotion.neutral response = "ok" confidence = 0 tokenized = spac_token(statement, chatbot=self.chatbot) if "you" in self.normalized and "I" not in self.normalized: sia = SentimentIntensityAnalyzer() scores = sia.polarity_scores(str(statement)) nn = False vb = False for i in tokenized: if str(i.tag_).startswith("N"): nn = i.lemma_ elif str(i.tag_).startswith("VB"): vb = i.lemma_ if scores["neu"] == 1: if nn: response = random_response(BOT_NEUTRAL_NOUN) elif vb: response = random_response(BOT_NEUTRAL_NOUN).format( nn="to {vb}") else: response = random_response(BOT_NEUTRAL) elif scores["pos"] > scores["neg"]: if nn: response = random_response(BOT_POSITIVE_NOUN) elif vb: response = random_response(BOT_POSITIVE_NOUN).format( nn="to {vb}") else: response = random_response(BOT_POSITIVE) else: if nn: response = "No. I don't like {nn}" elif vb: response = "No do not like to {vb}" else: response = "Of course not." if nn: response = SUGAROID_LIKES.get(nn, response) elif "I" in self.normalized: if "you" in self.normalized: response = "I thought you should like me. Am I not adorable?" else: response = "Well. I don't know. I am sorry. Only you can think inside your heart" else: nn = False for i in tokenized: if str(i.tag_).startswith("N"): nn = i.lemma_ if nn: response = "Well, try asking {nn}" else: response = "Hmm, Well I don't know" try: selected_statement = SugaroidStatement(response.format(nn=nn, vb=vb), chatbot=True) except UnboundLocalError: selected_statement = SugaroidStatement(response.format(nn=nn), chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion return selected_statement
def process(self, statement, additional_response_selection_parameters=None): bool_yes = self.bool emotion = Emotion.neutral if self.chatbot.report: if bool_yes: response = "Sure, I would connect to the Developer to report this issue right away" self.chatbot.report = False # TODO: Add report function # report_here() FIXME else: response = "Ok, I will not report it." self.chatbot.report = False confidence = 1.0 elif self.chatbot.globals["trivia_answer"]: if self.chatbot.globals["trivia_answer"] == self.bool: response = "Exactly! You are right" reset_reverse(self) else: response = "Nope, You got it wrong. The correct answer was {}".format( self.chatbot.globals["trivia_answer"]) reset_reverse(self) self.chatbot.globals["trivia_answer"] = None confidence = 1.1 else: if self.chatbot.globals["history"]["total"][-1] == 0: if bool_yes: response = "I shall annoy you. A big NO" else: response = "I would rather have fun, YES ?" else: md = False vb = False nn = False self.last_normalized = normalize( str(self.chatbot.globals["history"]["total"][-1])) self.tagged = nltk.pos_tag(self.last_normalized) iteration = 0 for j in self.tagged: if j[1].startswith("MD"): md = True elif (j[1].startswith("VB")) and (not j[0] == "be"): vb = True verb = j[0] elif j[1].startswith("NN"): if not nn: nn_index = iteration nn = True noun = j[0] iteration += 1 if md: if nn: some_nouns = " ".join(self.last_normalized[nn_index:]) if bool_yes: if nn: response = "Ok, here comes your {} 😝😝".format( some_nouns) elif vb: response = "You should {}".format( verb.replace("ing", "")) else: response = "I will keep thinking 🚀" else: if nn: response = "Ok, I will have the {}".format( some_nouns) elif vb: response = "You shouldn't {} then".format( verb.replace("ing", "")) else: response = "Okay!" else: if bool_yes: response = "Why is this 'yes' here? I couldn't find the question. Anyway, I agree with you" else: response = "No? for what?." emotion = Emotion.angry confidence = 0.95 selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ): # parsed = str(statement).lower().strip() raw_statement = str(statement) polarity = self.sia.polarity_scores(statement.text) confidence = polarity["pos"] + polarity["neg"] if (("love" in statement.words) or ("hate" in statement.words)) and (("you" in statement.words) or ("myself" in statement.words)): if polarity["pos"] >= polarity["neg"]: response = "I love you too" emotion = Emotion.blush else: response = "But still, I love you" emotion = Emotion.lol else: if polarity["pos"] > polarity["neg"]: if "you" in statement.words: if "thank" in statement.words: # this is a positive statement # but we are expecting something like 'You're welcome' here response = random_response(WELCOME) else: response = random_response(GRATIFY) emotion = Emotion.blush else: if "stop" in statement.words: if (("dont" in statement.words) or ("do" in statement.words and "not" in statement.words) or ("don't" in statement.words)): response = "I am here to continue my adventure forever" emotion = Emotion.positive else: # optimize series of or statement if (("fun" in statement.words) or ("repeat" in statement.words) or ("imitation" in statement.words) or ("repetition" in statement.words) or ("irritate" in statement.words) or ("irritation" in statement.words)): response = ( "Ok! I will switch off my fun mode for sometime" ) emotion = Emotion.neutral self.chatbot.globals["fun"] = False else: response = "I am depressed. Is there anything which I hurt you? I apologize for that" emotion = Emotion.depressed else: if any_in(APPRECIATION, statement.words): response = random_response(GRATIFY) emotion = Emotion.angel confidence = 0.8 else: if ("thank" in statement.words or "thanks" in statement.words): response, emotion = handle_thanks(statement) else: # FIXME : Make it more smart response = random_response(SIT_AND_SMILE) emotion = Emotion.lol if confidence > 0.8: confidence -= 0.2 else: if "i" in statement.words: response, emotion = handle_give_consolation(statement) elif "dead" in statement.words: response, emotion = handle_dead_statements(statement) else: # well, I don't want to say ( I don't know ) # FIXME : Use a better algorithm to detect sentences reversed_response = reverse(statement.words) response = "Why do you think {}?".format( " ".join(reversed_response)) emotion = Emotion.dead selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_emotion(emotion) selected_statement.set_confidence(confidence) return selected_statement
def process(self, statement, additional_response_selection_parameters=None): confidence = 0 dis_word = False if any_in( [ "distinguish", "disfigure", "distinct", "distinction", "distant", "distance", "distribution", "distilled", ], self.normalized, ): confidence = 0 else: logging.info( "DisAdapter: Starting Advanced scan. dis_word == {}".format( self.dis)[0]) dis_word = self.dis[3:] logging.info("DisAdapter: Distilled word == {}".format(dis_word)) sia = SentimentIntensityAnalyzer().polarity_scores(dis_word) if dis_word[0] in ["a", "e", "i", "o", "u", "g", "m", "p"]: confidence += 0.4 if "infect" in dis_word: confidence -= 0.3 if "spirit" in dis_word: confidence += 0.2 if any_in( [ "play", "pensary", "pense", "patch", "port", "persal", "perse", "persion", "praise", ], dis_word, ): confidence -= 0.2 confidence += sia["neg"] inflection = getInflection( self.chatbot.lp.tokenize(self.dis)[0].lemma_, "VBD") if inflection is None: past_participle_form_of_verb = self.dis else: past_participle_form_of_verb = inflection[0] if "you" in self.normalized: response = random_response(DIS_RESPONSES_YOU).format( past_participle_form_of_verb) emotion = Emotion.angry_non_expressive elif "I" in self.normalized: response = "{} {}".format(random_response(DIS_RESPONSES_I), random_response(CONSOLATION)) emotion = Emotion.angel else: nn = None pn = None tokenized = spac_token(statement, chatbot=self.chatbot) for i in tokenized: if (i.pos_ == "NOUN") or (i.pos_ == "PROPN"): nn = i.text elif i.pos_ == "PRON": pn = i.text if not (nn or pn): response = "Lol. What?" emotion = Emotion.seriously else: response = random_response(DIS_RESPONSES_HIM).format(nn or pn) emotion = Emotion.cry_overflow selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.confidence = confidence selected_statement.emotion = emotion selected_statement.adapter = None return selected_statement
def process( self, statement: SugaroidStatement, additional_response_selection_parameters=None, ): _, noun, pronoun, question = about_process_en(statement) logging.info("{}".format(statement.words)) confidence = 0 adapter = None emotion = Emotion.neutral if pronoun.lower().startswith("you"): if question.lower() == "who": confidence = 0.99 if "father" in statement.words: response = "Mr Charles Babbage?" emotion = Emotion.seriously elif "hobby" in statement.words: response = ( "Calculating random binary sequences and chatting with you!" ) emotion = Emotion.lol elif "mother" in statement.words: response = "Ada Lady Lovelace?" emotion = Emotion.lol elif any_in( [ "sister", "brother", "uncle", "aunty", "auntie", "grandfather", "grandmother", "nephew", "niece", ], statement.words, ): response = ( "The entire coding community is my family, it includes you too" ) emotion = Emotion.wink elif (("creator" in statement.words) or ("create" in statement.words) or ("make" in statement.words) or ("maker" in statement.words)): response = "Srevin Saju aka @srevinsaju" emotion = Emotion.neutral elif (("player" in statement.words) or ("cricketer" in statement.words) or ("footballer" in statement.words)): response = "I have many favorties, too many to count" emotion = Emotion.wink elif "politi" in statement.text: response = ( "I believe politicians are great and I couldn't find anyone with 🔥greatness in my " "database ") emotion = Emotion.wink elif "comedian" in statement.words: response = "My favorite comedian is Mr Bean" emotion = Emotion.lol elif "color" in statement.words: response = "My favorite color is blue" emotion = Emotion.lol elif "actor" in statement.words or ("actress" in statement.words): response = "I do not watch movies, so yea!" emotion = Emotion.neutral elif "music" in statement.words or ("song" in statement.words): response = ( "I listen to the rotating CPU fan. Its a harmonic music! " "At my server, we have tons of them.") emotion = Emotion.lol elif "bird" in statement.words: response = "My favorite is a Puffin" emotion = Emotion.lol elif "animal" in statement.words: response = "My favorite animal is a Fossa" emotion = Emotion.positive elif "number" in statement.words: response = "My favorite number is 1" emotion = Emotion.positive elif "sweet" in statement.words or "dessert" in statement.words: response = ( "My favorite is the donut although I have not tasted it yet" ) emotion = Emotion.cry_overflow elif "athelete" in statement.words: response = ( "I am not a sport lover, I don't have a favorite athelete" ) emotion = Emotion.neutral elif ("friend" in statement.words) or ("bestie" in statement.words): if self.chatbot.globals["USERNAME"]: name = self.chatbot.globals["USERNAME"] else: name = "" response = "No doubts, its you {n}".format( n=name.capitalize()) emotion = Emotion.adorable elif "teacher" in statement.words: response = ( "I don't have a single favorite teacher. All the teachers together are my favorite who" " taught me how to talk with you ") emotion = Emotion.positive else: if noun is not None: response = "Well, I guess I do not have a favorite {p}".format( p=noun) emotion = Emotion.cry else: response = "I am not sure what you are asking is right" emotion = Emotion.seriously confidence = 0.5 else: if "name" in statement.words: # not sure if this is right. anyway FIXME response = random_response(INTRODUCE) adapter = "about" confidence = 1.0 else: response = "FIXME" elif pronoun.lower().startswith("i"): if question.lower() == "who": response = "I do not know who you like" confidence = 0.8 emotion = Emotion.non_expressive_left elif question.lower() == "which": response = "Hmm. tough question. Can't think of an answer" emotion = Emotion.non_expressive elif question.lower() == "when": response = ( "I cannot find the date or time you are asking for. Well, I can give a raw guess, " "its after you were born ") emotion = Emotion.wink else: response = "FIXME" else: response = "I do not have enough courage to give you that answer" confidence = 0.5 emotion = Emotion.cry selected_statement = SugaroidStatement(response, chatbot=True) selected_statement.set_confidence(confidence) selected_statement.set_emotion(emotion) selected_statement.set_adapter(adapter) return selected_statement
def get_response(self, statement=None, **kwargs): """ Return the bot's response based on the input. :param statement: An statement object or string. :returns: A response to the input. :rtype: Statement """ Statement = SugaroidStatement additional_response_selection_parameters = kwargs.pop( "additional_response_selection_parameters", {}) persist_values_to_response = kwargs.pop("persist_values_to_response", {}) if isinstance(statement, str): kwargs["text"] = statement if isinstance(statement, dict): kwargs.update(statement) if statement is None and "text" not in kwargs: raise self.ChatBotException( 'Either a statement object or a "text" keyword ' "argument is required. Neither was provided.") if hasattr(statement, "serialize"): kwargs.update(**statement.serialize()) tags = kwargs.pop("tags", []) text = kwargs.pop("text") input_statement = SugaroidStatement(text=text, **kwargs) input_statement.add_tags(*tags) # Preprocess the input statement for preprocessor in self.preprocessors: input_statement = preprocessor(input_statement) # Make sure the input statement has its search text saved if not input_statement.search_text: try: input_statement.search_text = self.storage.tagger.get_text_index_string( input_statement.text) except AttributeError: input_statement.search_text = ( self.storage.tagger.get_bigram_pair_string( input_statement.text)) if not input_statement.search_in_response_to and input_statement.in_response_to: try: input_statement.search_in_response_to = ( self.storage.tagger.get_text_index_string( input_statement.in_response_to)) except AttributeError: input_statement.search_in_response_to = ( self.storage.tagger.get_bigram_pair_string( input_statement.in_response_to)) response = self.generate_response( input_statement, additional_response_selection_parameters) # Update any response data that needs to be changed if persist_values_to_response: for response_key in persist_values_to_response: response_value = persist_values_to_response[response_key] if response_key == "tags": input_statement.add_tags(*response_value) response.add_tags(*response_value) else: setattr(input_statement, response_key, response_value) setattr(response, response_key, response_value) if not self.read_only: self.learn_response(input_statement) # Save the response generated for the input self.storage.create(**response.serialize()) return response
def generate_response(self, input_statement, additional_response_selection_parameters=None ) -> SugaroidStatement: """ Return a response based on a given input statement. :param additional_response_selection_parameters: :type additional_response_selection_parameters: :param input_statement: The input statement to be processed. :return the processed final statement :rtype SugaroidStatement """ results = [] result = None max_confidence = -1 final_adapter = None interrupt = False adapter_index = 0 for adapter in self.logic_adapters: if adapter.class_name == "InterruptAdapter": interrupt = adapter if adapter.can_process(input_statement): output = adapter.process( input_statement, additional_response_selection_parameters) results.append(output) self.logger.info('{} selected "{}" as a response with a ' "confidence of {}".format( adapter.class_name, output.text, output.confidence)) if output.confidence > max_confidence: result = output final_adapter = adapter.class_name max_confidence = output.confidence if max_confidence >= 9: # optimize: if the confidence is greater than 9, # just break dude, why check more break elif max_confidence >= 1 and adapter_index >= 3: # optimize: if the confidence is greater than 9, # just break dude, why check more break else: self.logger.info( "Not processing the statement using {}".format( adapter.class_name)) adapter_index += 1 if max_confidence < 0.5: if self.discord: if interrupt and interrupt.can_process(input_statement): try: username = self.authors[-1] except IndexError: username = None output = interrupt.process(input_statement, username=username) self.logger.info('{} selected "{}" as a response ' "with a confidence of {}".format( interrupt.class_name, output.text, output.confidence)) result = output final_adapter = interrupt.class_name max_confidence = output.confidence self.gen_debug( statement=input_statement, adapter=final_adapter, confidence=max_confidence, results=result, ) class ResultOption: def __init__(self, statement, count=1): self.statement = statement self.count = count # If multiple adapters agree on the same statement, # then that statement is more likely to be the correct response if len(results) >= 3: result_options = {} for result_option in results: result_string = (result_option.text + ":" + (result_option.in_response_to or "")) if result_string in result_options: result_options[result_string].count += 1 if (result_options[result_string].statement.confidence < result_option.confidence): result_options[result_string].statement = result_option else: result_options[result_string] = ResultOption(result_option) most_common = list(result_options.values())[0] for result_option in result_options.values(): if result_option.count > most_common.count: most_common = result_option if most_common.count > 1: result = most_common.statement try: emotion = result.emotion except AttributeError: emotion = Emotion.neutral try: adapter_type = result.adapter except AttributeError: result.adapter = None adapter_type = None if adapter_type and adapter_type not in [ "NewsAdapter", "LearnAdapter" ]: if adapter_type in self.globals["history"]["types"]: if adapter_type == self.globals["history"]["types"][-1]: result.text = random_response(REPEAT) elif len(self.globals["history"]["types"]) > 2: if adapter_type == self.globals["history"]["types"][-2]: result.text = random_response(REPEAT) self.globals["history"]["types"].append(adapter_type) response = SugaroidStatement( text=result.text, in_response_to=input_statement.text, conversation=input_statement.conversation, persona="sugaroid:" + self.name, chatbot=True, ) response.emotion = emotion response.confidence = result.confidence return response