-
Notifications
You must be signed in to change notification settings - Fork 0
/
cv-csv.py
176 lines (151 loc) · 5.93 KB
/
cv-csv.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
import csv
import json
import re
from pymongo import MongoClient
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": {
"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"),
}
}
# 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_case_data(self, csv_file):
locations = self.get_county_locations()
try:
file = open(csv_file)
csv_reader = csv.reader(file, delimiter=',')
# build a collection of cases (dictionaries)
row_num = 0
cases = []
for row in csv_reader:
case = {
"case_number": int(re.sub("[^0-9]", "", row[0])),
"county": row[1],
"age": int(re.sub("[^0-9]", "", row[2])) if row[2].strip() else 'Unknown',
"sex": row[3],
"travel": row[4],
"travel_detail": [ item.strip().title() if len(item.strip()) > 2 else item.strip() for item in row[5].split(";") ] if row[5] else None,
"contact_with_confirmed_case": row[6] if row[6] else 'Unknown',
"jurisdiction": row[7],
"date_added": datetime.strptime(row[8], '%m/%d/%y'),
"deceased": row[9],
"location": locations.get(row[1], None)
}
cases.append(case)
# store to database
store_result = self.store_data(cases, "florida")
self.client.close()
except Exception as e:
print(str(e))
return {
"success": False,
"message": str(e)
}
return {
"success": True,
"message": f"{store_result['new_cases']} new cases added"
}
def get_other_data(self, csv_file):
try:
file = open(csv_file)
csv_reader = csv.reader(file, delimiter=',')
# build a collection of records (dictionaries)
row_num = 0
stats = []
prev_tests = 0
for row in csv_reader:
record = {
"date": datetime.strptime(row[0], '%m/%d/%y'),
"hospitalized": int(row[1]),
"tests": int(row[2]),
"new_tests": int(row[2]) - prev_tests
}
prev_tests = record["tests"]
stats.append(record)
# store to database
store_result = self.store_data(stats, "other_stats")
self.client.close()
except Exception as e:
print(str(e))
return {
"success": False,
"message": str(e)
}
return {
"success": True,
"message": f"{store_result['new_cases']} new cases added"
}
# store case data to Atlas/MongoDB instance
def store_data(self, records, collection):
current_count = self.db.get_collection(collection).estimated_document_count()
new_records = len(records) - current_count
# remove all cases
self.db.get_collection(collection).delete_many({})
print(f"Adding {new_records} new records to collection {collection}.")
try:
if len(records) > 0:
print("Adding records to database.")
self.db.get_collection(collection).insert_many(records)
except Exception as e:
print(str(e))
return {
"success": False,
"message": str(e)
}
return {
"success": True,
"message": "",
"new_cases": new_records
}
# 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()
def get_county_locations(self):
counties_file = open('./datasets/json/florida_counties.json')
counties = json.load(counties_file)
locations_hash = {}
for county in counties:
locations_hash[county["county"]] = county["location"]
return locations_hash
bot = Coronavirus()
case_result = bot.get_case_data("./datasets/csv/cases.csv")
other_result = bot.get_other_data("./datasets/csv/other_stats.csv")
bot.send_mail(case_result['message'])