-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.py
101 lines (75 loc) · 2.7 KB
/
code.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
# for speech-to-text
import speech_recognition as sr
# for text-to-speech
from gtts import gTTS
# for language model
import transformers
import os
import time
# for data
import os
import datetime
import numpy as np
# Building the AI
class ChatBot():
def __init__(self, name):
print("----- Starting up", name, "-----")
self.name = name
def speech_to_text(self):
recognizer = sr.Recognizer()
with sr.Microphone() as mic:
print("Listening...")
audio = recognizer.listen(mic)
self.text="ERROR"
try:
self.text = recognizer.recognize_google(audio)
print("Me --> ", self.text)
except:
print("Me --> ERROR")
@staticmethod
def text_to_speech(text):
print("Dev --> ", text)
speaker = gTTS(text=text, lang="en", slow=False)
speaker.save("res.mp3")
statbuf = os.stat("res.mp3")
mbytes = statbuf.st_size / 1024
duration = mbytes / 200
os.system('start res.mp3') #if you are using mac->afplay or else for windows->start
# os.system("close res.mp3")
time.sleep(int(50*duration))
os.remove("res.mp3")
def wake_up(self, text):
return True if self.name in text.lower() else False
@staticmethod
def action_time():
return datetime.datetime.now().time().strftime('%H:%M')
# Running the AI
if __name__ == "__main__":
ai = ChatBot(name="dev")
nlp = transformers.pipeline("conversational", model="microsoft/DialoGPT-medium")
os.environ["TOKENIZERS_PARALLELISM"] = "true"
ex=True
while ex:
ai.speech_to_text()
## wake up
if ai.wake_up(ai.text) is True:
res = "Hello I am Dave the AI, what can I do for you?"
## action time
elif "time" in ai.text:
res = ai.action_time()
## respond politely
elif any(i in ai.text for i in ["thank","thanks"]):
res = np.random.choice(["you're welcome!","anytime!","no problem!","cool!","I'm here if you need me!","mention not"])
elif any(i in ai.text for i in ["exit","close"]):
res = np.random.choice(["Tata","Have a good day","Bye","Goodbye","Hope to meet soon","peace out!"])
ex=False
## conversation
else:
if ai.text=="ERROR":
res="Sorry, come again?"
else:
chat = nlp(transformers.Conversation(ai.text), pad_token_id=50256)
res = str(chat)
res = res[res.find("bot >> ")+6:].strip()
ai.text_to_speech(res)
print("----- Closing down Dev -----")