def _updateProgramList(self) -> None: programsFile = FileManager.readFile("../DataBase/addedProgramms.db") self._programsList.clear() for row in programsFile: if row != '' and row != '\n' and row != ' ': self._programsList.update({ row.split(" = ")[0].lower(): row.split(" = ")[1].replace('\n', '') }) return
def __call__(self, textSource: str, srcLang: str) -> Exception: if srcLang != "en": textSource = self._translator.translate(text=textSource, dest="en", src=srcLang).text text_to_speech = TextToSpeechV1( iam_apikey="D6i3r45_nB2pNi_ewnSuZpu4ze_KexO9fBHtL1vs5E56", url="https://stream.watsonplatform.net/text-to-speech/api") audio = text_to_speech.synthesize(textSource, voice="en-US_AllisonV3Voice", accept="audio/ogg", codecs="opus") # This conversion is necessary, because TTS returns strange wav file that can use up a lot of RAM when played. FileManager.writeToFile(audio.get_result().content, "TEMP/sound.wav", "wb") AudioSegment.from_ogg("TEMP/sound.wav").export("TEMP/sound.wav", format="wav") return
def training(dataSet: dict, Val_split=0.1) -> None: if not FileManager.fileExist("../DataBase/models/model.pkl"): FileManager.createFile("../DataBase/models/model.pkl") else: self._text_clf = joblib.load("../DataBase/models/model.pkl") # fit and train the model lenght = len(dataSet['text']) if lenght > 10: indexes = arange(lenght) random.shuffle(indexes) X = [dataSet['text'][i] for i in indexes] Y = [dataSet['tag'][i] for i in indexes] nb_valid_samples = int(Val_split * lenght) trained = { 'train': { 'x': X[:-nb_valid_samples], 'y': Y[:-nb_valid_samples] }, 'test': { 'x': X[-nb_valid_samples:], 'y': Y[-nb_valid_samples:] } } self._text_clf.fit(trained['train']['x'], trained['train']['y']) self._text_clf.predict(trained['test']['x']) # save the model to disk joblib.dump(self._text_clf, "../DataBase/models/model.pkl", compress=3, protocol=4) return
def _getDataFromDB(self) -> None: ''' Check language choice and parse needed files. ''' def readFileToList(listOBJ: list, file: str) -> None: file = FileManager.readFile(file) listOBJ.clear() for line in file: listOBJ.append(line.replace('\n', '')) return # Parse data set only once. if len(self._dataSet) == 0 and FileManager.fileExist( "../DataBase/DataSet.db") == True: readFileToList(self._dataSet, "../DataBase/DataSet.db") readFileToList(self._stopWords, "../DataBase/stopWords" + self._lang.upper() + ".db") readFileToList(self._answerText, "../DataBase/answers" + self._lang.upper() + ".db") return
def changeLanguage(self, lang: str) -> None: self.serviceExpressions = FileManager.readFile( "../DataBase/ServiceExpressions" + lang.upper() + ".db") return
def addProgram(self, program: str, path: str) -> None: FileManager.writeToFile(program + " = " + path + '\n', "../DataBase/addedProgramms.db") self._updateProgramList() return
def conversation(self, enableVoice: bool, userInput="") -> str: ''' Start the conversation with the bot. ''' def _startChat(userInput: str) -> str: chatAnswer = self._chat.launch(userInput) try: self._doAction(self._chat.getInputType()) except (FileNotFoundError, OSError): exc = FileNotFoundError() exc.errno = 1 self._exceptionStack.append(exc) return str( self._dialog.getMessageFor("progNotFound") + " " + self._dialog.getMessageFor("addProg")).replace('\n', '') return chatAnswer chatAnswer = str() try: if enableVoice: self._setVoice(True) if self.getVoice(): try: userInput = voiceInput() except ValueError: userInput = "" self._update() chatAnswer = _startChat(userInput) except FileNotFoundError as exception: if exception.errno == 1 and userInput == 'Y' or userInput == 'y': self._exceptionStack[0].errno = 2 chatAnswer = self._dialog.getMessageFor( "addProgName") + " " + self._dialog.getMessageFor( "addProgPath") elif exception.errno == 2: parsedInput = userInput.split(" = ") try: if self.getPathToProgram( sub('[\t, \n, \r, \s]', '', parsedInput[0])): chatAnswer = self._dialog.getMessageFor( "progNameExist") if (len(parsedInput) == 2): self._parsedInput = parsedInput else: self._exceptionStack[0].errno = 0 # Replace program's path if userInput == "R" or userInput == "r": self._programsList[self._parsedInput[0].lower( )] = self._parsedInput[1].replace('\n', '') FileManager.clearFile("../DataBase/addedProgramms.db") for key, value in self._programsList.items(): FileManager.writeToFile( key + " = " + value + '\n', "../DataBase/addedProgramms.db", 'a') self._exceptionStack[0].errno = 1 chatAnswer = _startChat("open " + self._parsedInput[0]) self._parsedInput.clear() # Change the name of adding program elif len(parsedInput ) == 1 and self._exceptionStack[0].errno == 0: self._parsedInput[0] = parsedInput[0].lower() if self._exceptionStack[0].errno == 0: self._exceptionStack.pop(0) # this is a crutch to init self._parsedInput when adding a new programm # and the crutch to save self._parsedInput[0] when user change the name of the adding program if len(self._parsedInput) != 2: self._parsedInput = parsedInput self.addProgram( sub('[\t, \n, \r, \s]', '', self._parsedInput[0]), sub('[\t]', '', self._parsedInput[1]).replace("\n", '')) chatAnswer = _startChat("open " + self._parsedInput[0]) self._parsedInput.clear() except IndexError: chatAnswer = _startChat(userInput) self._parsedInput.clear() self._exceptionStack.pop(0) else: self._exceptionStack.pop(0) self._parsedInput.clear() chatAnswer = _startChat(userInput) except (ConnectionError, ConnectError): self._logger.writeLog() self._exceptionStack.pop(0) return self._dialog.getMessageFor("serviceError") except OSError as e: self._logger.writeLog() self._exceptionStack.pop(0) if e.errno == 6: return self._dialog.getMessageFor("errMicroDefine") elif e.errno == -9999: return self._dialog.getMessageFor("microAccesDenied").replace( '\n', " or ") + self._dialog.getMessageFor("errMicroDefine") else: return self._dialog.getMessageFor("error") except Exception: self._logger.logWrite() if len(self._exceptionStack) > 0: self._exceptionStack.pop(0) return self._dialog.getMessageFor("error") if self._voice: try: self._setVoice(False) self.tts(chatAnswer) except: self._logger.logWrite() return str( self._dialog.getMessageFor("serviceError") + chatAnswer) return chatAnswer
def readFileToList(listOBJ: list, file: str) -> None: file = FileManager.readFile(file) listOBJ.clear() for line in file: listOBJ.append(line.replace('\n', '')) return