Python Forum
Can a variable equal 2 things?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can a variable equal 2 things?
#1
Hello,

I'm looking to add a text input for my voice assistant in case a mic isn't around.
So if a mic isn't available I'd like to be able to switch to a text input mode where I can type in the commands instead of speaking them.

I would like to add:
command = input("Commander: ")
But I already have:
command = listenCommand()
Is it possible to keep both (can the command variable equal those two different things)?

Or do I have to make a function that switches between text input and voice input?
[If no mic is detected command=input() and if a mic is detected command = listenCommand() or if I say "Switch to text input" it would overwrite the command variable to equal input(), then if I say "Switch to voice input" it would then rewrite the command variable again to equal listenCommand()]

Can it be done like this, or is there a better way?

Thanks in advance.

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

import json
from pyexpat import version_info
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 
from Animations import startupAnimation

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

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)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)   
    else:
        speak("Good Evening" + Commander) 


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 

wishMe()
speak("How may I be of service?")  

#Initiate Start Up Animation
startupAnimation()

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) or ("what is" in command):
            if ('time' not in command):
                if ('news' not in command):
                    speak('Searching Wikipedia...')
                    command = command.replace("who is","")
                    command = command.replace("what is the","")
                    command = command.replace("what is a","")
                    command = command.replace("what is","")
                    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 ('weather' not in command):
        if ('news' not in command):
            if ('calculate' in command) or ("what's" in command) or ('define' in command):
                speak('Searching Wolfram Alpha...')
                command = command.replace("calculate","")
                command = command.replace("what's","")
                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")
        #----------------------
        exit()
    #-------------------------------------------------------------------------------------
Reply
#2
You could have your listenCommand() either detect which should be used, or you could have it take an input parameter to drive the input like:

command = listenCommand(style="mic")
command = listenCommand(style="keyboard")
Really it depends on where you want to keep the logic. Do you want to keep the state in in the main program, or do you want the input function to detect it?

Or if you couldn't touch the existing function, you could have two different functions and call the one you want depending on the program.

def listenCommand():
    """Used for mic input"""
    ...

def typeCommand():
    """Used for kbd input"""
    return input("Commander: ")

inputCommand = typeCommand
if microphone_detected():
    inputCommand = listenCommand

command = inputCommand()
BashBedlam likes this post
Reply
#3
Thanks for the helpful response.

I do have one more question though. Is it possible to have python detect an input device (the mic) I'm running Manjaro Gnome and I go to PulseAudio Volume Control to view my input devices. If there is not mic plugged in, nothing shows up in the input devices. Is there a way to have python see that there are no input devices plugged, that way I can incorporate it into the if statement (if there's no mic command=typeCommand -> Like you suggested above)?
Reply
#4
Possibly, but it would depend on specifics. Your OS might create a device file for the mic on plugin. If so, you could check the filesystem if the device is there.

Or it could be that trying to open the microphone when it's not present generates an error. You could do the attempt and catch the error.

But those are just generalities. I'm not familiar with the code/libraries/drivers you're using to capture the input, so I'm not sure what the best detection method might be.
Reply
#5
(Jan-18-2022, 08:57 PM)bowlofred Wrote: Possibly, but it would depend on specifics. Your OS might create a device file for the mic on plugin. If so, you could check the filesystem if the device is there.

Or it could be that trying to open the microphone when it's not present generates an error. You could do the attempt and catch the error.

But those are just generalities. I'm not familiar with the code/libraries/drivers you're using to capture the input, so I'm not sure what the best detection method might be.

No problem. I thought of using a button. When I click it, it sets Command=TypeCommand and when I click it again it sets Command=listenCommand.
The only problem is I can't get the RPi.GPIO module to work (Like I mentioned before I'm using arch-linux -> Manjaro and it doesn't seem to like using the GPIO pins. I downloaded the RPI.GPIO library from the Manjaro app store and it still tells me that the module doesn't exist. Off to the Arch-Linux forums I go).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  is there equal syntax to "dir /s /b" kucingkembar 2 981 Aug-16-2022, 08:26 AM
Last Post: kucingkembar
  Unusual things to do with unittest/HTMLTestRunner AndyHolyer 0 2,138 Jul-29-2020, 02:43 PM
Last Post: AndyHolyer
  I don't get the order of how things are executed with main() pythonrookie 5 2,569 Jul-21-2020, 01:35 PM
Last Post: pythonrookie
  Not equal a dictionary key value bazcurtis 2 1,916 Dec-11-2019, 11:15 PM
Last Post: bazcurtis
  Misunderstanding with the “if” statement and “not equal” scriptoghost 6 4,420 Jun-23-2017, 09:43 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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