O assistente de desktop virtual é uma coisa incrível. Se você quiser que sua máquina execute sob seu comando, como Jarvis fez para Tony. Sim, é possível. É possível usar Python. Python oferece uma boa biblioteca principal para que possamos usá-la para fazer um assistente virtual. O Windows tem Sapi5 e o Linux tem Espeak que pode nos ajudar a ter a voz de nossa máquina. É uma IA fraca

Módulos necessários

  • pyttsx3: pyttsx é uma biblioteca multi-plataforma de texto para fala que é independente de plataforma. A principal vantagem de usar esta biblioteca para conversão de texto em fala é que ela funciona offline. Para instalar este módulo, digite o comando abaixo no terminal.
pip install pyttsx3
  • SpeechRecognition: permite converter áudio em texto para processamento posterior. Para instalar este módulo, digite o comando abaixo no terminal.
pip install SpeechRecognition
  • webbrowser: Ele fornece uma interface de alto nível que permite a exibição de documentos com base na Web para os usuários. Para instalar este módulo, digite o comando abaixo no terminal.
pip install webbrowser
  • Wikipedia: é usada para buscar uma variedade de informações no site da Wikipedia. Para instalar este módulo, digite o comando abaixo no terminal.
pip install wikipedia

Métodos usados ​​para Assistente Virtual

1) Método de fala

O Método Fale nos ajudará a tirar a voz da máquina. Aqui está a explicação do código do Método de Fala

def speak(audio): 
      
    engine = pyttsx3.init() 
    
    
    voices = engine.getProperty('voices') 
      
    
    
    engine.setProperty('voice', voices[0].id) 
      
    
    engine.say(audio)   
      
    
    
    engine.runAndWait()

 2) Pegue o método de consulta

Este método verificará a condição. Se a condição for verdadeira, ele retornará uma saída. Podemos adicionar qualquer número se houver condições para isso e se a condição satisfizer, obteremos a saída desejada.

def Take_query(): 
  
    
    
    Hello() 
      
    
    
    
    
    while(True): 
        
      
      query = takeCommand().lower() 
        if "open geeksforgeeks" in query: 
            speak("Opening GeeksforGeeks ") 
                      webbrowser.open("www.geeksforgeeks.com") 
            continue
        elif "open google" in query: 
            speak("Opening Google ") 
            webbrowser.open("www.google.com") 
            continue
            elif "which day it is" in query: 
            tellDay() 
            continue
        elif "tell me the time" in query: 
            tellTime() 
            continue
        
        elif "bye" in query: 
            speak("Bye. Check Out GFG for more exicting things") 
            exit() 
        elif "from wikipedia" in query: 
                    speak("Checking the wikipedia ") 
            query = query.replace("wikipedia", "") 
                      result = wikipedia.summary(query, sentences=4) 
            speak("According to wikipedia") 
            speak(result) 
        elif "tell me your name" in query: 
            speak("I am Jarvis. Your deskstop Assistant")

3) método takeCommand

Este método é para receber os comandos e reconhecer o comando do módulo speech_Recognition

def takeCommand(): 
  
    r = sr.Recognizer() 
  
    
    
    
    with sr.Microphone() as source: 
        print('Listening') 
        
      r.pause_threshold = 0.7
        audio = r.listen(source) 
        
      
      try: 
            print("Recognizing") 
                      Query = r.recognize_google(audio, language='en-in') 
            print("the command is printed=", Query) 
            except Exception as e: 
            print(e) 
            print("Say that again sir") 
            return "None"
        return Query

*) método tellTime

def tellTime(self): 
    time = str(datetime.datetime.now()) 
      
    
    print(time) 
    hour = time[11:13] 
    min = time[14:16] 
    self.Speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes")      
 
 
 
 

4) Método Hello

Isso é usado apenas para cumprimentar o usuário com uma mensagem de olá.



def Hello(): 
    
    
    
    speak("hello sir I am your desktop assistant. /
          Tell me how may I help you")

5) Método principal

O método principal é o método onde todos os arquivos são executados, então chamaremos o método Take_query aqui para que ele possa reconhecer e nos dizer ou nos dar a saída desejada. 

if __name__ == '__main__': 
      
    
    
    Take_query()

 Código Completo:

import pyttsx3 
import speech_recognition as sr 
import webbrowser   
import datetime   
import wikipedia  
  
  
def takeCommand(): 
  
    r = sr.Recognizer() 
  
    
    
    
    with sr.Microphone() as source: 
        print('Listening') 
        
      r.pause_threshold = 0.7
        audio = r.listen(source) 
        
      
      try: 
            print("Recognizing") 
                      Query = r.recognize_google(audio, language='en-in') 
            print("the command is printed=", Query) 
            except Exception as e: 
            print(e) 
            print("Say that again sir") 
            return "None"
        return Query 
  
def speak(audio): 
      
    engine = pyttsx3.init() 
    
    
    voices = engine.getProperty('voices') 
      
    
    
    engine.setProperty('voice', voices[0].id) 
      
    
    engine.say(audio)   
      
    
    
    engine.runAndWait() 
  
def tellDay(): 
      
    
    
    day = datetime.datetime.today().weekday() + 1
      
    
    
    Day_dict = {1: 'Monday', 2: 'Tuesday'
                3: 'Wednesday', 4: 'Thursday'
                5: 'Friday', 6: 'Saturday', 
                7: 'Sunday'} 
      
    if day in Day_dict.keys(): 
        day_of_the_week = Day_dict[day] 
        print(day_of_the_week) 
        speak("The day is " + day_of_the_week) 
  
  
def tellTime(): 
      
    
    time = str(datetime.datetime.now()) 
      
    
    
    
    print(time) 
    hour = time[11:13] 
    min = time[14:16] 
    speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes")     
  
def Hello(): 
      
    
    
    
    speak("hello sir I am your desktop assistant. /
          Tell me how may I help you") 
  
  
def Take_query(): 
  
    
    
    Hello() 
      
    
    
    
    
    while(True): 
        
      
      query = takeCommand().lower() 
        if "open geeksforgeeks" in query: 
            speak("Opening GeeksforGeeks ") 
                      webbrowser.open("www.geeksforgeeks.com") 
            continue
        elif "open google" in query: 
            speak("Opening Google ") 
            webbrowser.open("www.google.com") 
            continue
            elif "which day it is" in query: 
            tellDay() 
            continue
        elif "tell me the time" in query: 
            tellTime() 
            continue
        
        elif "bye" in query: 
            speak("Bye. Check Out GFG for more exicting things") 
            exit() 
        elif "from wikipedia" in query: 
                    speak("Checking the wikipedia ") 
            query = query.replace("wikipedia", "") 
                      result = wikipedia.summary(query, sentences=4) 
            speak("According to wikipedia") 
            speak(result) 
        elif "tell me your name" in query: 
            speak("I am Jarvis. Your deskstop Assistant") 
  
if __name__ == '__main__': 
      
    
    
    Take_query()

Resultado: