示例#1
0
    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
示例#2
0
    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
示例#3
0
文件: bye.py 项目: Jojister/sugaroid
 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
示例#4
0
    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
示例#5
0
    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
示例#6
0
    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
示例#7
0
 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
示例#8
0
    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
示例#9
0
    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
示例#10
0
    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
示例#11
0
    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
示例#12
0
    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
示例#13
0
    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
示例#14
0
    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