-1

I'm making a virtual assistant in python, and one of my variables is giving an error message saying that it is undefined, even though I defined it at the top of my code. I'm not going to go entirely in detail about what I have so far. I have a bool variable called "responding" and it is set to "true" in the top of my code.

import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import random
import sys
import pyowm
import time
import wolframalpha
import jokes_library

listening = True
responding = True

# wake_phrases = ["hello ava", "hello", "good morning", "good afternoon", "good evening", "good morning ava", "good afternoon ava", "good evening ava"]
# wake_phrase = wake_phrases[0] or wake_phrases[1] or wake_phrases[2] or wake_phrases[3] or wake_phrases[4] or wake_phrases[5] or wake_phrases[6] or wake_phrases[7]

wake_phrase = "hello ava"
call_phrase = "hey ava"

respect_words = ["sir", "chief"]
respect_word = random.choice(respect_words)

goodbye_phrases = ["my pleasure", "until tomorrow", "ok, take it easy", "you betcha", "no problemo, see you later"]
goodbye_phrase = random.choice(goodbye_phrases)

engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)

def speak(audio):
   engine.say(audio)
   engine.runAndWait() 

def wish_me():
    hour = int(datetime.datetime.now().hour)
    if hour >= 0 and hour < 12:
        speak(f"good morning {respect_word}")

    elif hour >= 12 and hour < 18:
        speak(f"good afternoon {respect_word}")

    else:
        speak(f"good evening {respect_word}")

    speak(f"how may i help you")

def listen():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
    query = r.recognize_google(audio, key=None, language="en-US", show_all=False)

def take_command():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("i am listening")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("recognizing")
        query = r.recognize_google(audio, key=None, language="en-US", show_all=False)
        print(f"user said: {query}\n")

    except Exception as e:
        # print(e)
        print("Come again?")
        # speak("come again?")
        return None
    return query

def wake():
    with sr.Microphone() as source:
        r = sr.Recognizer()
        audio = r.listen(source)
    query = r.recognize_google(audio, key=None, language="en-US", show_all=False)
    if wake_phrase in query:
        take_command()
    wish_me()

def call_ava():
    responding = False
    with sr.Microphone() as source:
        r = sr.Recognizer()
        audio = r.listen(source)
    query = r.recognize_google(audio, key=None, language="en-US", show_all=False)
    if call_phrase in query:
        responding = True
        take_command()
    else:
        responding = False
    check_user()

def check_user():
    if responding == False:
        speak("will that be all, sir?")
        with sr.Microphone() as source:
            r = sr.Recognizer()
            audio = r.listen(source)
        query = r.recognize_google(audio, key=None, language="en-US", show_all=False)
        if "yes" in query:
            speak(goodbye_phrase)
            sys.exit()
        if "no" in query:
            responding = True
            speak("what else can i do for you")
            take_command()

while listening:  
    wake()
    if __name__ == "__main__":
        while responding:
            query = take_command().lower()

            if "wikipedia" in query:
                speak("searching wikipedia")
                query = query.replace("wikipedia", "")
                query = query.replace("search", "")
                query = query.replace("in", "")
                results = wikipedia.summary(query, sentences = 2)
                speak("according to wikipedia")
                print(results)
                speak(results)
                call_ava()

            elif "define" in query:
                speak("searching wolfram alpha for definitions")
                query = query.replace("define", "")
                query = query.replace("hey", "")
                query = query.replace("hello", "")
                query = query.replace("ava", "")
                app_id = "QHA83L-568TKTG4TV"
                client = wolframalpha.Client(app_id)
                results = client.query(query, sentences = 2)
                answer = next(results.results).text 
                answer = answer.replace("1", ",")
                answer = answer.replace("2", ",")
                answer = answer.replace("3", ",")
                answer = answer.replace("4", ",")
                answer = answer.replace("5", ",")
                answer = answer.replace("6", ",")
                answer = answer.replace("7", ",")
                answer = answer.replace("8", ",")
                answer = answer.replace("9", ",")
                answer = answer.replace("10", ",")
                answer = answer.replace("noun", "")
                answer = answer.replace("verb", "")
                answer = answer.replace("adjective", "")
                answer = answer.replace("determiner", "")
                speak(answer)
                call_ava()

            elif "time" in query:
                hour = datetime.datetime.now().strftime("%H")
                minute = datetime.datetime.now().strftime("%M")

                if int(hour) > 12:
                    hour = int(hour)
                    hour -= 12

                time = (f"{hour}:{minute}")
                speak(f"the time is {time} sir")
                call_ava()

            elif "weather" in query:
                owm = pyowm.OWM("65f3e6f2b1532bd1b5165346615128c1")
                city = "Austin"
                austin = owm.weather_at_place("Austin, US")
                weather = austin.get_weather()
                austin_rain_check = owm.three_hours_forecast("Austin, US")
                temperature = weather.get_temperature("fahrenheit")["temp"]
                rain_check = austin_rain_check.will_have_rain()

                if rain_check == True:
                    speak(f"Currently, it is {temperature} degrees in austin, and no rain is expected")
                else:
                    speak(f"Currently, it is {temperature} degrees in austin and rain is expected")

                call_ava()

            elif "joke" in query:
                jokes_library.joking_around()
                call_ava()

            elif "goodbye" or "thank you for your time" or "done" in query:
                speak(goodbye_phrase)
                sys.exit()

The error message refers me to line 98 where I have an if statement saying if responding == False: I probably have a stupid mistake, but can someone point me in the right direction?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    Please provide the full error traceback rather than a vague description, remember that this site doesn't have line numbers and there may be additional relevant information in the error message – G. Anderson May 13 '20 at 22:40
  • Error is "UnboundLocalError: local variable referenced before assignment", right? BTW welcome to SO! Check out the [tour] and [ask] if you want advice. – wjandrea May 13 '20 at 22:51
  • Read up on [Tutorial - 9.2. Python Scopes and Namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) – stovfl May 14 '20 at 12:40

1 Answers1

0

Try adding a global variable statement at the start of your code just before the first responding = True e.g.

global responding
responding = True