-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
310 lines (247 loc) · 11.3 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import pyttsx3
from datetime import datetime
import speech_recognition as sr
from random import choice, randint
import requests
from functions.online_ops import find_my_ip, get_latest_news, get_random_advice, get_random_joke, get_weather_report, play_on_youtube, search_on_google, search_on_wikipedia, send_email, cardapio_RU
from functions.os_ops import open_calculator, open_camera, open_cmd, open_notepad
from decouple import config
import serial
USERNAME = config('USER')
BOTNAME = config('BOTNAME')
RURL = config('RURL')
opening_text = [
"Ok, estou no processo.",
"Beleza, já iniciei.",
"Só um segundo.",
"Executando.",
"Claro! Estou fazendo isso."
]
listening_text = [
"Estou escutando.",
"O que deseja?",
"Eu!",
]
oracle = serial.Serial('COMX', 9600)
def speak(engine, text):
"""Used to speak whatever text is passed to it"""
engine.say(text)
engine.runAndWait()
def greet_user(engine):
"""Greets the user according to the time"""
hour = datetime.now().hour
if (hour >= 6) and (hour < 12):
speak(engine, f"Bom dia {USERNAME}")
elif (hour >= 12) and (hour < 18):
speak(engine, f"Boa tarde {USERNAME}")
elif (hour >= 18):
speak(engine, f"Boa noitinha {USERNAME}")
speak(engine, f"Eu sou {BOTNAME}. Como posso te ajudar?")
def take_user_input(engine):
"""Takes user input, recognizes it using Speech Recognition module and converts it into text"""
r = sr.Recognizer()
with sr.Microphone() as source:
print('Escutando....')
r.pause_threshold = 1
audio = r.listen(source)
try:
print('Reconhecendo...')
query = r.recognize_google(audio, language='pt-BR')
if not 'sair' in query or 'pare' in query:
speak(engine, choice(opening_text))
set_oracle(oracle,2)
# else:
# hour = datetime.now().hour
# if hour >= 21 and hour < 6:
# speak(engine, "Boa noite, cuide-se!")
# else:
# speak(engine, 'Tenha um bom dia!')
# exit()
except Exception:
query = 'None'
return query
def set_oracle(oracle,state):
oracle.write(str(state).encode() + b'\n')
def listen(engine):
"""Takes user input, recognizes it using Speech Recognition module and converts it into text"""
r = sr.Recognizer()
with sr.Microphone() as source:
r.pause_threshold = 1
audio = r.listen(source)
try:
query = r.recognize_google(audio, language='pt-BR')
print(query)
if not 'sair' in query or 'pare' in query:
pass
else:
# hour = datetime.now().hour
# if hour >= 18 and hour < 6:
# speak(engine, "Boa noite, cuide-se!")
# else:
# speak(engine, 'Tenha um bom dia!')
print("Saindo...")
exit()
except Exception:
query = 'None'
return query
def main():
esp_ip = "192.168.1.103"
volume = 1.5
engine = pyttsx3.init('sapi5')
# Set Rate
engine.setProperty('rate', 210)
# Set Volume
engine.setProperty('volume', volume)
# Set Voice (Female)
# The getProperty method returns a list of voices available in the system.
voices = engine.getProperty('voices')
# engine.setProperty('voice', voices[1].id)
for voice in voices:
if "brazil" in voice.name.lower():
engine.setProperty('voice', voice.id)
break
greet_user(engine)
while True:
query = listen(engine).lower()
set_oracle(oracle,0)
if 'faraday' in query or 'faradai' in query or 'faradei' in query:
speak(engine, choice(listening_text))
while True:
set_oracle(oracle,1)
query = take_user_input(engine).lower()
if 'abrir bloco de notas' in query:
open_notepad()
break
elif 'abrir prompt de comando' in query or 'abrir cmd' in query:
open_cmd()
break
elif 'se apresente' in query or 'apresente-se' in query:
speak(engine,
f'Olá, eu sou a Faraday, a assistente virtual do PET Elétrica Ufes. Caso deseje minha ajuda basta me chamar que eu atenderei. Se quiser uma lista dos possíveis comandos que eu executo, basta dizer Comandos que explicarei.')
break
elif 'abrir camera' in query:
open_camera()
break
elif 'ru do dia' in query or 'ru' in query or 'cardápio ru' in query:
cardapio = cardapio_RU(RURL, datetime.now().hour)
speak(engine,
f'RU, {cardapio}')
break
elif 'acender' in query:
url_on = f"http://{esp_ip}/H"
response_on = requests.get(url_on)
if response_on.status_code == 200:
print("LED aceso!")
else:
print("Falha ao acender o LED.")
break
elif 'apagar' in query:
url_on = f"http://{esp_ip}/L"
response_on = requests.get(url_on)
if response_on.status_code == 200:
print("LED apagado!")
else:
print("Falha ao apagar o LED.")
break
elif 'endereço de ip' in query:
ip_address = find_my_ip()
speak(engine,
f'Seu endereço de IP é: {ip_address}.\n TE EME JOTA')
print(f'Seu endereço de IP é: {ip_address}')
break
elif 'wikipedia' in query:
speak(engine, 'O quê você quer pesquisar na Wikipedia?')
search_query = take_user_input(engine).lower()
results = search_on_wikipedia(search_query)
speak(engine, f"De acordo com a Wikipedia, {results}")
speak(engine, "Estou printando na tela.")
print(results)
break
elif 'youtube' in query:
speak(engine, 'O quê você quer ver no YouTube?')
video = take_user_input(engine).lower()
play_on_youtube(video)
break
elif 'pesquisar' in query:
speak(engine, 'O que vocÊ quer pesquisar no Google?')
query = take_user_input(engine).lower()
search_on_google(query)
break
elif 'receba os alunos' in query or 'receba' in query:
speak(engine,
f'Olá! Sejam bem-vindos ao PET Elétrica. Eu sou a Farady, sua assistente virtual e estou aqui para tornar a sua visita uma experiência fantástica.'\
'Estamos ansiosos para mostrar a vocês o emocionante mundo da ciência, experimentação e descoberta.' \
'Vocês estão prestes a embarcar em uma jornada emocionante, cheia de curiosidades, aprendizado e diversão. Aqui, a imaginação é o nosso combustível,' \
'e as possibilidades são infinitas. Aqui, vocês poderão explorar, fazer perguntas e aprender de uma maneira única e envolvente.')
break
# elif "enviar email" in query:
# speak(
# engine, "Entre com o email para o qual deseja enviar.")
# receiver_address = input("Entre ocm o endereço de email: ")
# speak(engine, "Qual deve ser o assunto?")
# subject = take_user_input(engine).capitalize()
# speak(engine, "Qual é a mensagem?")
# message = take_user_input(engine).capitalize()
# if send_email(receiver_address, subject, message):
# speak(engine, "Email enviado.")
# else:
# speak(engine,
# "Algo deu errado enquanto enviava o email,por favor, cheque o log de erro.")
# break
elif 'piadoca' in query:
speak(engine, f"Espero que goste dessa.")
joke = get_random_joke()
speak(engine, joke)
speak(engine, "Estou printando na tela.")
break
elif "conselho" in query:
speak(engine, f"Aqui vai um conselho para você.")
advice = get_random_advice()
speak(engine, advice)
speak(engine, "Estou printando na tela.")
break
elif 'notícias' in query:
speak(engine, f"Estou lendo as últimas notícias.")
speak(engine, get_latest_news())
speak(engine, "Estou printando na tela.")
print(*get_latest_news(), sep='\n')
break
elif 'clima' in query:
ip_address = find_my_ip()
city = requests.get(f"https://ipapi.co/{ip_address}/city/").text
speak(engine, f"Procurando o relatório do tempo de {city}.")
weather, temperature, feels_like = get_weather_report(city)
speak(engine,
f"A temperatura atual é {temperature}, com a sensação térmica de {feels_like}")
speak(engine, f"Também, é falado no relatório que {weather}")
speak(engine, "Estou printando na tela.")
print(
f"Descrição: {weather}\n Temperatura: {temperature}\n Sensação: {feels_like}")
break
elif 'sorteio' in query:
speak(engine, 'De quanto a quanto?')
while True:
query = take_user_input(engine).lower()
lims = query.split()
if len(lims) > 0:
try:
inf = int(lims[1])
sup = int(lims[3])
num = randint(inf, sup)
speak(engine, f"Seu número é {num}")
print(num)
break
except ValueError:
speak("Desculpe, não consegui entender os números. Certifique-se de que você forneceu números válidos.")
else:
set_oracle(oracle,3)
speak("Desculpe, não consegui entender os números. Certifique-se de que você forneceu números válidos.")
break
elif 'sair' in query:
exit()
elif query != None:
speak(engine,
'Desculpe, não consegui entender. Você poderia repetir?')
if __name__ == '__main__':
main()
# variação de volume