Esempio n. 1
0
    def __init__(self):
        """
        Initializes the Text2Speech adapter for sugaroid

        The ``Text2Speech`` adapter includes a smart algorithm
        to automatically reduce downloads and cache messages
        so that they can be reused on every outgoing message
        from sugaroid. Sugaroid uses Google Speech API to
        convert text messages into audio files. The Speech
        materials ``(*.mp3)`` are stored in the default
        configuration as provided by the ``ConfigManager``

        Text2Speech Adapter can be used as

            >>> t2s = Text2Speech()
            >>> t2s.speak("Hello, I am Sugaroid")

        """

        self.cfgmgr = ConfigManager()
        if not os.path.exists(os.path.join(self.cfgmgr.get_cfgpath(), "tts")):
            os.makedirs(os.path.join(self.cfgmgr.get_cfgpath(), "tts"))
        self.tts_dir = os.path.join(self.cfgmgr.get_cfgpath(), "tts")
        if not os.path.exists(os.path.join(self.tts_dir,
                                           "let_me_try_that.mp3")):
            gTTS("Let me try that,").save(
                os.path.join(self.tts_dir, "let_me_try_that.mp3"))
        if not os.path.exists(
                os.path.join(self.tts_dir, "why_do_you_think.mp3")):
            gTTS("Why do you think").save(
                os.path.join(self.tts_dir, "why_do_you_think.mp3"))
        if not os.path.exists(
                os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3")):
            gTTS("Did you mean any of these?").save(
                os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3"))
Esempio n. 2
0
    def train(self, trainer):
        print('Initializing trainer')
        self.cfgmgr = ConfigManager()

        data = self.cfgmgr.get_config()
        il = []
        for i in data:
            il.append(i)
            trainer.train(data[i])
        with open(os.path.join(self.cfgmgr.get_cfgpath(), 'data.json'),
                  'w') as w:
            json.dump({"il": il}, w)
Esempio n. 3
0
class Text2Speech:
    def __init__(self):
        self.cfgmgr = ConfigManager()
        if not os.path.exists(os.path.join(self.cfgmgr.get_cfgpath(), "tts")):
            os.makedirs(os.path.join(self.cfgmgr.get_cfgpath(), "tts"))
        self.tts_dir = os.path.join(self.cfgmgr.get_cfgpath(), "tts")
        if not os.path.exists(os.path.join(self.tts_dir, "let_me_try_that.mp3")):
            gTTS("Let me try that,").save(
                os.path.join(self.tts_dir, "let_me_try_that.mp3")
            )
        if not os.path.exists(os.path.join(self.tts_dir, "why_do_you_think.mp3")):
            gTTS("Why do you think").save(
                os.path.join(self.tts_dir, "why_do_you_think.mp3")
            )
        if not os.path.exists(
            os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3")
        ):
            gTTS("Did you mean any of these?").save(
                os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3")
            )

    def speak(self, args):
        let_me = False
        why_do = False
        did_you_mean = False
        if args.lower().startswith("let me try that"):
            text = args.lower().lstrip("let me try that")
            print("TTS: ", text)
            let_me = True
        elif args.lower().startswith("why do you think"):
            text = args.lower().lstrip("why do you think")
            why_do = True
        elif "ok ok" in args.lower():
            text = "ok ok"
        elif "did you mean any of" in args.lower():
            did_you_mean = True
            text = "Did you mean any of these?"
        else:
            text = args
        if len(text) > 50:
            text = text.split(".")[0]
        processed = text.lower().replace(" ", "_") + ".mp3"
        path = os.path.join(self.tts_dir, processed)
        if os.path.exists(path):
            pass
        else:
            en = gTTS(text)
            en.save(path)
        if why_do:
            playsound(os.path.join(self.tts_dir, "why_do_you_think.mp3"))
        if let_me:
            playsound(os.path.join(self.tts_dir, "let_me_try_that.mp3"))
        playsound(path)
Esempio n. 4
0
class Text2Speech:
    def __init__(self):
        self.cfgmgr = ConfigManager()
        if not os.path.exists(os.path.join(self.cfgmgr.get_cfgpath(), 'tts')):
            os.makedirs(os.path.join(self.cfgmgr.get_cfgpath(), 'tts'))
        self.tts_dir = os.path.join(self.cfgmgr.get_cfgpath(), 'tts')
        if not os.path.exists(os.path.join(self.tts_dir,
                                           'let_me_try_that.mp3')):
            gTTS('Let me try that,').save(
                os.path.join(self.tts_dir, 'let_me_try_that.mp3'))
        if not os.path.exists(
                os.path.join(self.tts_dir, 'why_do_you_think.mp3')):
            gTTS('Why do you think').save(
                os.path.join(self.tts_dir, 'why_do_you_think.mp3'))
        if not os.path.exists(
                os.path.join(self.tts_dir, 'did_you_mean_any_of_these.mp3')):
            gTTS('Did you mean any of these?').save(
                os.path.join(self.tts_dir, 'did_you_mean_any_of_these.mp3'))

    def speak(self, args):
        let_me = False
        why_do = False
        did_you_mean = False
        if args.lower().startswith('let me try that'):
            text = args.lower().lstrip('let me try that')
            print("TTS: ", text)
            let_me = True
        elif args.lower().startswith('why do you think'):
            text = args.lower().lstrip('why do you think')
            why_do = True
        elif 'ok ok' in args.lower():
            text = 'ok ok'
        elif 'did you mean any of' in args.lower():
            did_you_mean = True
            text = 'Did you mean any of these?'
        else:
            text = args
        if len(text) > 50:
            text = text.split('.')[0]
        processed = text.lower().replace(' ', '_') + '.mp3'
        path = os.path.join(self.tts_dir, processed)
        if os.path.exists(path):
            pass
        else:
            en = gTTS(text)
            en.save(path)
        if why_do:
            playsound(os.path.join(self.tts_dir, 'why_do_you_think.mp3'))
        if let_me:
            playsound(os.path.join(self.tts_dir, 'let_me_try_that.mp3'))
        playsound(path)
Esempio n. 5
0
class SugaroidTrainer:
    def __init__(self):
        self.cfgmgr = None
        print("Sugaroid Trainer v{}".format(__version__))

    def train(self, trainer):
        print('Initializing trainer')
        self.cfgmgr = ConfigManager()

        data = self.cfgmgr.get_config()
        il = []
        for i in data:
            il.append(i)
            trainer.train(data[i])
        with open(os.path.join(self.cfgmgr.get_cfgpath(), 'data.json'),
                  'w') as w:
            json.dump({"il": il}, w)

    def modify(self):
        pass

    @staticmethod
    def prompt_cli():
        try:
            a = input("trainer @>")
            if a == "Q" or a == 'q':
                return False
            return a
        except KeyboardInterrupt:
            return False

    def reset(self):
        self.cfgmgr.reset_config()

    def write(self):
        self.cfgmgr.update_config(self.data)
        self.cfgmgr.write_file()

    def trainer_init(self):
        self.cfgmgr = ConfigManager()
        self.data = self.cfgmgr.get_config()
        self.trainer = []

    def trainer_cli(self):
        while True:
            conversation = self.prompt_cli()
            if conversation:
                self.trainer.append(conversation)
            else:
                break
        self.data["{}".format(time.time())] = self.trainer
        self.write()
Esempio n. 6
0
 def __init__(self):
     self.cfgmgr = ConfigManager()
     if not os.path.exists(os.path.join(self.cfgmgr.get_cfgpath(), 'tts')):
         os.makedirs(os.path.join(self.cfgmgr.get_cfgpath(), 'tts'))
     self.tts_dir = os.path.join(self.cfgmgr.get_cfgpath(), 'tts')
     if not os.path.exists(os.path.join(self.tts_dir,
                                        'let_me_try_that.mp3')):
         gTTS('Let me try that,').save(
             os.path.join(self.tts_dir, 'let_me_try_that.mp3'))
     if not os.path.exists(
             os.path.join(self.tts_dir, 'why_do_you_think.mp3')):
         gTTS('Why do you think').save(
             os.path.join(self.tts_dir, 'why_do_you_think.mp3'))
     if not os.path.exists(
             os.path.join(self.tts_dir, 'did_you_mean_any_of_these.mp3')):
         gTTS('Did you mean any of these?').save(
             os.path.join(self.tts_dir, 'did_you_mean_any_of_these.mp3'))
Esempio n. 7
0
 def __init__(self):
     self.cfgmgr = ConfigManager()
     if not os.path.exists(os.path.join(self.cfgmgr.get_cfgpath(), "tts")):
         os.makedirs(os.path.join(self.cfgmgr.get_cfgpath(), "tts"))
     self.tts_dir = os.path.join(self.cfgmgr.get_cfgpath(), "tts")
     if not os.path.exists(os.path.join(self.tts_dir, "let_me_try_that.mp3")):
         gTTS("Let me try that,").save(
             os.path.join(self.tts_dir, "let_me_try_that.mp3")
         )
     if not os.path.exists(os.path.join(self.tts_dir, "why_do_you_think.mp3")):
         gTTS("Why do you think").save(
             os.path.join(self.tts_dir, "why_do_you_think.mp3")
         )
     if not os.path.exists(
         os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3")
     ):
         gTTS("Did you mean any of these?").save(
             os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3")
         )
Esempio n. 8
0
    def __init__(self, readonly=True):
        self.trainer = None
        self.corpusTrainer = None
        self.neuron = None
        self.audio = 'audio' in sys.argv
        self.cfgmgr = ConfigManager()
        self.cfgpath = self.cfgmgr.get_cfgpath()
        self.database = SqlDatabaseManagement(
            os.path.join(self.cfgpath, 'sugaroid_internal.db'))
        self.database_exists = os.path.exists(
            os.path.join(self.cfgpath, 'sugaroid.db'))
        self.commands = [
            'sugaroid.brain.debug.DebugAdapter',
            'sugaroid.brain.interrupt.InterruptAdapter',
            'sugaroid.brain.learn.LearnAdapter',
        ]
        self.adapters = [
            'sugaroid.brain.yesno.BoolAdapter',
            'sugaroid.brain.aki.AkinatorAdapter',
            'sugaroid.brain.hangman.HangmanAdapter',
            'sugaroid.brain.either.OrAdapter',
            'sugaroid.brain.ok.OkayAdapter',
            'sugaroid.brain.bye.ByeAdapter',
            'sugaroid.brain.time.TimeAdapter',
            'sugaroid.brain.convert.CurrencyAdapter',
            'sugaroid.brain.trivia.TriviaAdapter',
            'sugaroid.brain.whoami.WhoAdapter',
            'sugaroid.brain.news.NewsAdapter',
            'sugaroid.brain.joke.JokeAdapter',
            'sugaroid.brain.play.PlayAdapter',
            'sugaroid.brain.let.LetAdapter',
            'sugaroid.brain.whatwhat.WhatWhatAdapter',
            'sugaroid.brain.waitwhat.WaitWhatAdapter',
            'sugaroid.brain.assertive.AssertiveAdapter',
            'sugaroid.brain.canmay.CanAdapter',
            'sugaroid.brain.because.BecauseAdapter',
            'sugaroid.brain.rereversei.ReReverseAdapter',
            'sugaroid.brain.reversethink.ReverseAdapter',
            'sugaroid.brain.covid.CovidAdapter',
            'sugaroid.brain.myname.MyNameAdapter',
            'sugaroid.brain.iam.MeAdapter',
            'sugaroid.brain.about.AboutAdapter',
            'sugaroid.brain.wiki.WikiAdapter',
            'sugaroid.brain.dolike.DoLikeAdapter',
            'sugaroid.brain.feel.FeelAdapter',
            'sugaroid.brain.dolike.DoLikeAdapter',
            'sugaroid.brain.do.DoAdapter',
            'sugaroid.brain.emotion.EmotionAdapter',
            'sugaroid.brain.dis.DisAdapter',
            'sugaroid.brain.twoword.TwoWordAdapter',
            'sugaroid.brain.oneword.OneWordAdapter',
            'sugaroid.brain.why.WhyWhenAdapter',
            'sugaroid.brain.reader.ReaderAdapter',
            'sugaroid.brain.imitate.ImitateAdapter',
            'sugaroid.brain.fun.FunAdapter',
            'chatterbot.logic.UnitConversion',
        ]

        if self.audio:
            self.tts = Text2Speech()
        else:
            self.tts = None

        self.chatbot = SugaroidBot(
            'Sugaroid',
            storage_adapter='chatterbot.storage.SQLStorageAdapter',
            logic_adapters=self.commands +
            [{
                'import_path': 'chatterbot.logic.BestMatch',
                'maximum_similarity_threshold': 0.80
            }] + self.adapters,
            database_uri='sqlite+pysqlite:///{}/sugaroid.db'.format(
                self.cfgpath),
            read_only=readonly)
        self.chatbot.globals['adapters'] = self.adapters

        self.read()
        self.invoke_brain()
Esempio n. 9
0
class Sugaroid:
    """
    Sugaroid
    Initates the chatbot class and connects logic Adapters together.
    Initates the ConfigManager to store sugaroid data and connects scans
    sys.argv

    """
    def __init__(self, readonly=True):
        self.trainer = None
        self.corpusTrainer = None
        self.neuron = None
        self.audio = 'audio' in sys.argv
        self.cfgmgr = ConfigManager()
        self.cfgpath = self.cfgmgr.get_cfgpath()
        self.database = SqlDatabaseManagement(
            os.path.join(self.cfgpath, 'sugaroid_internal.db'))
        self.database_exists = os.path.exists(
            os.path.join(self.cfgpath, 'sugaroid.db'))
        self.commands = [
            'sugaroid.brain.debug.DebugAdapter',
            'sugaroid.brain.interrupt.InterruptAdapter',
            'sugaroid.brain.learn.LearnAdapter',
        ]
        self.adapters = [
            'sugaroid.brain.yesno.BoolAdapter',
            'sugaroid.brain.aki.AkinatorAdapter',
            'sugaroid.brain.hangman.HangmanAdapter',
            'sugaroid.brain.either.OrAdapter',
            'sugaroid.brain.ok.OkayAdapter',
            'sugaroid.brain.bye.ByeAdapter',
            'sugaroid.brain.time.TimeAdapter',
            'sugaroid.brain.convert.CurrencyAdapter',
            'sugaroid.brain.trivia.TriviaAdapter',
            'sugaroid.brain.whoami.WhoAdapter',
            'sugaroid.brain.news.NewsAdapter',
            'sugaroid.brain.joke.JokeAdapter',
            'sugaroid.brain.play.PlayAdapter',
            'sugaroid.brain.let.LetAdapter',
            'sugaroid.brain.whatwhat.WhatWhatAdapter',
            'sugaroid.brain.waitwhat.WaitWhatAdapter',
            'sugaroid.brain.assertive.AssertiveAdapter',
            'sugaroid.brain.canmay.CanAdapter',
            'sugaroid.brain.because.BecauseAdapter',
            'sugaroid.brain.rereversei.ReReverseAdapter',
            'sugaroid.brain.reversethink.ReverseAdapter',
            'sugaroid.brain.covid.CovidAdapter',
            'sugaroid.brain.myname.MyNameAdapter',
            'sugaroid.brain.iam.MeAdapter',
            'sugaroid.brain.about.AboutAdapter',
            'sugaroid.brain.wiki.WikiAdapter',
            'sugaroid.brain.dolike.DoLikeAdapter',
            'sugaroid.brain.feel.FeelAdapter',
            'sugaroid.brain.dolike.DoLikeAdapter',
            'sugaroid.brain.do.DoAdapter',
            'sugaroid.brain.emotion.EmotionAdapter',
            'sugaroid.brain.dis.DisAdapter',
            'sugaroid.brain.twoword.TwoWordAdapter',
            'sugaroid.brain.oneword.OneWordAdapter',
            'sugaroid.brain.why.WhyWhenAdapter',
            'sugaroid.brain.reader.ReaderAdapter',
            'sugaroid.brain.imitate.ImitateAdapter',
            'sugaroid.brain.fun.FunAdapter',
            'chatterbot.logic.UnitConversion',
        ]

        if self.audio:
            self.tts = Text2Speech()
        else:
            self.tts = None

        self.chatbot = SugaroidBot(
            'Sugaroid',
            storage_adapter='chatterbot.storage.SQLStorageAdapter',
            logic_adapters=self.commands +
            [{
                'import_path': 'chatterbot.logic.BestMatch',
                'maximum_similarity_threshold': 0.80
            }] + self.adapters,
            database_uri='sqlite+pysqlite:///{}/sugaroid.db'.format(
                self.cfgpath),
            read_only=readonly)
        self.chatbot.globals['adapters'] = self.adapters

        self.read()
        self.invoke_brain()

    def init_local_trainers(self):
        """
        Init local trainers with minimum conversation
        :return:
        """
        # initialize the trainer
        self.trainer = ListTrainer(self.chatbot)
        self.corpusTrainer = ChatterBotCorpusTrainer(self.chatbot)

    def list_train(self, li):
        self.trainer.train(li)

    def interrupt_ds(self):
        self.chatbot.interrupt = 2

    def disable_interrupt_ds(self):
        self.chatbot.interrupt = 0

    def toggle_discord(self):
        self.chatbot.discord = not self.chatbot.discord

    def append_author(self, author):
        self.chatbot.authors.append(author)

    def read(self):
        """
        Train Sugaroid database from the sugaroid.trainer.json located in the configuration directory
        if it exists. If the sugaroid.db file exists, the Database update is skipped

        :return:
        """
        if 'train' in sys.argv:
            from sugaroid.trainer.trainer import main as trainer
            # FIXME replace with dynamic trainer i.e GUI + CLI
            trainer()
        else:
            if self.database_exists:
                print("Database already exists")
                pass
            else:
                if self.trainer is None:
                    self.init_local_trainers()

                st = SugaroidTrainer()
                st.train(self.trainer)
                self.corpus()
        if 'update' in sys.argv:
            if self.trainer is None:
                self.init_local_trainers()

            st = SugaroidTrainer()
            st.train(self.trainer)

    def write(self):
        raise NotImplementedError

    def corpus(self):
        """
        Train data if it doesn't exists.
        Periodically update the data too
        :return: True when the process is complete
        """
        db_dir = os.path.join(os.path.dirname(__file__), 'data', 'sugaroid.db')
        shutil.copy(db_dir, os.path.join(self.cfgpath, 'sugaroid.db'))
        return True

    def invoke_brain(self):
        """
        Initiate the Brain
        :return:
        """
        self.neuron = Neuron(self.chatbot)

    def parse(self, args):
        """
        Do a simple parsing of the init statement. Classify statement on the
        type of input_statement
        and confidence of each statement
        :param args:
        :return:
        """
        if isinstance(args, str):
            preflight_time = time.time()
            response = self.neuron.parse(args)
            self.chatbot.globals['history']['total'].append(response)
            self.chatbot.globals['history']['user'].append(args)
            success_time = time.time()
            delta_time = success_time - preflight_time
            try:
                _text_response = response.text
            except AttributeError:
                _text_response = response

            assert isinstance(_text_response, str)
            if 'gui' not in sys.argv:
                try:
                    self.database.append(statement=_text_response,
                                         in_reponse_to=args,
                                         time=preflight_time,
                                         processing_time=delta_time)
                except Exception:
                    # to protect our system, we sh
                    pass
            return response
        else:
            raise ValueError("Invalid data type passed to Sugaroid.parse")

    def prompt_cli(self):
        """
        Classic prompt for Sugaroid Command Line Interface
        :return:
        """

        response = self.parse(input(Fore.CYAN + '( ဖ‿ဖ) @> ' + Fore.RESET))
        return response

    def display_cli(self, response):
        """
        Classic display adapter for TTY Sugaroid Command Line Interface
        :param response:
        :return:
        """
        try:
            print(Style.BRIGHT + Fore.GREEN + "sugaroid: " + Fore.RESET +
                  Style.RESET_ALL + Fore.BLUE + emojize(response.text) +
                  Fore.RESET + "\n")
        except AttributeError:
            print(Style.BRIGHT + Fore.GREEN + "sugaroid: " + Fore.RESET +
                  Style.RESET_ALL + Fore.BLUE + emojize(response) +
                  Fore.RESET + "\n")
        if self.audio:
            self.tts.speak(str(response))

    def loop_cli(self):
        """
        Sugaroid loop_cli for Sugaroid Command Line Interface
        :return:
        """
        try:
            while True:
                self.display_cli(self.prompt_cli())
        except (KeyboardInterrupt, EOFError):
            self.database.close()

    def loop_gui(self):
        """
        Launch the sugaroid PyQt5 gui with Breeze theme and custom features
        If PyQt5 not installed, raise ModuleNotFoundError
        :return:
        """
        if not GUI_DEPS:
            raise ModuleNotFoundError(
                "PyQt5 is not Installed. Install it by pip3 install PyQt5")

        print("Launching GUI")
        QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
        QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps,
                                  True)  # use highdpi icons
        app = QtWidgets.QApplication(sys.argv)
        app.setStyle('Breeze')
        from sugaroid.gui.ux import InterfaceSugaroidQt
        window = InterfaceSugaroidQt(parent=self)
        window.init()
        try:
            app.exec_()
        except KeyboardInterrupt:
            pass
        self.database.close()
Esempio n. 10
0
 def trainer_init(self):
     self.cfgmgr = ConfigManager()
     self.data = self.cfgmgr.get_config()
     self.trainer = []
Esempio n. 11
0
class Text2Speech:
    def __init__(self):
        """
        Initializes the Text2Speech adapter for sugaroid

        The ``Text2Speech`` adapter includes a smart algorithm
        to automatically reduce downloads and cache messages
        so that they can be reused on every outgoing message
        from sugaroid. Sugaroid uses Google Speech API to
        convert text messages into audio files. The Speech
        materials ``(*.mp3)`` are stored in the default
        configuration as provided by the ``ConfigManager``

        Text2Speech Adapter can be used as

            >>> t2s = Text2Speech()
            >>> t2s.speak("Hello, I am Sugaroid")

        """

        self.cfgmgr = ConfigManager()
        if not os.path.exists(os.path.join(self.cfgmgr.get_cfgpath(), "tts")):
            os.makedirs(os.path.join(self.cfgmgr.get_cfgpath(), "tts"))
        self.tts_dir = os.path.join(self.cfgmgr.get_cfgpath(), "tts")
        if not os.path.exists(os.path.join(self.tts_dir,
                                           "let_me_try_that.mp3")):
            gTTS("Let me try that,").save(
                os.path.join(self.tts_dir, "let_me_try_that.mp3"))
        if not os.path.exists(
                os.path.join(self.tts_dir, "why_do_you_think.mp3")):
            gTTS("Why do you think").save(
                os.path.join(self.tts_dir, "why_do_you_think.mp3"))
        if not os.path.exists(
                os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3")):
            gTTS("Did you mean any of these?").save(
                os.path.join(self.tts_dir, "did_you_mean_any_of_these.mp3"))

    def speak(self, args: str):
        """
        Speaks a statement using gTTS or plays a downloaded file
        if the ``args`` matches the downloaded files name

        :param args: The text to speak
        :type args: str
        """
        let_me = False
        why_do = False
        did_you_mean = False
        if args.lower().startswith("let me try that"):
            text = args.lower().lstrip("let me try that")
            print("TTS: ", text)
            let_me = True
        elif args.lower().startswith("why do you think"):
            text = args.lower().lstrip("why do you think")
            why_do = True
        elif "ok ok" in args.lower():
            text = "ok ok"
        elif "did you mean any of" in args.lower():
            did_you_mean = True
            text = "Did you mean any of these?"
        else:
            text = args
        if len(text) > 50:
            text = text.split(".")[0]
        processed = text.lower().replace(" ", "_") + ".mp3"
        path = os.path.join(self.tts_dir, processed)
        if os.path.exists(path):
            pass
        else:
            en = gTTS(text)
            en.save(path)
        if why_do:
            playsound(os.path.join(self.tts_dir, "why_do_you_think.mp3"))
        if let_me:
            playsound(os.path.join(self.tts_dir, "let_me_try_that.mp3"))
        playsound(path)