Python Forum
Virtual Assistant code is looping back in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Virtual Assistant code is looping back in python
#1
I am working on a virtual assistant and have almost completed it. But when I try to give it a test run, it either doesn't stop listening or loops back to "What can I help you with?"

I can't seem to figure out what the problem is. I have tried changing stuff but it didn't help me in any way. I have checked my microphone and it seems to be working properly. In fact, the assistant is taking in correct inputs, but not displaying outputs as it is supposed to.

The up-to-date GitHub link for this project: https://github.com/ShishirModi/YourEdu
Please help me through this. Thanks!
 
import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
import time
import subprocess
import wolframalpha
import json
import requests
import sys
engine=pyttsx3.init()
voices=engine.getProperty('voices')
engine.setProperty('voice','voices[1].id')
def speak(text):
    engine.say(text)
    engine.runAndWait()

def wishMe():
    hour=datetime.datetime.now().hour
    if hour>=0 and hour<12:
        speak("Good morning!")
        print("Good morning!")
    elif hour>=12 and hour<18:
        speak("Good afternoon!")
        print("Good afternoon!")
    else:
        speak("Good evening!")
        print("Good evening!")
def takeCommand():
    r=sr.Recognizer()
    with sr.Microphone() as source:
        print("What can I help you with?")
        speak("What can I help you with?")
        print("Listening...")
        r.pause_threshold = 1
        r.adjust_for_ambient_noise(source, duration=1)
        audio=r.listen(source)
        try:
            statement=r.recognize_google(audio,language='en')
            print(f"You said: {statement}\n")
        except sr.UnknownValueError:
            speak("I'm sorry, I didn't catch that")
            takeCommand()
        return statement
print("Please wait while your assistant loads...")
speak("Please wait while your assistant loads")
wishMe()
if __name__=='__main__':

    while True:
        statement = takeCommand().lower()
        if statement==0:
            continue
if "bye" in statement or "stop" in statement:
  speak('Glad to help you! I will shut down now')
  print('Glad to help you! I will shut down now')
  time.sleep(2)
  sys.exit()
elif 'wikipedia' in statement:
  speak('Searching Wikipedia...')
  statement =statement.replace("wikipedia", "")
  results = wikipedia.summary(statement, sentences=3)
  speak("According to Wikipedia")
  print(results)
  speak(results)
elif 'open youtube' in statement:
  webbrowser.open_new_tab("https://www.youtube.com")
  speak("Youtube is open now")
  time.sleep(5)
elif 'open google' in statement:
  webbrowser.open_new_tab("https://www.google.com")
  speak("Google is open now")
  time.sleep(5)
elif 'open gmail' in statement:
  webbrowser.open_new_tab("gmail.com")
  speak("Gmail is open now")
  time.sleep(5)
elif 'time' in statement:
  strTime=datetime.datetime.now().strftime("%H:%M:%S")
  speak(f"the time is {strTime}")
elif 'news' in statement:
  news = webbrowser.open_new_tab("https://bbc.com")
  speak('Here are some headlines from the BBC news, Happy reading!')
  time.sleep(6)
elif 'search'  in statement:
  statement = statement.replace("search", "")
  webbrowser.open_new_tab(statement)
  time.sleep(5)
elif 'what is' in statement:
  speak('I can get you answers for computational and geographical problems. Please ask your question now')
  question=takeCommand()
  client = wolframalpha.Client('6QKTYA-66TGTQE6TX')
  res = client.query(question)
  answer = next(res.results).text
  speak(answer)
  print(answer)
elif 'who are you' in statement or 'what can you do' in statement:
  speak('I am your personal productivity assistant YourEdu. I am programmed to minor tasks like'
  'opening youtube,google chrome, gmail and stackoverflow ,predict time,search wikipedia' 
  'get top headline news from BBC and you can ask me computational or geographical questions too!')
elif "who made you" in statement or "who created you" in statement or "who discovered you" in statement:
  speak("I was built by Shishir Modi")
  print("I was built by Shishir Modi")
elif "log off" in statement or "sign out" in statement:
  speak("Ok , your pc will log off in 10 sec make sure you exit from all applications")
  time.sleep(10)
  subprocess.call(["shutdown", "/l"])
time.sleep(3)
Reply
#2
I would try taking the speak(what can I help you with?) out of your take_command function and move it right after the while loop using your speak() and put your take command function right after it
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Best practice on using virtual environments in Python bytecrunch 6 812 Feb-14-2024, 03:22 PM
Last Post: snippsat
  Virtual Env changing mysql connection string in python Fredesetes 0 375 Dec-20-2023, 04:06 PM
Last Post: Fredesetes
  Installing python packages in a virtual environment Led_Zeppelin 1 759 Aug-15-2023, 08:18 PM
Last Post: deanhystad
  Can anyone tell me why this code isn't looping properly? SuchUmami 2 933 Jun-17-2023, 11:37 AM
Last Post: SuchUmami
Question Virtual Environment (using VS Code) Ashcora 4 13,693 Feb-15-2023, 07:17 PM
Last Post: snippsat
  Virtual Environments - Organization (VS Code) JaysonWonder 11 1,845 Jan-26-2023, 11:34 PM
Last Post: Larz60+
  Code won't break While loop or go back to the input? MrKnd94 2 947 Oct-26-2022, 10:10 AM
Last Post: Larz60+
  front-end js and back-end python 3lnyn0 0 989 Jun-03-2022, 08:51 PM
Last Post: 3lnyn0
  How do I link the virtual environment of that project to the 3.9.2 version of python? Bryant11 1 1,371 Feb-26-2022, 11:15 AM
Last Post: Larz60+
  "while" loop is looping back too early mangurian 1 1,270 Jan-28-2022, 09:15 AM
Last Post: ibreeden

Forum Jump:

User Panel Messages

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