1

Today I tried writing a voice assistant in Python for the first time. Using speech_recognition, pyttsx3, fuzzywuzzy, datetime, time, os. And soon faced with such a problem: My assistant executes the command only once, and then refuses to work. I understand that I need a loop for speak? I did this:

while True:
    speak(command)

and I did it differently but it still doesn't work. But I can't do it. Please explain to me what the error is. Here is my code for Repl.it - https://repl.it/repls/DownrightImpressiveChords#main.py This is my code -

# Audio-Bot Kevin  version - 1.0
import os
import time
import speech_recognition as sr
from fuzzywuzzy import fuzz
import pyttsx3
import datetime


opts = {

    "alias": ('кевин','кевинчик','кев','киев', 'бот'),
    "tbr": ('эй','скажи','расскажи','открой','сколько','произнеси'),
    "cmds": {
        "ctime": ('сколько сейчас времени','который час','текущее время', 'сколько время'),
        "radio": ('включи музыку','воспроизведи радио','открой радио'),
        "stupid1": ('расскажи анегдот','расскажи какой-нибудь анегдот','раскажи шутку','ты знаешь шутки','ты знаешь анегдоты'),
        "google_chrome": ('открой хром','открой браузер хром','открой гугл хром','открой браузер гугл хром'),
        "mozilla_firefox": ('открой фаерфокс','открой браузер фаерфокс','открой мозила фаерфокс','открой браузер мозила фаерфокс'),
        "browser_youtube": ('открой ютуб','открой вкладку ютуб','открой страницу ютуба','открой сайт ютуб')
    }
}



# functions
def speak(what):
    print( what )
    speak_engine = pyttsx3.init()
    speak_engine.say (what)
    speak_engine.runAndWait()
    speak_engine.stop()
 
def callback(recognizer, audio):
    try:
        voice = recognizer.recognize_google(audio, language = "ru-RU").lower()
        print("[log] Распознано: " + voice)
    
        if voice.startswith(opts["alias"]):
            # обращаются к Кеше
            cmd = voice
 
            for x in opts['alias']:
                cmd = cmd.replace(x, "").strip()
            
            for x in opts['tbr']:
                cmd = cmd.replace(x, "").strip()
            
            # распознаем и выполняем команду
            cmd = recognize_cmd(cmd)
            execute_cmd(cmd['cmd'])
 
    except sr.UnknownValueError:
        print("[log] Голос не распознан!")
    except sr.RequestError as e:
        print("[log] Неизвестная ошибка, проверьте интернет!")
 
def recognize_cmd(cmd):
    RC = {'cmd': '', 'percent': 0}
    for c,v in opts['cmds'].items():
 
        for x in v:
            vrt = fuzz.ratio(cmd, x)
            if vrt > RC['percent']:
                RC['cmd'] = c
                RC['percent'] = vrt
    
    return RC
 
def execute_cmd(cmd):
    if cmd == 'ctime':
        # сказать текущее время
        now = datetime.datetime.now()
        speak("Сейчас " + str(now.hour) + ":" + str(now.minute))
    
    elif cmd == 'radio':
        # воспроизвести радио
        os.system("D:\\Jarvis\\res\\radio_record.m3u")

    elif cmd == 'stupid1':
        # рассказать анекдот
        speak("Шутка про Ватсона. Поймал как-то Ватсон кошку, и накочал её бензином. После этого он отпустил кошку и тогда она пробежала 3 метра и упала. Бензин закончился подумал Ватсон")

    else:
        print('Команда не распознана, повторите!')

# start
r = sr.Recognizer()
m = sr.Microphone(device_index = 1)
 
with m as source:
    r.adjust_for_ambient_noise(source)
 
speak_engine = pyttsx3.init()


speak("Здравствуйте, повелитель")
speak("Что прикажите?")

stop_listening = r.listen_in_background(m, callback)
while True:
    speak(command)

Thank you in advance!

HTTPs
  • 19
  • 5

1 Answers1

1

You need to run both recognition and synthesis in the loop:

while True:
    command = r.recognize_google()
    speak(command)

or run recognition and speak in the thread too:

# Processing goes there
def callback(r):
    command = r.recognize_google()
    speak(command)

# Here we run a thread
stop_listening = r.listen_in_background(m, callback)

# Here we just sleep and wait for other thread
while True:
    time.sleep(1.0)
Nikolay Shmyrev
  • 24,897
  • 5
  • 43
  • 87
  • Thank you for your answer! I have when adding this code while True: command = r.recognize_google() speak(command) an error occurs - TypeError: recognize_google() missing 1 required positional argument: 'audio_data' what causes this error? – HTTPs Aug 20 '20 at 20:25