dons02 / assistenteVirtualTina

Uma assistente virtual, assim como a alexa. Essa se chama Tina. pesquisa videos no youtube e faz pesquisa no google.
0 stars 0 forks source link

completo #2

Open dons02 opened 1 year ago

dons02 commented 1 year ago

import speech_recognition as sr import playsound from gtts import gTTS import random import webbrowser import pyttsx3 import os

class Virtual_assit(): def init(self, assist_name, person): self.person = person self.assit_name = assist_name

    self.engine = pyttsx3.init() #play no audio
    self.r = sr.Recognizer() #reconhecer a voz

    self.voice_data = '' #armazena o texto do audio

def engine_speak(self, text):
    """
    fala da assitente virtual
    """
    text = str(text) #converte o que foi dito em str
    self.engine.say(text) #dizer o que foi captado pelo audio
    self.engine.runAndWait() #rodar e esperar um pouco.

def record_audio(self, ask=""): #gravar o audio

    with sr.Microphone() as source: #ouvir o audio e gravar.
        if ask:
            print('Escutando...')
            self.engine_speak(ask) 

        audio = self.r.listen(source,5 , 5)# pega dados de audio de 5s
        print('Só um minuto, estou vasculhando o meu banco de dados.')
        try: #tratamento de erro.
            self.voice_data = self.r.recognize_google(audio) #converte audio para texto

        except sr.UnknownValueError:
            self.engine_speak('Me desculpe, não consegui entender. Poderia repetir?') #caso não entenda o que foi dito.

        except sr.RequestError:
            self.engine_speak('Sinto muito, não estou conseguindo me conectar ao servidor.') # Caso haja problemas de conexão.

        print(">>",self.voice_data.lower()) #imprime o que foi dito.
        self.voice_data = self.voice_data.lower()

        return self.voice_data.lower()

def engine_speak(self, audio_strig):
    audio_strig = str(audio_strig)
    tts = gTTS(text=audio_strig, lang='pt')
    r = random.randint(1,20000)
    audio_file = 'audio' + str(r) + '.mp3'
    tts.save(audio_file)
    playsound.playsound(audio_file)
    print(self.assit_name + ':', audio_strig)
    os.remove(audio_file)

def there_exist(self, terms):
    """
    função para identificar se o termo existe
    """
    for term in terms:
        if term in self.voice_data:
            return True

def respond(self, voice_data):
    if self.there_exist(['hey', 'hi', 'hello', 'oi', 'holla','olá', 'tina']):
        greetigns = [f'Olá {self.person}, o que temos pra hoje?',
                    'Ei mestre, em que posso lhe ajudar?',
                    'Olá mestre, o que você precisa?',
                    'Oi mestre, precisa de algo?']

        greet = greetigns[random.randint(0,len(greetigns)-1)]
        self.engine_speak(greet)

    #google
    if self.there_exist(['procure por']) and 'youtube' not in voice_data:
        search_term = voice_data.split("for")[-1]
        url =  "http://google.com.br/search?q=" + search_term
        webbrowser.get().open(url)
        self.engine_speak("foi isso que eu encontrei para " + search_term + 'no google')

    #google 
    if self.there_exist(["procure no youtube"]):
        search_term  = voice_data.split("no")[-1]
        url = "http://www.youtube.com/results?search_query=" + search_term
        webbrowser.get().open(url)
        self.engine_speak("aqui esta o resultado de " + search_term + 'no youtube')

    #spa
    if self.there_exist(['open sap']):
        pass

assistent = Virtual_assit('Lana', 'Nicolas')

while True:

voice_data = assistent.record_audio('Escutando...')
assistent.respond(voice_data)

if assistent.there_exist(['bye', 'goodbye', 'seeyou', 'see you later', 'see you', 'adeus', 'tchau','até mais', 'nos vemos depois']):
    assistent.engine_speak("Foi otimo estar com você, até mais!")
    break
dons02 commented 1 year ago

Projeto de assistente virtual. Ela puxa pesquisas no Google ou no Youtube conforme comando de voz.