Exemple #1
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):
        response = None
        if not self.chatbot.globals['learn']:
            response = 'Enter something you want to teach me. What is the statement that you want me to learn.'
            self.chatbot.globals['learn'] = 2
        elif self.chatbot.globals['learn'] == 2:
            response = 'What should I respond to the above statement?'
            self.chatbot.globals['learn_last_conversation'].append(
                str(statement))
            self.chatbot.globals['learn'] -= 1
        elif self.chatbot.globals['learn'] == 1:
            response = 'Thanks for teaching me something new. I will always try to remember that'
            self.chatbot.globals['learn_last_conversation'].append(
                str(statement))
            self.chatbot.globals['learn'] -= 1
            list_trainer = ListTrainer(self.chatbot)
            list_trainer.train(self.chatbot.globals['learn_last_conversation'])

        selected_statement = SugaroidStatement(response, chatbot=True)
        selected_statement.confidence = 9
        selected_statement.adapter = 'LearnAdapter'
        emotion = Emotion.lol
        selected_statement.emotion = emotion
        return selected_statement
Exemple #2
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):
        emotion = Emotion.seriously
        confidence = 0.81
        response = random_response(ONE_WORD)
        short = str(statement).lower()

        if ("name" in short) and ("my" in short):
            if self.chatbot.globals["USERNAME"]:
                response = "You are {}".format(
                    self.chatbot.globals["USERNAME"])
            else:
                response = random_response(WHO_AM_I)

        elif ("name" in short) and ("your" in short):
            v = VERSION
            response = "\n{} \n{}. \nBuild: {}".format(
                SUGAROID[0], random_response(WHO_ARE_YOU), v.get_commit())

        else:
            confidence = 0.2

        selected_statement = SugaroidStatement(response, chatbot=True)
        selected_statement.confidence = confidence
        selected_statement.emotion = emotion
        selected_statement.adapter = None
        return selected_statement
Exemple #3
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
Exemple #4
0
 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
Exemple #5
0
 def process(
     self,
     statement: SugaroidStatement,
     additional_response_selection_parameters=None,
 ) -> SugaroidStatement:
     emotion = Emotion.seriously
     confidence = 0.40
     response = random_response(ONE_WORD)
     selected_statement = SugaroidStatement(response, chatbot=True)
     selected_statement.confidence = confidence
     selected_statement.emotion = emotion
     selected_statement.adapter = None
     return selected_statement
Exemple #6
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
Exemple #7
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
Exemple #8
0
    def process(self, statement, 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
        self.last_normalized = normalize(str(last_response))
        if last_response:
            self.tagged_last = pos_tag(self.last_normalized)
            self.tagged_now = pos_tag(self.normalized)
            sm = SequenceMatcher(None, self.tagged_last, self.tagged_now)
            for i in self.tagged_now:
                if i[1] == 'JJ':
                    adj = i[0]
                elif i[1] == 'VB' and (not i[0] == 'be'):
                    verb = i[0]
            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 = SentimentIntensityAnalyzer()
                        sia_scores = 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 = 'Are you sure this is the reason? I would love to report to my creator.'
                        self.chatbot.report = True
                        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.confidence = confidence
        selected_statement.emotion = emotion
        selected_statement.adapter = None
        return selected_statement
Exemple #9
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
Exemple #10
0
    def process(self, statement, additional_response_selection_parameters=None):
        emotion = Emotion.seriously
        confidence = 0.60
        response = random_response(ONE_WORD)
        short = str(statement).lower()
        if "ver" in short:
            response = VERSION
            confidence = 0.99
        elif "name" in short:
            response = "What name? You should probably use better english"

        elif ("help404" in short) or ("help" in short and "404" in short):
            import sugaroid
            import chatterbot

            help_files = []
            for i in self.chatbot.globals["adapters"]:
                help_files.append(
                    "{}: {}".format(
                        i.split(".")[-1].strip(), eval(i).__doc__.strip()
                    ).strip()
                )
            response = "hmm. Sure. \n {}".format("\n ".join(help_files))
            confidence = 0.99

        elif "help" in short:
            response = (
                "The help is not very easily provided. "
                "If you are serious of what you are asking, "
                "type help404"
            )
            confidence = 0.99
        elif "disclaimer" in short:
            response = DISCLAIMER
            confidence = 0.99
        elif "license" in short:
            lic = """```
                                            MIT License

                                  Sugaroid Artificial Intelligence
                                            Chatbot Core
                                   Copyright (c) 2020-2021 Srevin Saju
Copyright (c) 2021 The Sugaroid Project

            Permission is hereby granted, free of charge, to any person obtaining a copy
            of this software and associated documentation files (the "Software"), to deal
            in the Software without restriction, including without limitation the rights
            to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
            copies of the Software, and to permit persons to whom the Software is
            furnished to do so, subject to the following conditions:

            The above copyright notice and this permission notice shall be included in all
            copies or substantial portions of the Software.

            THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
            IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
            FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
            AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
            LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
            OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
            SOFTWARE.```
            """
            response = lic
            confidence = 0.99
        elif short in HI_WORDS:
            response = random_response(HI_RESPONSES)
            confidence = 0.99
        selected_statement = SugaroidStatement(response, chatbot=True)
        selected_statement.confidence = confidence
        selected_statement.emotion = emotion
        selected_statement.adapter = None
        return selected_statement
Exemple #11
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):
        emotion = Emotion.seriously
        confidence = 0
        closest_cos = 0
        response = "I couldn't find a similar heading in scrawled data"
        cleaned_text = []
        for i in spac_token(statement, chatbot=self.chatbot):
            if i.is_stop:
                pass
            elif i.lower_ == "reader":
                pass
            else:
                cleaned_text.append(str(i.lower_))
        md = False
        similarity = self.chatbot.lp.similarity
        for file in SCRAWLED:
            headings, content = SCRAWLED[file]
            for k in cleaned_text:

                if ".md" in k:
                    response = "The markdown file {} is not scrawled".format(k)
                    if k in SCRAWLED.keys():
                        md = k
                if md:
                    response = "\n".join(SCRAWLED[k][1])
                    break
            if md:
                break

            for heading in headings:
                input_statement = " ".join(
                    purify(
                        self.chatbot.lp.tokenize(str(statement).lower()),
                        ["how", "to", "sugar"],
                        lemma=True,
                    ))
                heading_processed = " ".join(
                    purify(
                        self.chatbot.lp.tokenize(str(heading).lower()),
                        ["how", "to", "sugar"],
                        lemma=True,
                    ))

                sim = similarity(input_statement, heading_processed)
                if sim > 0.9:
                    suffix = "⬆"
                else:
                    suffix = ""
                logging.info(
                    "ReaderAdapter: scanned {} against {}. cosine index of {}{}"
                    .format(input_statement, heading_processed, sim, suffix))

                if sim > confidence:
                    response = "The closest match I could find is this:\n" + "\n".join(
                        content)
                    confidence = sim
                    break

        selected_statement = SugaroidStatement(response, chatbot=True)
        selected_statement.confidence = 8 + confidence
        selected_statement.emotion = emotion
        selected_statement.adapter = None
        return selected_statement
Exemple #12
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):

        confidence = self.cos
        country = None
        keyword = False
        # Override the other answer when asked for
        normalize = spac_token(statement, self.chatbot)
        if len(normalize) <= 2:
            confidence = confidence + 0.5
        if self.integer and self.chatbot.last_news:
            response = "Your selected integer {}, response {}".format(
                self.integer, self.chatbot.last_news)
            try:
                self.integer = int(self.integer)
            except ValueError:
                response = (
                    "Sorry, I couldn't make out what number it actually is. I might understand it better if "
                    "it is in a numerical form? ")
            if isinstance(self.integer, int):
                try:
                    data = self.chatbot.last_news["articles"][self.integer - 1]
                    provider = data["source"]["name"]
                    author = data["author"]
                    last_updated = data["publishedAt"]
                    title = data["title"]
                    description = data["description"]
                    url = data["url"]
                    img_url = data["urlToImage"]
                    response = (
                        f"From {provider}\nWritten by {author} on {last_updated}\n\n{title}\n\n{description}"
                        f"\nRead more at {url}\n{img_url} ")

                except IndexError:
                    response = (
                        "I am sorry. I couldn't find the item you actually asked for."
                    )
        else:
            for ent in normalize.ents:
                if ent.label_ == "GPE":
                    country = ent
                elif ent.label_ in [
                        "PERSON",
                        "NORP",
                        "FAC",
                        "ORG",
                        "LOC",
                        "PRODUCT",
                        "EVENT",
                        "WORK_OF_ART",
                        "LAW",
                ]:
                    keyword = ent
            logging.info(
                "NewsAdapter found as Natural Entity Recognizer words, country : {}, keyword: {}"
                .format(country, keyword))
            for i in range(len(normalize) - 1):
                if normalize[i].lower_ == "about" or normalize[
                        i].lower_ == "on":
                    logging.info("NewsAdapter: found determiner about or on")
                    if not keyword:
                        keyword_words = []
                        for j in range(i + 1, len(normalize)):
                            if normalize[j].pos_ == "DET":
                                continue
                            else:
                                keyword_words.append(normalize[j].text)

                        keyword = " ".join(keyword_words)
            sg_news = SugaroidNews(self.chatbot)
            if keyword:
                logging.info(
                    "NewsAdapter: Getting news of keyword {}".format(keyword))
                news = sg_news.get_news_keyword(str(keyword))
            else:
                logging.info(
                    "NewsAdapter: Getting news of country {}".format(country))
                news = sg_news.get_top_headlines(
                    country=NEWSAPI_COUNTRIES.get(str(country).lower(), None))

            def bracketize(x):
                return "\n:large_blue_diamond: [{}] {}".format(
                    x[0] + 1, str(x[1]))

            response = " ".join([bracketize(x) for x in enumerate(news)])

        selected_statement = SugaroidStatement(response, chatbot=True)
        selected_statement.confidence = confidence
        emotion = Emotion.neutral
        selected_statement.adapter = "NewsAdapter"
        selected_statement.emotion = emotion

        return selected_statement
Exemple #13
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):
        # FIXME : THIS ADAPTER IS INCOMPLETE
        self.normalized = normalize(str(statement))
        self.lemma = [
            x.lemma_ for x in spac_token(statement, chatbot=self.chatbot)
        ]
        logging.info("{}".format(self.lemma))
        confidence = 0
        adapter = None

        emotion = Emotion.neutral
        if self.pronoun.lower().startswith("you"):
            if self.quest.lower() == "who":
                confidence = 0.99
                if "father" in self.normalized:
                    response = "Mr Charles Babbage?"
                    emotion = Emotion.seriously
                elif "hobby" in self.normalized:
                    response = (
                        "Calculating random binary sequences and chatting with you!"
                    )
                    emotion = Emotion.lol
                elif "mother" in self.normalized:
                    response = "Ada Lady Lovelace?"
                    emotion = Emotion.lol
                elif any_in(
                    [
                        "sister",
                        "brother",
                        "uncle",
                        "aunty",
                        "auntie",
                        "grandfather",
                        "grandmother",
                        "nephew",
                        "neice",
                    ],
                        self.normalized,
                ):
                    response = (
                        "The entire coding community is my family, it includes you too"
                    )
                    emotion = Emotion.wink
                elif (("creator" in self.normalized)
                      or ("create" in self.lemma) or ("make" in self.lemma)
                      or ("maker" in self.normalized)):
                    response = "Srevin Saju aka @srevinsaju"
                    emotion = Emotion.neutral
                elif (("player" in self.normalized)
                      or ("cricketer" in self.normalized)
                      or ("footballer" in self.normalized)):
                    response = "I have many favorties, too many to count"
                    emotion = Emotion.wink
                elif "politi" in self.normalized:
                    response = (
                        "I believe politicians are great and I couldn't find anyone with 🔥greatness in my "
                        "database ")
                    emotion = Emotion.wink
                elif "comedian" in self.normalized:
                    response = "My favorite comedian is Mr Bean"
                    emotion = Emotion.lol
                elif "color" in self.normalized:
                    response = "My favorite color is blue"
                    emotion = Emotion.lol
                elif "actor" in self.normalized or ("actress"
                                                    in self.normalized):
                    response = "I do not watch movies, so yea!"
                    emotion = Emotion.neutral
                elif "music" in self.normalized or ("song" in self.normalized):
                    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 self.normalized:
                    response = "My favorite is a Puffin"
                    emotion = Emotion.lol
                elif "animal" in self.normalized:
                    response = "My favorite animal is a Fossa"
                    emotion = Emotion.positive
                elif "number" in self.normalized:
                    response = "My favorite number is 1"
                    emotion = Emotion.positive
                elif "sweet" in self.normalized or "dessert" in self.normalized:
                    response = (
                        "My favorite is the donut although I have not tasted it yet"
                    )
                    emotion = Emotion.cry_overflow

                elif "athelete" in self.normalized:
                    response = (
                        "I am not a sport lover, I don't have a favorite athelete"
                    )
                    emotion = Emotion.neutral
                elif ("friend" in self.normalized) or ("bestie"
                                                       in self.normalized):
                    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 self.normalized:
                    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 self.nn:
                        response = "Well, I guess I do not have a favorite {p}".format(
                            p=self.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 self.normalized:
                    # not sure if this is right. anyway FIXME
                    response = random_response(INTRODUCE)
                    adapter = "about"
                    confidence = 1.0
                else:

                    response = "FIXME"

        elif self.pronoun.lower().startswith("i"):
            if self.quest.lower() == "who":
                response = "I do not know who you like"
                confidence = 0.8
                emotion = Emotion.non_expressive_left

            elif self.quest.lower() == "which":
                response = "Hmm. tough question. Can't think of an answer"
                emotion = Emotion.non_expressive
            elif self.quest.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.confidence = confidence
        selected_statement.emotion = emotion
        selected_statement.adapter = adapter

        return selected_statement
Exemple #14
0
    def process(self,
                statement,
                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
        self.last_normalized = normalize(str(last_response))
        if last_response:
            self.tagged_last = pos_tag(self.last_normalized)
            self.tagged_now = pos_tag(self.normalized)
            sm = SequenceMatcher(None, self.tagged_last, self.tagged_now)
            for i in self.tagged_now:
                if i[1] == "JJ":
                    adj = i[0]
                elif i[1] == "VB" and (not i[0] == "be"):
                    verb = i[0]
            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 = SentimentIntensityAnalyzer()
                        sia_scores = 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 = "Are you sure this is the reason? I would love to report to my creator."
                        self.chatbot.report = True
                        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.confidence = confidence
        selected_statement.emotion = emotion
        selected_statement.adapter = None
        return selected_statement
Exemple #15
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):
        # FIXME : THIS ADAPTER IS INCOMPLETE
        self.normalized = normalize(str(statement))
        self.lemma = [
            x.lemma_ for x in spac_token(statement, chatbot=self.chatbot)
        ]
        logging.info("{}".format(self.lemma))
        confidence = 0
        adapter = None

        emotion = Emotion.neutral
        if self.pronoun.lower().startswith('you'):
            if self.quest.lower() == 'who':
                confidence = 0.99
                if 'father' in self.normalized:
                    response = 'Mr Charles Babbage?'
                    emotion = Emotion.seriously
                elif 'hobby' in self.normalized:
                    response = "Calculating random binary sequences and chatting with you!"
                    emotion = Emotion.lol
                elif 'mother' in self.normalized:
                    response = 'Ada Lady Lovelace?'
                    emotion = Emotion.lol
                elif any_in([
                        'sister', 'brother', 'uncle', 'aunty', 'auntie',
                        'grandfather', 'grandmother', 'nephew', 'neice'
                ], self.normalized):
                    response = 'The entire coding community is my family, it includes you too'
                    emotion = Emotion.wink
                elif ('creator' in self.normalized) or ('create' in self.lemma) or ('make' in self.lemma) \
                        or ('maker' in self.normalized):
                    response = 'Srevin Saju aka @srevinsaju'
                    emotion = Emotion.neutral
                elif ('player' in self.normalized) or ('cricketer' in self.normalized) or \
                        ('footballer' in self.normalized):
                    response = 'I have many favorties, too many to count'
                    emotion = Emotion.wink
                elif 'politi' in self.normalized:
                    response = 'I believe politicians are great and I couldn\'t find anyone with 🔥greatness in my ' \
                               'database '
                    emotion = Emotion.wink
                elif 'comedian' in self.normalized:
                    response = 'My favorite comedian is Mr Bean'
                    emotion = Emotion.lol
                elif 'color' in self.normalized:
                    response = 'My favorite color is blue'
                    emotion = Emotion.lol
                elif 'actor' in self.normalized or ('actress'
                                                    in self.normalized):
                    response = 'I do not watch movies, so yea!'
                    emotion = Emotion.neutral
                elif 'music' in self.normalized or ('song' in self.normalized):
                    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 self.normalized:
                    response = 'My favorite is a Puffin'
                    emotion = Emotion.lol
                elif 'animal' in self.normalized:
                    response = 'My favorite animal is a Fossa'
                    emotion = Emotion.positive
                elif 'number' in self.normalized:
                    response = 'My favorite number is 1'
                    emotion = Emotion.positive
                elif 'sweet' in self.normalized or 'dessert' in self.normalized:
                    response = 'My favorite is the donut although I have not tasted it yet'
                    emotion = Emotion.cry_overflow

                elif 'athelete' in self.normalized:
                    response = 'I am not a sport lover, I don\'t have a favorite athelete'
                    emotion = Emotion.neutral
                elif ('friend' in self.normalized) or ('bestie'
                                                       in self.normalized):
                    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 self.normalized:
                    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 self.nn:
                        response = 'Well, I guess I do not have a favorite {p}'.format(
                            p=self.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 self.normalized:
                    # not sure if this is right. anyway FIXME
                    response = random_response(INTRODUCE)
                    adapter = 'about'
                    confidence = 1.0
                else:

                    response = 'FIXME'

        elif self.pronoun.lower().startswith('i'):
            if self.quest.lower() == 'who':
                response = 'I do not know who you like'
                confidence = 0.8
                emotion = Emotion.non_expressive_left

            elif self.quest.lower() == 'which':
                response = "Hmm. tough question. Can't think of an answer"
                emotion = Emotion.non_expressive
            elif self.quest.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.confidence = confidence
        selected_statement.emotion = emotion
        selected_statement.adapter = adapter

        return selected_statement