-
Notifications
You must be signed in to change notification settings - Fork 0
/
cv.py
173 lines (148 loc) · 6.26 KB
/
cv.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
from selenium import webdriver
from pymongo import MongoClient
import json
import re
from os import path, environ
from datetime import datetime
import smtplib
class Coronavirus():
# constructor
def __init__(self):
# read config, if config.json file is not available then try OS environment vars
if path.exists('config.json'):
with open('config.json') as config_file:
self.config = json.load(config_file)
else:
self.config = {
"mongodb": {
"url": environ.get("DATABASE_URL"),
"database": environ.get("DATABASE_NAME")
},
"other": {
"chromedriver_binary": environ.get("CHROMEDRIVER_PATH"),
"data_url": environ.get("DATA_URL"),
"dashboard_url": environ.get("DASHBOARD_URL")
},
"smtp": {
"user": environ.get("SMTP_USER"),
"password": environ.get("SMTP_PASSWORD"),
"email_from": environ.get("EMAIL_FROM"),
"email_to": environ.get("EMAIL_TO"),
}
}
# set up chromedriver options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
# set up selenium chrome driver
self.driver = webdriver.Chrome(self.config["other"]["chromedriver_binary"], options=chrome_options)
# connect to MongoDB/Atlas
self.client = MongoClient(self.config["mongodb"]["url"])
self.db = self.client.get_database(self.config["mongodb"]["database"])
# scrape source data from FLDOH
def get_data(self):
try:
self.driver.get(self.config["other"]["data_url"])
table = self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[2]/div[3]/div/div[2]/block/table')
# build a collection of cases (dictionaries)
row_num = 0
cases = []
for row in table.find_elements_by_css_selector('tr'):
if row_num >= 2:
cells = row.find_elements_by_tag_name('td')
case = {
"case_number": int(re.sub("[^0-9]", "", cells[0].text)),
"county": cells[1].text,
"age": int(re.sub("[^0-9]", "", cells[2].text)) if cells[2].text.strip() else 'Unknown',
"sex": cells[3].text,
"travel": cells[4].text,
"date_added": datetime.now()
}
cases.append(case)
row_num+=1
# store to database
store_result = self.store_data(cases)
self.driver.close()
self.client.close()
except Exception as e:
print(str(e))
self.driver.quit()
return {
"success": False,
"message": str(e)
}
return {
"success": True,
"message": "{} new cases and {} cases under investigation".format(store_result['new_cases'],
store_result['under_investigation'])
}
# store case data to Atlas/MongoDB instance
def store_data(self, cases):
records = self.db.florida
cursor = records.aggregate([
{
"$group": {
"_id": None,
"max_case": {"$max": "$case_number"}
}
}
])
result = list(cursor)
max_case_number = 0
if len(result) > 0:
max_case_number = result[0]['max_case']
# filter for new cases (case # > last case number added)
new_cases = list(filter(lambda item: item['case_number'] > max_case_number, cases))
# we'll refresh under investigation cases in case status changed
inv_cursor = records.find({"travel": "Under Investigation"}, {"case_number": 1})
under_investigation = list(map(lambda item: item['case_number'], list(inv_cursor)))
# filter for cases that need updating (under investigation)
update_cases = list(filter(lambda item: item['case_number'] in under_investigation, cases))
print("Found {} new cases.".format(len(new_cases)))
print("Found {} cases under investigation.".format(len(under_investigation)))
try:
if len(new_cases) > 0:
print("Adding new cases to database.")
self.db.florida.insert_many(new_cases)
if len(update_cases) > 0:
print("Updating under investigation cases.")
for case in update_cases:
self.db.florida.update_one(
{"case_number": case['case_number']},
{"$set": {"travel": case['travel']}},
upsert=False)
except Exception as e:
print(str(e))
return {
"success": False,
"message": str(e)
}
return {
"success": True,
"message": "",
"new_cases": len(new_cases),
"under_investigation": len(update_cases)
}
# sends email notification with the specified message and analytics dashboard URL
def send_mail(self, message):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(self.config["smtp"]["user"], self.config["smtp"]["password"])
subject = 'Florida COVID-19 Status'
dashboard_url = self.config["other"]["dashboard_url"]
body = f"{message}\nCheck out the analytics dashboard: {dashboard_url}"
msg = f"Subject: {subject}\n\n{body}"
server.sendmail(
self.config["smtp"]["email_from"],
self.config["smtp"]["email_to"],
msg
)
print('Sent email notification')
server.quit()
bot = Coronavirus()
result = bot.get_data()
bot.send_mail(result['message'])