2

I have my basic structure setup but wanted a suggestion. Once I call the assistant, it waits for queries but after that, it stops. Can it be made in such a way that after answering the first query, for example, opening YouTube, it waits for a second command for some time, otherwise goes offline again? Also, any other way of using the break/continue commands? I mean adding them to all of the queries is a bit time-consuming.

import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
import time
import subprocess
from ecapture import ecapture as ec
import wolframalpha
import json
import requests
import pywhatkit
import pyjokes
import pyautogui
from playsound import playsound

vc = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0'

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', vc)
engine.setProperty('rate', 215)


# listen to the input from microphone and return as text


def transform():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Listening...')
        r.pause_threshold = 1
        said = r.listen(source)

        try:
            q = r.recognize_google(said, language='en-in')
            print(f"You said:{q}\n")

        except sr.UnknownValueError:
            print("Didn't catch that")
            return "Waiting for input"

        except sr.RequestError:
            print('server down')
            return "Waiting for input"

        except:
            return "Waiting for input"
    return q


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


def wish_me():
    hour = datetime.datetime.now().hour
    if 0 <= hour < 12:
        speak("Hello, Good Morning.")
        print("Hello, Good Morning.")
    elif 12 <= hour < 18:
        speak("Hello, Good Afternoon.")
        print("Hello, Good Afternoon.")
    else:
        speak("Hello, Good Evening.")
        print("Hello, Good Evening.")


def query_day():
    f_date = datetime.date.today()
    weekday = f_date.weekday()
    date = datetime.date.today().day
    month = datetime.date.today().month

   
    weekday_mapping = {
        0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday',
    }

    month_mapping = {
        1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August',
        9: 'September', 10: 'October', 11: 'November', 12: 'December '
    }
    print(f"Today is {weekday_mapping[weekday]}, {date} {month_mapping[month]}.")
    try:
        speak(f"Today is {weekday_mapping[weekday]}, {date} {month_mapping[month]}.")
    except:
        pass


def query_time():
    str_time = datetime.datetime.now().strftime("%I:%M %p")
    speak(f"The time is {str_time}")
    print(f"The time is {str_time}")



# heart of our assistant


def main_function():
    wish_me()
    while True:
        q = transform().lower()
        if 'shadow' in q:
            playsound("C:\\Users\\vnsin\\PycharmProjects\\Shadow_Assistant\\7.mp3")

            while True:
                q = transform().lower()

                if 'youtube' in q:
                    speak('starting Youtube.')
                    webbrowser.open('https://www.youtube.com')
                    break

                elif 'google' in q:
                    code_path = r"C:\Program File(x86)\Google\Chrome\Application\chrome.exe"
                    speak('starting Google.')
                    os.startfile(code_path)
                    break

                elif 'zoom' in q or 'classes' in q or 'school' in q:
                    code_path = r"C:\Users\vnsin\AppData\Roaming\Zoom\bin\Zoom.exe"
                    speak('starting Zoom.')
                    os.startfile(code_path)
                    break

                elif 'wikipedia' in q:
                    speak('Searching Wikipedia...')
                    q = q.replace("wikipedia", "")
                    q = q.replace("search", "")
                    q = q.replace("for", "")
                    results = wikipedia.summary(q, sentences=3)
                    speak("According to Wikipedia")
                    print(results)
                    speak(results)
                    break

                elif 'joke' in q:
                    speak(pyjokes.get_joke())
                    break

                elif 'day' in q or 'date' in q:
                    query_day()
                    break

                elif 'time' in q:
                    query_time()
                    break

                elif 'switch window' in q:
                    speak("switching window")
                    pyautogui.hotkey("alt", "tab")
                    break

                elif 'task' in q or 'manager' in q:
                    speak("starting task manager")
                    pyautogui.hotkey("ctrl", "shift", "esc")
                    break

                elif 'show desktop' in q:
                    pyautogui.hotkey('win', 'm')
                    speak("showing desktop")
                    break

                elif 'stop' in q or 'offline' in q or 'turn off' in q or 'shut down' in q or 'break' in q:
                    speak('shutting down')
                    break


main_function()
Nimantha
  • 6,405
  • 6
  • 28
  • 69
ritik
  • 21
  • 3

1 Answers1

0

Put your code in a function and after every query put the function there, it will loop. Here is an example below with your code:

def main():

    def transform():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print('Listening...')
            r.pause_threshold = 1
            said = r.listen(source)

            try:
                q = r.recognize_google(said, language='en-in')
                print(f"You said:{q}\n")

            except sr.UnknownValueError:
                print("Didn't catch that")
                return "Waiting for input"

            except sr.RequestError:
                print('server down')
                return "Waiting for input"

            except:
                return "Waiting for input"
        return q


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


    def wish_me():
        hour = datetime.datetime.now().hour
        if 0 <= hour < 12:
            speak("Hello, Good Morning.")
            print("Hello, Good Morning.")
            main()
        elif 12 <= hour < 18:
            speak("Hello, Good Afternoon.")
            print("Hello, Good Afternoon.")
            main()
        else:
            speak("Hello, Good Evening.")
            print("Hello, Good Evening.")
            main()

    def query_day():
        f_date = datetime.date.today()
        weekday = f_date.weekday()
        date = datetime.date.today().day
        month = datetime.date.today().month


        weekday_mapping = {
            0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday',
        }

        month_mapping = {
            1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August',
            9: 'September', 10: 'October', 11: 'November', 12: 'December '
        }
        print(f"Today is {weekday_mapping[weekday]}, {date} {month_mapping[month]}.")
        try:
            speak(f"Today is {weekday_mapping[weekday]}, {date} {month_mapping[month]}.")
            main()
        except:
            pass


    def query_time():
        str_time = datetime.datetime.now().strftime("%I:%M %p")
        speak(f"The time is {str_time}")
        print(f"The time is {str_time}")
        main()


    # heart of our assistant


    def main_function():
        wish_me()
        while True:
            q = transform().lower()
            if 'shadow' in q:
                playsound("C:\\Users\\vnsin\\PycharmProjects\\Shadow_Assistant\\7.mp3")

                while True:
                    q = transform().lower()

                    if 'youtube' in q:
                        speak('starting Youtube.')
                        webbrowser.open('https://www.youtube.com')
                        main()


                    elif 'google' in q:
                        code_path = r"C:\Program File(x86)\Google\Chrome\Application\chrome.exe"
                        speak('starting Google.')
                        os.startfile(code_path)
                        main()

                    elif 'zoom' in q or 'classes' in q or 'school' in q:
                        code_path = r"C:\Users\vnsin\AppData\Roaming\Zoom\bin\Zoom.exe"
                        speak('starting Zoom.')
                        os.startfile(code_path)
                        main()

                    elif 'wikipedia' in q:
                        speak('Searching Wikipedia...')
                        q = q.replace("wikipedia", "")
                        q = q.replace("search", "")
                        q = q.replace("for", "")
                        results = wikipedia.summary(q, sentences=3)
                        speak("According to Wikipedia")
                        print(results)
                        speak(results)
                        main()

                    elif 'joke' in q:
                        speak(pyjokes.get_joke())
                        main()

                    elif 'day' in q or 'date' in q:
                        query_day()
                        main()

                    elif 'time' in q:
                        query_time()
                        main()

                    elif 'switch window' in q:
                        speak("switching window")
                        pyautogui.hotkey("alt", "tab")
                        main()

                    elif 'task' in q or 'manager' in q:
                        speak("starting task manager")
                        pyautogui.hotkey("ctrl", "shift", "esc")
                        main()

                    elif 'show desktop' in q:
                        pyautogui.hotkey('win', 'm')
                        speak("showing desktop")
                        main()

                    elif 'stop' in q or 'offline' in q or 'turn off' in q or 'shut down' in q or 'break' in q:
                        speak('shutting down')
                        main()
main()
General Grievance
  • 4,555
  • 31
  • 31
  • 45
AstroGuy
  • 56
  • 6
  • no, this didn't work for me, maybe it has something to do with main_function() and main() – ritik Jan 24 '22 at 04:30