Python Forum
Adding a Wake word to my Script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding a Wake word to my Script
#1
Hello,

I am trying to add a wake word to my voice assistant script but I don't know where to add it or how to get it working properly.

I have created a variable name called
AI_Name = 'baxter'
where 'baxter' will be used as the wake word.

The part I'm having trouble with is, where do I put a statement that allows the code to only listen when the wake word is said (and what statement do I use? Should it be a while or Boolean? )

I have this chunk of code here where I think the statement should go, but I don't know how/where to implement the wake word.
def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)
Any help is greatly appreciated.

Thanks in advance.

Here is the full code:
#!/usr/bin/env python3
 
import json
import random
import datetime
import operator
import os
import time
from time import process_time
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import espeakng
import speech_recognition as sr 
 
#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'baxter'
#-------------------------------------------------------------------------------------
 
print ("Initializing B.A.X.T.E.R...")
 
def speak(text):
    mySpeaker = espeakng.Speaker()
    #mySpeaker.say('Initializing Baxter')
     
 
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
        print("Good Morning " + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)
        print("Good Afternoon " + Commander)   
    else:
        speak("Good Evening" + Commander) 
        print("Good Evening " + Commander) 
        speak("How may I be of service?")
        print("How may I be of service?")   

#---------------------------
# Listens for commands through mic
def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)
#---------------------------
# Uses google API to listen -> STT (Speech To Text)
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
 
    except:
            pass
 
    return command 
 
#--------------------------------
 
speak("Initializing Baxter..........")
wishMe()
 
def main():
    command = listenCommand()
    command=str(command).lower()
 
    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command):
        if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
            if ('time' not in command):
                speak('Searching Wikipedia...')
                command = command.replace("who is","")
                command = command.replace("what is the","")
                command = command.replace("what is a","")
                results = wikipedia.summary(command, sentences = 2)
                print("Baxter:",results)
                return speak(results) 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    elif ('calculate' in command) or ('what is' in command) or ('define' in command):
        speak('Searching Wolfram Alpha...')
        command = command.replace("calculate","")
        command = command.replace("what is","")
        command = command.replace("define","")
        # Wolframalpha App Id
        appId = 'JH9XHR-W9J76L7H5A'
        # Wolfram Instance
        client = wolframalpha.Client(appId)
        res = client.query(''.join(command))
        results = next(res.results).text
        print("Baxter:",results)
        return speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
    if ('news' in command):
        speak('Searching news networks...')
        command = command.replace("news","")
        url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
        results = requests.get(url)
        soup = BeautifulSoup(results.text, 'html.parser')
        headlines = soup.find('body').find_all('h3')
        for x in headlines:
            print("Baxter:",x.text.strip())
        return speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
    if ('weather' in command):
        if ('week' in command):
            speak('Searching weather networks...')
            command = command.replace("weather for the week","")
            #Call weather data for the week:
            displayWeeksWeatherData()
        else :
            speak('Searching weather networks...')
            command = command.replace("weather","")
            #Call weather data  for today:
            displayWeatherData()
    #-------------------------------------------------------------------------------------
                                        #Tell Time
    #-------------------------------------------------------------------------------------
    elif ('time' in command):
        speak('Scanning local clock networks...')
        command = command.replace("time","")
        strTime = datetime.datetime.now().strftime("%I:%M%P")
        speak("The time is {strTime}")
        print("Baxter:", "The time is", strTime)
    #-------------------------------------------------------------------------------------
                                #Enter the Matrix (Easter Egg)
    #-------------------------------------------------------------------------------------
    elif ('matrix' in command):
        speak('Entering the matrix...')
        print("Baxter:","Taking the red pill...")
        command = command.replace("matrix","")
        time.sleep(2)
        os.system("cmatrix")
    #-------------------------------------------------------------------------------------
 
    #-------------------------------------------------------------------------------------
                                #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
    elif ('stop' in command) or ('shutdown' in command) or ('quit' in command):
        speak("Shutting Down...")
        return exit()
        
    else:
        return 0 
    #-------------------------------------------------------------------------------------
 
while True:
    main()  
Reply
#2
I think you may need to restructure your code a bit. I would first separate each command into its own function to get rid of clutter in the main function. Also, it would be better to put a while loop in the main function rather than looping the main function itself. As for the problem, I would use the listen function in a while loop, and put an if statement to check if baxter has been said. If not, return to the top of the loop with continue. Otherwise, listen again, this time for the command that's being specified, if any.
Reply
#3
(Jan-12-2022, 06:51 PM)SheeppOSU Wrote: I think you may need to restructure your code a bit. I would first separate each command into its own function to get rid of clutter in the main function. Also, it would be better to put a while loop in the main function rather than looping the main function itself. As for the problem, I would use the listen function in a while loop, and put an if statement to check if baxter has been said. If not, return to the top of the loop with continue. Otherwise, listen again, this time for the command that's being specified, if any.

So I changed the main function to a while loop, and now I'm wondering how to change the listenCommand(): function to a while loop.

Would it be like this?
#def listenCommand():
while True():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
    #--------------------------------
    if ('baxter' not in command):
        continue
 
Thanks.


Full Working Code (as of now):
#!/usr/bin/env python3

import json
import random
import datetime
import operator
import os
import time
import sys
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import espeakng
import speech_recognition as sr 

#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'baxter'
#-------------------------------------------------------------------------------------

print ("Initializing B.A.X.T.E.R...")

def speak(text):
    mySpeaker = espeakng.Speaker()
    #mySpeaker.say('Initializing Baxter')
    

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
        print("Good Morning " + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)
        print("Good Afternoon " + Commander)   
    else:
        speak("Good Evening" + Commander) 
        print("Good Evening " + Commander) 
        speak("How may I be of service?")
        print("How may I be of service?")   

def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
    #--------------------------------

    except:
            pass

    return command 

speak("Initializing Baxter..........")
wishMe()

while True():
    command = listenCommand()
    command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command):
        if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
            if ('time' not in command):
                speak('Searching Wikipedia...')
                command = command.replace("who is","")
                command = command.replace("what is the","")
                command = command.replace("what is a","")
                results = wikipedia.summary(command, sentences = 2)
                #----------------------
                #Auto typing animation:
                print("Baxter: ", end="")
                for i in results:
                    sys.stdout.write(i)
                    sys.stdout.flush()
                    time.sleep(0.05)
                print("\n")
                #----------------------
                speak(results) 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    if ('calculate' in command) or ('what is' in command) or ('define' in command):
        speak('Searching Wolfram Alpha...')
        command = command.replace("calculate","")
        command = command.replace("what is","")
        command = command.replace("define","")
        # Wolframalpha App Id
        appId = 'JH9XHR-W9J76L7H5A'
        # Wolfram Instance
        client = wolframalpha.Client(appId)
        res = client.query(''.join(command))
        results = next(res.results).text
        #print("Baxter:",results)
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in results:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.05)
        print("\n")
        #----------------------
        speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
    if ('news' in command):
        speak('Searching news networks...')
        command = command.replace("news","")
        #Gets the news headlines from this url:
        url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
        results = requests.get(url)
        soup = BeautifulSoup(results.text, 'html.parser')
        headlines = soup.find('body').find_all('h3')
        for x in headlines:
            print("Baxter:",x.text.strip())
        speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
    if ('weather' in command):
        if ('week' in command):
            speak('Searching weather networks...')
            command = command.replace("weather for the week","")
            #Call weather data for the week:
            displayWeeksWeatherData()
        else:
            speak('Searching weather networks...')
            command = command.replace("weather","")
        #Call weather data for today:
        displayWeatherData()
    #-------------------------------------------------------------------------------------
                                        #Tell Time
    #-------------------------------------------------------------------------------------
    elif ('time' in command):
        speak('Scanning local clock networks...')
        command = command.replace("time","")
        strTime = datetime.datetime.now().strftime("%I:%M%P")
        speak("The time is {strTime}")
        print("Baxter: The time is ", strTime)
    #-------------------------------------------------------------------------------------
                                #Enter the Matrix (Easter Egg)
    #-------------------------------------------------------------------------------------
    elif ('matrix' in command):
        speak('Entering the matrix...')
        command = command.replace("matrix","")
        response = "Taking the red pill..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        time.sleep(2)
        os.system("cmatrix")
    #-------------------------------------------------------------------------------------

    #-------------------------------------------------------------------------------------
                                #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
    elif ('stop' in command) or ('shutdown' in command) or ('quit' in command):
        speak("Shutting Down...")
        response = "Terminating program..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        exit()
    #-------------------------------------------------------------------------------------
Reply
#4
I didn't mean replace the functions with while loops, but to put a while loop inside the functions. Also, in the while loops you have made, you are attempting to call True with the parenthesis. It should be like this while True:. The listen function is fine as it was before. The only changes needed should be in the main function. I'll give an example below of what I meant in my post before.
def main():
    commands = {
        1: "weather",
        2: "news",
        # ...
    }
    while True:
        num = random.randint(1, 10)  # Represents listen function
        if num != 1:  # Represents a check to see if baxter was said
            continue
        cmd = random.randint(1, 10)  # Listen again for the command
        print(commands[cmd])  # Carry out command
Reply
#5
(Jan-13-2022, 07:48 PM)SheeppOSU Wrote: I didn't mean replace the functions with while loops, but to put a while loop inside the functions. Also, in the while loops you have made, you are attempting to call True with the parenthesis. It should be like this while True:. The listen function is fine as it was before. The only changes needed should be in the main function. I'll give an example below of what I meant in my post before.
def main():
    commands = {
        1: "weather",
        2: "news",
        # ...
    }
    while True:
        num = random.randint(1, 10)  # Represents listen function
        if num != 1:  # Represents a check to see if baxter was said
            continue
        cmd = random.randint(1, 10)  # Listen again for the command
        print(commands[cmd])  # Carry out command

Sorry, I'm still confused.

Would it be like this?
def main():
    commands = {

        1: "who is", 
        2: "what is the",
        3: "what is a",

        4: "calculate",
        5: "what is",
        6: "define",

        7: "news",

        8: "weather",

        9: "time",

        10: "matrix",

        12: "stop",
        13: "shutdown",
        14: "quit",
    }


    while True:
        command = listenCommand()
        if command != AI_Name: 
            continue
        cmd = listenCommand()
        print(commands[cmd])
            
        #command = listenCommand()
        #command=str(command).lower()
Because if I say the AI_Name, pause, then say my command (Like "Who is will Smith") I get a key error and the program exits.
I'm guessing that's because it needs to match the "commands"/dictionary numbers to the actual "if statements" in my full code below??

I get that it should listen for the AI_Name and if I don't say it, then it ignores me and keeps on listening. But If I do say the wake word/AI_Name then it should run the command.
In your example, I don't understand what those random numbers/ints are used for and how they translate to the wake word and listen function or command execution.

Full Code:
#!/usr/bin/env python3

import json
import random
import datetime
import operator
import os
import time
import sys
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import espeakng
import speech_recognition as sr 

#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'Baxter'
#-------------------------------------------------------------------------------------

print ("Initializing B.A.X.T.E.R...")

def speak(text):
    mySpeaker = espeakng.Speaker()
    #mySpeaker.say('Initializing Baxter')
    

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
        print("Good Morning " + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)
        print("Good Afternoon " + Commander)   
    else:
        speak("Good Evening" + Commander) 
        print("Good Evening " + Commander) 
        speak("How may I be of service?")
        print("How may I be of service?")   

def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
    #--------------------------------

    except:
            pass

    return command 

speak("Initializing Baxter..........")
wishMe()

def main():
    commands = {

        1: "who is", 
        2: "what is the",
        3: "what is a",

        4: "calculate",
        5: "what is",
        6: "define",

        7: "news",

        8: "weather",

        9: "time",

        10: "matrix",

        12: "stop",
        13: "shutdown",
        14: "quit",
    }


    while True:
        command = listenCommand()
        if command != AI_Name: 
            continue
        cmd = listenCommand()
        print(commands[cmd])
            
        #command = listenCommand()
        #command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
        if ('weather' not in command):
            if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
                if ('time' not in command):
                    speak('Searching Wikipedia...')
                    command = command.replace("who is","")
                    command = command.replace("what is the","")
                    command = command.replace("what is a","")
                    results = wikipedia.summary(command, sentences = 2)
                    #----------------------
                    #Auto typing animation:
                    print("Baxter: ", end="")
                    for i in results:
                        sys.stdout.write(i)
                        sys.stdout.flush()
                        time.sleep(0.05)
                    print("\n")
                    #----------------------
                    speak(results) 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
        if ('calculate' in command) or ('what is' in command) or ('define' in command):
            speak('Searching Wolfram Alpha...')
            command = command.replace("calculate","")
            command = command.replace("what is","")
            command = command.replace("define","")
            # Wolframalpha App Id
            appId = 'JH9XHR-W9J76L7H5A'
            # Wolfram Instance
            client = wolframalpha.Client(appId)
            res = client.query(''.join(command))
            results = next(res.results).text
            #----------------------
            #Auto typing animation:
            print("Baxter: ", end="")
            for i in results:
                sys.stdout.write(i)
                sys.stdout.flush()
                time.sleep(0.05)
            print("\n")
            #----------------------
            speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
        if ('news' in command):
            speak('Searching news networks...')
            command = command.replace("news","")
            #Gets the news headlines from this url:
            url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
            results = requests.get(url)
            soup = BeautifulSoup(results.text, 'html.parser')
            headlines = soup.find('body').find_all('h3')
            for x in headlines:
                print("Baxter:",x.text.strip())
            speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
        if ('weather' in command):
            if ('week' in command):
                speak('Searching weather networks...')
                command = command.replace("weather for the week","")
                #Call weather data for the week:
                displayWeeksWeatherData()
            else:
                speak('Searching weather networks...')
                command = command.replace("weather","")
            #Call weather data for today:
            displayWeatherData()
    #-------------------------------------------------------------------------------------
                                        #Tell Time
    #-------------------------------------------------------------------------------------
        elif ('time' in command):
            speak('Scanning local clock networks...')
            command = command.replace("time","")
            strTime = datetime.datetime.now().strftime("%I:%M%P")
            speak("The time is {strTime}")
            print("Baxter: The time is ", strTime)
    #-------------------------------------------------------------------------------------
                                #Enter the Matrix (Easter Egg)
    #-------------------------------------------------------------------------------------
        elif ('matrix' in command):
            speak('Entering the matrix...')
            command = command.replace("matrix","")
            response = "Taking the red pill..."
            #----------------------
            #Auto typing animation:
            print("Baxter: ", end="")
            for i in response:
                sys.stdout.write(i)
                sys.stdout.flush()
                time.sleep(0.2)
            print("\n")
            #----------------------
            time.sleep(2)
            os.system("cmatrix")
    #-------------------------------------------------------------------------------------

    #-------------------------------------------------------------------------------------
                                #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
        elif ('stop' in command) or ('shutdown' in command) or ('quit' in command):
            speak("Shutting Down...")
            response = "Terminating program..."
            #----------------------
            #Auto typing animation:
            print("Baxter: ", end="")
            for i in response:
                sys.stdout.write(i)
                sys.stdout.flush()
                time.sleep(0.2)
            print("\n")
            #----------------------
            return exit()

        else:
            return 0
    #-------------------------------------------------------------------------------------

while True:
    main()
Reply
#6
(Jan-13-2022, 09:10 PM)Extra Wrote: I don't understand what those random numbers/ints are used for and how they translate to the wake word and listen function or command execution.
Sorry, I could've phrased the example better. The random numbers aren't needed in your code, it was just for that specific example to convey the concept. For you it would probably look more something like this. This is just a basic example and there are more complex things you can do to make it interpret and respond better.
def main():
    keywords = {  # List of keywords that correspond to certain commands
        'weather': weather,  # A function that will carry out the weather command
        'news': news,
        'what is': what_is,
        # ...
    }
    while True:
        command = listenCommand()
        if AI_Name not in command:  # Check for the ai name being said
            continue
        cmd = listenCommand()
        for keyword, func in keywords.items():  # Iterate through all the keywords
            if keyword in cmd:  # Check if the keyword is mentioned
                func(cmd)  # Carry out the function of the command correspond to the keyword said
Reply
#7
(Jan-13-2022, 11:53 PM)SheeppOSU Wrote:
(Jan-13-2022, 09:10 PM)Extra Wrote: I don't understand what those random numbers/ints are used for and how they translate to the wake word and listen function or command execution.
Sorry, I could've phrased the example better. The random numbers aren't needed in your code, it was just for that specific example to convey the concept. For you it would probably look more something like this. This is just a basic example and there are more complex things you can do to make it interpret and respond better.
def main():
    keywords = {  # List of keywords that correspond to certain commands
        'weather': weather,  # A function that will carry out the weather command
        'news': news,
        'what is': what_is,
        # ...
    }
    while True:
        command = listenCommand()
        if AI_Name not in command:  # Check for the ai name being said
            continue
        cmd = listenCommand()
        for keyword, func in keywords.items():  # Iterate through all the keywords
            if keyword in cmd:  # Check if the keyword is mentioned
                func(cmd)  # Carry out the function of the command correspond to the keyword said

A couple Questions:

1) Can this be done with an array, where it just looks for the keywords(strings)?
def main():
    keywords = [ 
        
        'who is', 
        'what is',
        'what is a',

        'calculate',
        'what is',
        'define',

        'news',

        'weather',

        'time',

        'matrix',

        'stop',
        'shutdown',
        'quit'
    ]


    while True:
        command = listenCommand()
        if AI_Name not in command: 
            continue
        cmd = listenCommand()
        for keyword, func in keywords.items():  # Iterate through all the keywords
            if keyword in cmd:  # Check if the keyword is mentioned
                func(cmd)  # Carry out the function of the command correspond to the keyword said
        print(command[cmd])
2) If I do it like this:
def main():
    keywords = {

        'who is': wikiSearch, 
        'what is': wikiSearch,
        'what is a': wikiSearch,

        #'calculate': calculate,
        #'what is': what_is,
        #'define': define,

        #'news': news,

        #'weather': weather,

        #'time': time,

        #'matrix': matrix,

        #'stop': stop,
        #'shutdown': shutdown,
        #'quit': quit,
    }


    while True:
        command = listenCommand()
        if AI_Name not in command: 
            continue
        cmd = listenCommand()
        for keyword, func in keywords.items():  # Iterate through all the keywords
            if keyword in cmd:  # Check if the keyword is mentioned
                func(cmd)  # Carry out the function of the command correspond to the keyword said
        print(command[cmd])
Where I have a function:
    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
def wikiSearch():
        if ('weather' not in command):
            if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
                if ('time' not in command):
                    speak('Searching Wikipedia...')
                    command = command.replace("who is","")
                    command = command.replace("what is the","")
                    command = command.replace("what is a","")
                    results = wikipedia.summary(command, sentences = 2)
                    #----------------------
                    #Auto typing animation:
                    print("Baxter: ", end="")
                    for i in results:
                        sys.stdout.write(i)
                        sys.stdout.flush()
                        time.sleep(0.05)
                    print("\n")
                    #----------------------
                    speak(results) 
I get a TypeError: wikiSearch() takes 0 positional arguments but 1 was given

And if it did work and I were to say "What is the weather" would it jump to the weather function(which I do want), or would it just search it on wiki(which I don't want)?

Thanks for your continued support by the way. I do appreciated it, I'm just having trouble understanding.
Hopefully you can clear this up for me.

Thanks again.
Reply
#8
(Jan-14-2022, 06:52 PM)Extra Wrote: I get a TypeError: wikiSearch() takes 0 positional arguments but 1 was given
This error occurs because you didn't specify command in the function parameters.
(Jan-14-2022, 06:52 PM)Extra Wrote: And if it did work and I were to say "What is the weather" would it jump to the weather function(which I do want), or would it just search it on wiki(which I don't want)?
If you were to put weather on top of the keywords what is, what is the, etc. then it would work, however the way it's setup now, it will search the wiki. That's one of the downsides of this simple implementation. Making something like this more accurate can quickly become complex.
Reply
#9
Quote:This error occurs because you didn't specify command in the function parameters.
Did that:
while True:
        command = listenCommand()
        if AI_Name not in command: 
            continue
        command = listenCommand()
        for keyword, func in keywords.items():  # Iterate through all the keywords
            if keyword in command:  # Check if the keyword is mentioned
                func(command)  # Carry out the function of the command correspond to the keyword said
        print(command[command])
            
        #command = listenCommand()
        #command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
def wikiSearch(command):
        if ('weather' not in command):
            if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
                if ('time' not in command):
                    speak('Searching Wikipedia...')
                    command = command.replace("who is","")
                    command = command.replace("what is the","")
                    command = command.replace("what is a","")
                    results = wikipedia.summary(command, sentences = 2)
                    #----------------------
                    #Auto typing animation:
                    print("Baxter: ", end="")
                    for i in results:
                        sys.stdout.write(i)
                        sys.stdout.flush()
                        time.sleep(0.05)
                    print("\n")
                    #----------------------
                    speak(results) 
When I said "Who is Albert Einstein" it displayed the results, but then gave me another TypeError. And I also noticed that my auto type animation didn't work and I also got another error saying "sleep" is not recognized.

Quote:If you were to put weather on top of the keywords what is, what is the, etc. then it would work, however the way it's setup now, it will search the wiki. That's one of the downsides of this simple implementation. Making something like this more accurate can quickly become complex.

Well that sucks.

I guess I'll have to stick to unmuting my mic when I want to execute a command, then keep it muted until I need another command to be executed.
Would it be possible to use my phone as a Bluetooth mic? I used an app called "Microphone Live" but my Rpi recognizes it as an output device, not an input (Even through when I talk through my phone I can see the sound waves being picked up on the Rpi). Is there a way to change that? Just curious.

I'll keep playing around with the code and see if I can get a wakeword working properly. If not, it'll end up being "push to talk".

Oh, wait a sec! I have an Arduino Speech synthesizer board that I used to use as an old voice assistant (the only problem was that it couldn't access the internet. The only thing it was good for was controlling lights and motors), that had a wake word. Would it be possible to use the Arduino's wakeword on the Rpi. What I mean is when I say "Baxter" on the arduino, it will recognize that it's callsign is said and send either a (1), "True", or the string ("Baxter") to the Rpi, therefore triggering the listenCommand(). I know not everyone is familiar with Arduino, but I'm asking if this would be possible on the python/Rpi side (through serial command or something) Would that work, or would it be the same thing that we just did?
Reply
#10
(Jan-14-2022, 09:17 PM)Extra Wrote: but then gave me another TypeError
That's caused by print(command[command]) because you're trying to index a string with a string, but an integer should be used instead.
(Jan-14-2022, 09:17 PM)Extra Wrote: I also got another error saying "sleep" is not recognized.
Is it properly implemented like this (I assume you mean the sleep function from the time library)? from time import sleep
(Jan-14-2022, 09:17 PM)Extra Wrote: Would it be possible to use the Arduino's wakeword on the Rpi. What I mean is when I say "Baxter" on the arduino, it will recognize that it's callsign is said and send either a (1), "True", or the string ("Baxter") to the Rpi, therefore triggering the listenCommand(). I know not everyone is familiar with Arduino, but I'm asking if this would be possible on the python/Rpi side (through serial command or something) Would that work, or would it be the same thing that we just did?
I think what you are wanting to use here is sockets.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,564 Aug-12-2021, 04:25 PM
Last Post: palladium
  Adding a list to Python Emailing Script Cknutson575 4 2,374 Feb-18-2021, 09:13 AM
Last Post: buran
Question Word, adding a hyperlink from a bookmark using Python mart79 1 2,368 Jan-14-2021, 08:41 PM
Last Post: Larz60+
  Python Speech recognition, word by word AceScottie 6 16,119 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  print a word after specific word search evilcode1 8 4,944 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  Adding markers to Folium map only adding last element. tantony 0 2,168 Oct-16-2019, 03:28 PM
Last Post: tantony
  difference between word: and word[:] in for loop zowhair 2 3,714 Mar-03-2018, 07:24 AM
Last Post: zowhair
  Adding a parameter/argument to a script jehoshua 11 9,542 Jan-29-2018, 09:45 AM
Last Post: jehoshua
  How to make a script to find a certain word in text files in a whole directory ? RandoomDude 2 5,984 Apr-27-2017, 10:27 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020