Doing voice assistant on python

Question:

I need help. I have followed one of the tutorials. I have got a voice assistant, but it does only one command and than does not do anything. Can you help me to make him listen forever. So, it will always listen, but turn off only, when I close it.
PS: Please don’t pay attention on other language words.
Here is my code:

import pyttsx3
import os
import time
from fuzzywuzzy import fuzz
import datetime
import speech_recognition as sr

opts = {
    "alias": ("петя", "петечка", "петюлечка", "петрович", "петич", "петр", "петька", "петь"),
    "tbr": ("скажи", "расскажи", "покажи", "сколько", "произнеси"),
    "cmds": {
        "ctime": ("текущее время", "сейчас времени", "который час"),
        "radio": ("включи музыку", "воспроизведи радио", "включи радио"),
        "stupid1": ("расскажи анекдот")
    }
}

def speak(what):
    print(what)
    speak_engine.say(what)
    speak_engine.runAndWait()
    speak_engine.stop()

def callback(recongizer, audio):
    try:
        voice = recongizer.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 = recongize_cmd(cmd)
            execute_cmd(cmd['cmd'])
    except sr.UnknownValueError:
        print("[log] Голос не распознан!")
    except sr.RequestError as e:
        print("[log] Неизвестная ошибка, проверьте интернет")
def recongize_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("Мой разработчик не научил меня анекдотам ... Ха ха ха")
    else:
        print('Команда не распознана, повторите!')

r = sr.Recognizer()
m = sr.Microphone(device_index=1)
with m as sourse:
    r.adjust_for_ambient_noise(sourse)



speak_engine = pyttsx3.init()

speak("Привет")
speak("Петя слушает")

stop_listening = r.listen_in_background(m, callback)
while True: time.sleep(0.1)
Asked By: Resadesker

||

Answers:

I had to do speak_engine = pyttsx3.init() not in nearly end of the code, but place it in speak()

Answered By: Resadesker

Try this code for continuous voice input:

from googlesearch import search
import webbrowser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyaudio
import re
from tkinter import *
import google.auth
import threading
import subprocess
import requests
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import speech_recognition as sr
import pyttsx3
import wikipedia
import pywhatkit
import os
import glob
import webbrowser
from googlesearch import search
import webbrowser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyaudio
import threading
from multiprocessing import Process
import re
import time

listener = sr.Recognizer()
player = pyttsx3.init()
home_dir = "/Users/<user>/"

def talk(text):
    player.say(text)
    time.sleep(1)
    player.runAndWait()
    time.sleep(1)

def open_app(command):
    res = os.system("open /System/Applications/"+command+".app")
    if (res == 256):
        res = os.system("open /Applications/"+command)
        if (res == 256):
            talk("cannot find the app")

def listen(source):
    print("I am listening...")

    while 1:
        try:
            voice_content = listener.listen(source, phrase_time_limit = 10)
            text_command = listener.recognize_google(voice_content, language = 'en-in')
            text_command = text_command.lower()
            if text_command.startswith("Anukul"):
                text_command = text_command.replace("Anukul","")
            else:
                continue
        except:
            continue

        print(text_command)
    
    
        if "open application" in text_command:
            text_command = text_command.replace("open application", "").strip()
            x = threading.Thread(target=open_app, args=(text_command,))
            x.start()
        else:    
            input_command = vectorizer.transform([text_command])
            print (type(input_command))
            command_category_bow = clf_svm.predict(input_command)
            print(command_category_bow)
            extra_info = None

            if (command_category_bow[0] == 'OPEN_UI_PR'):
                words = text_command.split(' ')
                for i in words:
                    if i.strip().isnumeric():
                        extra_info = i
                        break

            t = threading.Thread(target=run_voice_bot, args=(command_category_bow[0], extra_info))
            t.start()
    

def run_voice_bot(command, extra_info):
    if "play" in command:
        command = command.replace("play", "")
        x = threading.Thread(target=play_video, args=(command,))
        x.start()
    elif "open application" in command:
        command = command.replace("open application", "").strip()
        x = threading.Thread(target=open_app, args=(command,))
        x.start()
    elif ("google" in command and "search" in command):
        command = command.replace(re.findall("search[a-zs]*google(?:withs)*(?:fors)*", command)[0], "").strip()
        command = command.replace(re.findall("search[a-zs]*google(?:withs)*(?:fors)*", command)[0], "").strip()
        x = threading.Thread(target=google_search, args=(command,))
        x.start()     
    elif ("open website" in command):
        command = command.replace("open website", "").strip()
        x = threading.Thread(target=open_website, args=(command,))
        x.start()
    elif ("open [a-zs]*last file [a-zs]*download[a-zs]*" in command):
        command = command.replace("open [a-zs]*last file [a- zs]*download[a-zs]*", "").strip()
        last_file = findlatestfile(home_dir+"Downloads")
        x = threading.Thread(target=startfile, args=(last_file,))
        x.start()
    elif ("open [a-zs]*last file [a-zs]*document[a-zs]*" in command):
        command = command.replace("open [a-zs]*last file [a-zs]*download[a-zs]*", "").strip()
        last_file = findlatestfile(home_dir+"Documents")
        x = threading.Thread(target=startfile, args=(last_file,))
        x.start()
    else:
        return

    return


if __name__ == "__main__":
   
    with sr.Microphone(device_index=0) as source:
        #listener.pause_threshold=0
        listener.adjust_for_ambient_noise(source) 
        listener.energy_threshold=15
        listen(source)
Answered By: Subhradeep Biswas