me encuentro trabajando en la programación de un chatbot utilizando Python 3.8 y PyQt5, pero he encontrado dos problemas que no he podido superar:
El primero ocurre con el script de python, al enviar un comando por voz, el script realiza la acción solicitada, pero al terminar de hacerlo, repite esta accion, es decir, que al solicitarle que me diga la hora o mi número telefónico, responde y lo hace indefinidamente hasta que recibe otro comando distinto que funciona pero hace lo mismo, repetirse indefinidamente.
El segundo problema consiste en que la interfaz gráfica funciona sólo al inicio de la ejecución del script, es decir, inicializo el script, recibo un saludo del bot y se abre la interfaz, completamente funcional y con el gif animado reproduciéndose, pero el resto del chatbot se detiene hasta no cerrar la ventana de la interfaz, al cerrarla el chatbot funciona normalmente salvo el primer problema que cité arriba.
Intenté las soluciones propuestas que se relacionan con estos problemas especialmente con la consideración de que tal vez estoy generando un método o función bloqueante en el caso del gif en la interfaz gráfica, pero encuentro que el problema sigue aún con la creación de un hilo para ejecutar la función bloqueante: el gif se reproduce dentro de la interfaz gráfica, pero mi programa principal permanece inactivo hasta que cierro la interfaz.
Agradezco de antemano la ayuda o comentarios que me proporcionen.
Reduje el código al mínimo:
from AssistantGif_ui import *
from PyQt5.QtWidgets import QMainWindow,QApplication,QLabel
from PyQt5.Qt import QMovie
import speech_recognition as sr
import pyttsx3
import pyjokes
import datetime
import time
listener = sr.Recognizer()
engine = pyttsx3.init()
rate = engine.getProperty('rate')
engine.setProperty("rate", 130)
volume = engine.getProperty('volume')
engine.setProperty('volume', volume-0.1)
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
now = datetime.datetime.now()
class Nueva(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self, *args, **kwargs):
QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.I = QLabel(self)
self.I.resize(450,500)
self.movi = QMovie("original.gif")
self.I.setMovie(self.movi)
self.movi.start()
theline = QtWidgets.QLineEdit(self)
theline.move(600, 140)
app = QApplication([])
n = Nueva()
n.resize(900,500)
n.show()
def speak(audio):
print('Assistant: ' + audio)
engine.say(audio)
engine.runAndWait()
def timeSett():
currentH = int(datetime.datetime.now().hour)
if currentH >= 0 and currentH < 12:
speak('Good Morning!')
if currentH >= 12 and currentH < 18:
speak('Good Afternoon!')
if currentH >= 18 and currentH != 0:
speak('Good Evening!')
timeSett()
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('Listenning...')
voice = listener.listen(source)
global command
command = listener.recognize_google(voice, language='en-english')
command = command.lower()
if 'Assistant' in command:
command = command.replace('Assistant','')
print(command)
except:
pass
return command
app.exec_()
def run_Assistant():
command = take_command()
print('command')
if 'what time is it' in command:
print("Current date and time : ")
print(now.strftime("The time is %H:%M"))
speak(now.strftime("The time is %H:%M"))
engine.runAndWait()
elif 'goodbye' in command:
print("Hasta la vista... Baby!")
speak("Hastala vista...Baby!")
exit()
elif 'what is my phone number' in command:
print('xx xx xx xx xx is your phone number sir')
talk('xx xx xx xx xx is your phone number sir')
elif 'tell me a joke' in command:
talk(pyjokes.get_joke('en'))
elif 'what time is it' in command:
print("Current date and time : ")
print(now.strftime("The time is %H:%M"))
speak(now.strftime("The time is %H:%M"))
engine.runAndWait()
else:
talk('just now im not ready for this')
while True:
run_Assistant()