-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathvirtual_assistant.py
185 lines (152 loc) · 4.95 KB
/
virtual_assistant.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
'''
Description: Create your own virtual assistant with Python.
Author: aulerjbailey
Version: 2.0.0
Video: https://youtu.be/Cr9O31eqXuA
'''
import AVMSpeechMath as sm
import AVMYT as yt
import spoty
import speech_recognition as sr
import pyttsx3
import pywhatkit
import json
from datetime import datetime, date, timedelta
import wikipedia
import pyjokes
from time import time
start_time = time()
engine = pyttsx3.init()
# name of the virtual assistant
name = 'alexa'
attemts = 0
# keys
with open('src/keys.json') as json_file:
keys = json.load(json_file)
# colors
green_color = "\033[1;32;40m"
red_color = "\033[1;31;40m"
normal_color = "\033[0;37;40m"
# get voices and set the first of them
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
# editing default configuration
engine.setProperty('rate', 178)
engine.setProperty('volume', 0.7)
day_es = [line.rstrip('\n') for line in open('src/day/day_es.txt')]
day_en = [line.rstrip('\n') for line in open('src/day/day_en.txt')]
def iterateDays(now):
for i in range(len(day_en)):
if day_en[i] in now:
now = now.replace(day_en[i], day_es[i])
return now
def getDay():
now = date.today().strftime("%A, %d de %B del %Y").lower()
return iterateDays(now)
def getDaysAgo(rec):
value =""
if 'ayer' in rec:
days = 1
value = 'ayer'
elif 'antier' in rec:
days = 2
value = 'antier'
else:
rec = rec.replace(",","")
rec = rec.split()
days = 0
for i in range(len(rec)):
try:
days = float(rec[i])
break
except:
pass
if days != 0:
try:
now = date.today() - timedelta(days=days)
now = now.strftime("%A, %d de %B del %Y").lower()
if value != "":
return f"{value} fue {iterateDays(now)}"
else:
return f"Hace {days} días fue {iterateDays(now)}"
except:
return "Aún no existíamos"
else:
return "No entendí"
def speak(text):
engine.say(text)
engine.runAndWait()
def get_audio():
r = sr.Recognizer()
status = False
with sr.Microphone() as source:
print(f"{green_color}({attemts}) Escuchando...{normal_color}")
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
rec = ""
try:
rec = r.recognize_google(audio, language='es-ES').lower()
if name in rec:
rec = rec.replace(f"{name} ", "").replace("á", "a").replace("é", "e").replace("í", "i").replace("ó", "o").replace("ú", "u")
status = True
else:
print(f"Vuelve a intentarlo, no reconozco: {rec}")
except:
pass
return {'text':rec, 'status':status}
while True:
rec_json = get_audio()
rec = rec_json['text']
status = rec_json['status']
if status:
if 'estas ahi' in rec:
speak('Por supuesto')
elif 'reproduce' in rec:
if 'spotify' in rec:
music = rec.replace('reproduce en spotify', '')
speak(f'Reproduciendo {music}')
spoty.play(keys["spoty_client_id"], keys["spoty_client_secret"], music)
else:
music = rec.replace('reproduce', '')
speak(f'Reproduciendo {music}')
pywhatkit.playonyt(music)
# yt.play(music)
elif 'cuantos suscriptores tiene' in rec:
name_subs = rec.replace('cuantos suscriptores tiene', '')
speak("Procesando...")
while True:
try:
channel = yt.getChannelInfo(name_subs)
speak(channel["name"] + " tiene " + channel["subs"])
break
except:
speak("Volviendo a intentar...")
continue
elif 'que' in rec:
if 'hora' in rec:
hora = datetime.now().strftime('%I:%M %p')
speak(f"Son las {hora}")
elif 'dia' in rec:
if 'fue' in rec:
speak(f"{getDaysAgo(rec)}")
else:
speak(f"Hoy es {getDay()}")
elif 'busca' in rec:
order = rec.replace('busca', '')
wikipedia.set_lang("es")
info = wikipedia.summary(order, 1)
speak(info)
elif 'chiste' in rec:
chiste = pyjokes.get_joke("es")
speak(chiste)
elif 'cuanto es' in rec:
speak(sm.getResult(rec))
elif 'descansa' in rec:
speak("Saliendo...")
break
else:
print(f"Vuelve a intentarlo, no reconozco: {rec}")
attemts = 0
else:
attemts += 1
print(f"{red_color} PROGRAMA FINALIZADO CON UNA DURACIÓN DE: { int(time() - start_time) } SEGUNDOS {normal_color}")