You are on page 1of 2

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()
self.r = sr.Recognizer()

self.voice_data = ""

def engine_speak(self, text)

text = str(text)
self.engine.say(text)
self.engine.runAndwait()

def record_audio(self, ask=""):

with sr.Microphone() as source:


if ask:
print("Recording")
self.engine_speak(ask)

audio = self.r.listen(source, 5,5)


print('looking at the data base')

try:
self.voice_data = self.r.recognize_bing(audio)
except sr.UnknownValueError:
self.engine_speak(f"Sorry {self.person}, I did not get what you
said. can you please repeat?")
except sr.RequestError:
self.engine_speak("Sorry Boss, my server is dow")

print(">>", self.voice_data.lower())
self.voice_data = self.voice_data.lower()
assert isinstance(self.voice_data,)
return self.voice_data.lower()

def engine_speak(self, audio_string):


audio_string = str(audio_string)
tts = gTTS(text=audio_string, 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_string)
os.remove(audio_file)
def there_exist(self, terms):

for term in terms:


if term in self.voice_data()
return True

def respond(self, voice_data):


if self.there_exist(['olá, oi, hey']):
greetigns = [f'ola {self.person}, o que vamos fazer chef?',
'ola chefe, como posso te ajudar?',
'ola chefe, o que precisa?']

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

if self.there_exist(['search for']) and 'youtube' not in voice_data:


search_term = voice_data.split("for")[-1]
url = "http://google.com/search?q=" + search_term
webbrowser.get().open(url)
self.engine_speak("foram é o que eu encontrei para" + search_term +
'on google')

if self.there_exist(['search youtube for']):


search_term = voice_data.split("for")[-1]
url = "http://www.youtube.com/results?search_query=" + search_term
webbrowser.get().open(url)
self.engine_speak("foram é o que eu encontrei para" + search_term +
'on youtube')

assistent = Virtual_assit('Dark', 'Naldo')

while True:

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

if assistent.there_exist(['tchau', 'adeus', 'ate mais', 'falou men', 'ate


depois'])
assistent.engine_speak("ate mais chefe")

You might also like