-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchatbot.py
More file actions
384 lines (316 loc) · 15.6 KB
/
chatbot.py
File metadata and controls
384 lines (316 loc) · 15.6 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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import requests
import json
import re
import threading
import time
import string
API_KEY = "tTwOPEfNOXmB"
PROJECT_TOKEN = "ts9X3T1m_aCb"
RUN_TOKEN = "tgNTTV9TKzkz" # "toi8Txr1XDon"
startTime = time.time()
auto_update = False
class Data:
def __init__(self, api_key, project_token):
self.api_key = api_key
self.project_token = project_token
self.params = { "api_key": self.api_key }
self.data = self.get_data()
def get_data(self):
response = requests.get(
f'https://www.parsehub.com/api/v2/projects/{self.project_token}/last_ready_run/data', params=self.params)
data = json.loads(response.text)
return data
# GET HELP
def getHelp(self):
help_txt = "Some questions you can ask me are:\n" +\
"How many total cases are there?\n" +\
"How many new cases are there?\n" +\
"Give me the deaths in the US.\n" +\
"How many new deaths have there been in the US?\n" +\
"How many people have recovered from COVID in California?\n" +\
"Give me the number of active cases in San Luis Obispo.\n" +\
"How many tests have been given in Santa Clara?\n"
return help_txt
# TIMESTAMP
def getTimestamp(self):
data = self.data['timestamp']
return data
# WORLD and USA
def getStoreData(self, key):
try:
return self.data[key], key
except KeyError:
return 0, 0
except:
return None, None
# CALIFORNIA
def getStoreCaliData(self, key):
data = self.data['covid_urls']
try:
return data[0][key], key
except KeyError:
return 0, 0
except:
return None, None
# CITIES
def getStoreCityData(self, find_city, key):
data = self.data['covid_urls']
try:
print('here13')
for content in data:
for city in content['cities']:
if city['name'].lower() == find_city.lower():
return city[key], key, city['name']
except KeyError:
return 0, 0, 0
except:
return None, None, None
# Get Cities in a list
def get_city_list(self):
city_list = []
data = self.data['covid_urls']
for content in data:
for city in content['cities']:
city_list.append(city['name'].lower())
return city_list
def update_data(self):
response = requests.post(
f'https://www.parsehub.com/api/v2/projects/{self.project_token}/run', params=self.params)
def poll():
time.sleep(0.1)
old_data = self.data
while True:
new_data = self.get_data()
if new_data != old_data:
self.data = new_data
print("Data updated!")
break
time.sleep(5)
t = threading.Thread(target=poll)
t.start()
def transcribe_response(pattern_items, text, city_list):
for pattern, func in pattern_items:
if pattern.match(text):
result, request, city_name = None, None, None
try:
result, request = func()
# if request == 'total_cases':
if (result != 0 and request != 0) and (request.find('world') == -1 or request.find('usa') == -1):
city_name = 'California'
except ValueError:
result = func()
except TypeError:
for city in city_list:
if city in text:
result, request, city_name = func(city)
if result == None and (request == None or city_name == None): # case when nothing reads
return "An internal error occurred."
if result == 0 and request == 0: # case if no data found
return False
if request == None: # case when asking for the last update time
return result
location, id_type = parse_name(request)
if location == None:
location, id_type = city_name, ''
if request == (id_type + 'total_cases'):
return "There have been a total of %s cases in %s." % (result, location)
elif request == (id_type + 'new_cases'):
return "There have been a total of %s new cases in %s today." % (result, location)
elif request == (id_type + 'total_deaths'):
return "There have been a total of %s deaths in %s." % (result, location)
elif request == (id_type + 'new_deaths'):
return "There have been a total of %s new deaths in %s today." % (result, location)
elif request == (id_type + 'total_recovered'):
return "There have been a total of %s people recovered in %s." % (result, location)
elif request == (id_type + 'active_cases'):
return "There are a total of %s active cases in %s." % (result, location)
elif request == (id_type + 'total_tests'):
return "There are have been a total of %s tests given in %s." % (result, location)
def parse_name(request):
location = request
if request.find('_') != -1:
location = request[:request.find('_')]
if location == 'usa':
return 'United States', 'usa_'
elif location == 'world':
return 'the world', 'world_'
return None, None
def add_chr_to_text(text: str):
new_text = 'a '
char = 'a'
us_list = ['u.s', 'usa', 'u.s.a', 'u.s.', 'u.s.a.', 'united states']
for us in us_list:
text = text.replace(us, 'us')
split = text.split()
world = False
key_list = ['world', 'global', 'globally', 'worldwide', 'international', 'internatonally']
if split[-1] == 'there' and split[-2] == 'are':
world = True
city_list = ['contra', 'santa', 'del', 'el', 'san', 'los']
for idx, word in enumerate(split):
if word in key_list:
world = True
if word in city_list:
if split[idx + 1] == 'luis':
word += " " + split[idx + 1] + " " + split[idx + 2]
word += " " + split[idx + 1]
word += ' a '
new_text += word
return (new_text, world)
def main(question: str):
""" takes in question from user, then trasnslates an answer """
print("Started Program")
thisData = Data(API_KEY, PROJECT_TOKEN)
ASK_PATTERNS = {
# ASK FOR HELP
re.compile("[\w\s]+ help [\w\s]+ "): lambda: thisData.getHelp(),
re.compile("[\w\s]+ help"): lambda: thisData.getHelp(),
re.compile("help [\w\s]+"): lambda: thisData.getHelp(),
}
TIMESTAMP_PATTERNS = {
# TIMESTAMP
re.compile("[\w\s]+ updated [\w\s]+"): lambda: thisData.getTimestamp(),
re.compile("[\w\s]+ update [\w\s]+ "): lambda: thisData.getTimestamp(),
}
TOTAL_PATTERNS = {
# WORLD
# Total Recovered
re.compile("[\w\s]+ recovered [\w\s]+"): lambda: thisData.getStoreData('world_total_recovered'),
# Active Cases
re.compile("[\w\s]+ active [\w\s]+"): lambda: thisData.getStoreData('world_active_cases'),
# Total Tests
re.compile("[\w\s]+ tests [\w\s]+"): lambda: thisData.getStoreData('world_total_tests'),
# New Cases
re.compile("[\w\s]+ new [\w\s]+ cases [\w\s]+"): lambda: thisData.getStoreData('world_new_cases'),
# New Deaths
re.compile("[\w\s]+ new [\w\s]+ deaths [\w\s]+"): lambda: thisData.getStoreData('world_new_deaths'),
# Total Cases
re.compile("[\w\s]+ cases [\w\s]+"): lambda: thisData.getStoreData('world_total_cases'),
# Total Deaths
re.compile("[\w\s]+ deaths [\w\s]+"): lambda: thisData.getStoreData('world_total_deaths'),
}
USA_PATTERNS = {
# US
# Total Recovered
re.compile("[\w\s]+ us [\w\s]+ recovered [\w\s]+"): lambda: thisData.getStoreData('usa_total_recovered'),
re.compile("[\w\s]+ recovered [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_total_recovered'),
# Active Cases
re.compile("[\w\s]+ us [\w\s]+ active [\w\s]+ cases [\w\s]+"): lambda: thisData.getStoreData('usa_active_cases'),
re.compile("[\w\s]+ active [\w\s]+ cases [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_active_cases'),
re.compile("[\w\s]+ cases [\w\s]+ active [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_active_cases'),
# Total Tests
re.compile("[\w\s]+ us [\w\s]+ tests [\w\s]+"): lambda: thisData.getStoreData('usa_total_tests'),
re.compile("[\w\s]+ tests [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_total_tests'),
# New Cases
re.compile("[\w\s]+ us [\w\s]+ new [\w\s]+ cases [\w\s]+"): lambda: thisData.getStoreData('usa_new_cases'),
re.compile("[\w\s]+ new [\w\s]+ cases [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_new_cases'),
# New Deaths
re.compile("[\w\s]+ us [\w\s]+ new [\w\s]+ deaths [\w\s]+"): lambda: thisData.getStoreData('usa_new_deaths'),
re.compile("[\w\s]+ new [\w\s]+ deaths [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_new_deaths'),
re.compile("[\w\s]+ deaths [\w\s]+ new [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_new_deaths'),
# Total Cases
re.compile("[\w\s]+ us [\w\s]+ cases [\w\s]+"): lambda: thisData.getStoreData('usa_total_cases'),
re.compile("[\w\s]+ cases [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_total_cases'),
# Total Deaths
re.compile("[\w\s]+ us [\w\s]+ deaths [\w\s]+"): lambda: thisData.getStoreData('usa_total_deaths'),
re.compile("[\w\s]+ deaths [\w\s]+ us [\w\s]+"): lambda: thisData.getStoreData('usa_total_deaths'),
}
CALIFORNIA_PATTERNS = {
# CALIFORNIA
# Total Recovered
re.compile("[\w\s]+ california [\w\s]+ recovered [\w\s]+"): lambda: thisData.getStoreData('usa_total_recovered'),
re.compile("[\w\s]+ recovered [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('total_recovered'),
# Active Cases
re.compile("[\w\s]+ california [\w\s]+ active [\w\s]+"): lambda: thisData.getStoreCaliData('active_cases'),
re.compile("[\w\s]+ active [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('active_cases'),
# Total Tests
re.compile("[\w\s]+ tests [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('total_tests'),
re.compile("[\w\s]+ california [\w\s]+ tests[\w\s]+"): lambda: thisData.getStoreCaliData('total_tests'),
# New Cases
re.compile("[\w\s]+ california [\w\s]+ new [\w\s]+ cases [\w\s]+"): lambda: thisData.getStoreCaliData('new_cases'),
re.compile("[\w\s]+ new [\w\s]+ cases [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('new_cases'),
re.compile("[\w\s]+ cases [\w\s]+ new [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('new_cases'),
# New Deaths
re.compile("[\w\s]+ california [\w\s]+ new [\w\s]+ deaths [\w\s]+"): lambda: thisData.getStoreCaliData('new_deaths'),
re.compile("[\w\s]+ new [\w\s]+ deaths [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('new_deaths'),
re.compile("[\w\s]+ deaths [\w\s]+ new [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('new_deaths'),
# Total Cases
re.compile("[\w\s]+ cases [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('total_cases'),
re.compile("[\w\s]+ california [\w\s]+ cases [\w\s]+"): lambda: thisData.getStoreCaliData('total_cases'),
# Total Deaths
re.compile("[\w\s]+ california [\w\s]+ deaths [\w\s]+"): lambda: thisData.getStoreCaliData('total_deaths'),
re.compile("[\w\s]+ deaths [\w\s]+ california [\w\s]+"): lambda: thisData.getStoreCaliData('total_deaths'),
}
CITY_PATTERNS = {
# CITIES
# Total Recovered
re.compile("[\w\s]+ recovered [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'total_recovered'),
# Active Cases
re.compile("[\w\s]+ active [\w\s]+ cases [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'active_cases'),
re.compile("[\w\s]+ cases [\w\s]+ active [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'active_cases'),
# Total Tests
re.compile("[\w\s]+ tests [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'total_tests'),
# New Cases
re.compile("[\w\s]+ new [\w\s]+ cases [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'new_cases'),
re.compile("[\w\s]+ cases [\w\s]+ new [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'new_cases'),
# New Deaths
re.compile("[\w\s]+ new [\w\s]+ deaths [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'new_deaths'),
re.compile("[\w\s]+ deaths [\w\s]+ new [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'new_deaths'),
# Total Cases
re.compile("[\w\s]+ cases [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'total_cases'),
# Total Deaths
re.compile("[\w\s]+ deaths [\w\s]+"): lambda city: thisData.getStoreCityData(city, 'total_deaths'),
}
UPDATE_COMMAND = "update"
for punc in string.punctuation:
question = question.replace(punc, '')
text = question.lower()
key = False
text, key = add_chr_to_text(text)
result = "I'm sorry, I don't understand that phrase."
city_list = thisData.get_city_list()
pattern_list = [ASK_PATTERNS, TIMESTAMP_PATTERNS, USA_PATTERNS, CALIFORNIA_PATTERNS, CITY_PATTERNS, TOTAL_PATTERNS]
if key == True: # check if 'world' is in the word
print('key is True')
response = transcribe_response(TOTAL_PATTERNS.items(), text, city_list)
if response == False:
for pattern, func in TIMESTAMP_PATTERNS.items():
text = "when was it last updated"
pattern.match(text)
result = func()
return "No data found for this request. %s" % (result)
elif response != None:
return response
else:
for pattern in pattern_list:
response = transcribe_response(pattern.items(), text, city_list)
if response == False:
for pattern, func in TIMESTAMP_PATTERNS.items():
text = "when was it last updated"
pattern.match(text)
result = func()
return "No data found for this request. %s" % (result)
if response != None:
return response
if auto_update and time.time() - startTime <= 3600:
result = "Data is being updated. This may take a moment!"
startTime = time.time()
thisData.update_data()
return result
if __name__ == "__main__":
phrase = "How many total new cases are there"
# phrase = "How many total cases are there in Canada"
# phrase = "How many total cases are there in USA"
# phrase = "How many total cases are there in Argentina"
# phrase = "How many total deaths are there"
# phrase = "How many cases are there"
# phrase = "how many cases in napa"
# phrase = "How many total ca,ses i*n u-s?"
# phrase = "how many active cases are there"
phrase = "how many total cases are in the santa anna"
# phrase = "how many cases global"
# phrase = "When was it last updated"
# phrase = "How many new cases in california"
# phrase = "help"
ans = main(phrase)
print(ans)