-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathChatbot.py
More file actions
239 lines (184 loc) · 6.71 KB
/
Chatbot.py
File metadata and controls
239 lines (184 loc) · 6.71 KB
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
import random
import re
import pygame
import string
from gtts import gTTS
import time
import pyttsx3
import speech_recognition as sr
mic_name = "sysdefault"
sample_rate = 48000
chunk_size = 2048
name = "Xertia"
event = "Shehack"
engine = pyttsx3.init()
pygame.mixer.init()
pygame.init()
footprint = 20.8
start = 0
meal = 0
shop = 0
tree = 0
end = 0
solar = 0
car = 0
car_f = 0
food = ['kitchen', 'zomato', 'swiggy', 'big basket', 'cooking', 'hungry', 'starving', 'food']
cupboard = ['amazon', 'snapdeal', 'flipkart', 'shop', 'myntra', 'clothes']
green = ['planted', 'composting', 'watered']
panel = ['solar', 'panel', 'renewable']
travel = ['cab', 'cycle', 'walk', 'scooter', 'rickshaw', 'flight', 'plane', 'train', 'air', 'travel']
endride = ['end', 'Android']
bot_template = "BOT : {0}"
user_template = "USER : {0}"
rules = { "hello": ["hey", "hello to you", "good morning"],
"(.*) name": [
"my name is {0}".format(name),
"they call me {0}".format(name),
"I go by {0}".format(name)
],
"(.*) event": [
"Today's event is {0}".format(event),
"it's {0} today".format(event)
],
"I want to go to (.*)": ["We have come to {0}."],
"I want to order (.*)": ["Carbon footprint for {0} have been calculated."],
"end ride": ["Your ride has been ended", "Carbon footprint for your ride has been calculated!"],
"I want to book a (.*)": ["Book an Ola or Uber?"],
"Ola": ["Okay, your ride has been started"],
"uber":["Okay, your ride has been started"],
"order through (.*)": ["Thanks for using our website!"],
"(.*) hungry": ["Let's redirect you to the kitchen"],
"(.*) starving": ["Let's redirect you to the kitchen"],
"I am taking a (.*)": ["Your ride has been started"],
"(.*) footprint":["Your carbon footprint is " + str(footprint)],
}
# Define variables
# Define a dictionary with the predefined responses
'''def replace_pronouns(message):
message = message.lower()
if 'me' in message:
# Replace 'me' with 'you'
return re.sub('me','you',message)
if 'my' in message:
# Replace 'my' with 'your'
return re.sub('my','your',message)
if 'your' in message:
# Replace 'your' with 'my'
return re.sub('your','my',message)
if 'you' in message:
# Replace 'you' with 'me'
return re.sub('you', 'me', message)
return message'''
def match_rule(rules, message):
response, phrase = "Sorry, couldn't recognise", None
# Iterate over the rules dictionary
for pattern, responses in rules.items():
# Create a match object
match = re.search(pattern, message)
if match is not None:
# Choose a random response
global start
global end
global meal
global shop
global tree
global solar
global car
data = match.group(0)
data = data.split(" ")
for i in data:
if i in food:
meal += 1
elif i in cupboard:
shop += 1
elif i in green:
tree += 1
elif i in panel:
solar += 3
elif i in travel:
car += 1
start=time.time()
if i in endride:
end=time.time()
else:
meal += 0
shop += 0
tree += 0
solar += 0
car += 0
response = random.choice(responses)
if '{0}' in response:
phrase = match.group(1)
# Return the response and phrase
return response.format(phrase)
form_question = ["What is your name?",
"What car do you use?", ]
ans = []
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
def form_questions():
for que in form_question:
audio = gTTS(que, 'en', False)
name = randomString(2) + 'mp3'
audio.save(name)
pygame.mixer.music.load(name)
pygame.mixer.music.play(loops=1, start=0.0)
time.sleep(10)
pygame.mixer.music.set_volume(10)
r = sr.Recognizer()
mic_list = sr.Microphone.list_microphone_names()
for i, microphone_name in enumerate(mic_list):
if microphone_name == mic_name:
device_id = i
with sr.Microphone(device_index=device_id, sample_rate=sample_rate,
chunk_size=chunk_size) as source:
r.adjust_for_ambient_noise(source)
print("Say Something")
audio = r.listen(source) # listens for the user's input
try: # error occurs when google could not understand what was said
ans = r.recognize_google(audio)
print("you said: " + ans)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
global car_f
if ans[1] is "diesel":
car_f = 6.99
elif ans[1] is "petrol":
car_f = 8.04
#form_questions()
for i in range(0,60):
r = sr.Recognizer()
mic_list = sr.Microphone.list_microphone_names()
for i, microphone_name in enumerate(mic_list):
if microphone_name == mic_name:
device_id = i
with sr.Microphone(device_index=device_id, sample_rate=sample_rate,
chunk_size=chunk_size) as source:
r.adjust_for_ambient_noise(source)
print("Say Something")
audio = r.listen(source) # listens for the user's input
try: # error occurs when google could not understand what was said
text = r.recognize_google(audio)
print("you said: " + text)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
if text == "end":
break
footprint += 4+((end-start)/3600*car_f)+(meal*2.34)-(solar*2.6)-(tree*0.05)+(shop*2.6)
bot = match_rule(rules, text)
audio = gTTS(bot, 'en', False)
print("BOT:"+ bot)
name = randomString(3) + 'mp3'
audio.save(name)
pygame.mixer.music.load(name)
pygame.mixer.music.play(loops=1, start=0.0)
time.sleep(10)
pygame.mixer.music.set_volume(10)
engine.runAndWait()