2 votes

Assistant vocal en Python

J'ai mis en place ma structure de base, mais j'ai besoin d'une suggestion. Une fois que j'ai appelé l'assistant, il attend des requêtes, mais après cela, il s'arrête. Est-il possible de faire en sorte qu'après avoir répondu à la première requête, par exemple ouvrir YouTube, il attende une deuxième commande pendant un certain temps, puis s'arrête à nouveau ? Par ailleurs, existe-t-il une autre façon d'utiliser les commandes break/continue ? Je veux dire que les ajouter à toutes les requêtes prend un peu de temps.

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()

0voto

AstroGuy Points 16

Mettez votre code dans une fonction et après chaque requête, mettez la fonction à cet endroit, elle tournera en boucle. Voici un exemple ci-dessous avec votre 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()

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X