-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.py
506 lines (431 loc) · 17.2 KB
/
parse.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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
from pickle import load
from googleapiclient.discovery import build
from csv import reader
import json
from time import sleep
import datetime
from math import floor
from urllib.request import urlopen
from codecs import iterdecode
from urllib.error import HTTPError
from copy import deepcopy
with open('token.pickle', 'rb') as token:
creds = load(token)
service = build('sheets', 'v4', credentials=creds)
with open('api.key', 'r') as key:
apiKey = key.read()
drive = build('drive', 'v3', developerKey=apiKey)
fieldMap = {
'Confirmed COVID-19' : 'Confirmed',
'COVID-19 Persons Under Investigation' : 'Under Investigation',
'Cumulative COVID-19 Cases in Colorado by Date of Illness Onset' : 'Cases by Onset',
'Cumulative COVID-19 Cases in Colorado by Date Reported to the State': 'Cases',
'Cumulative Deaths Among COVID-19 Cases in Colorado by Date of Death': 'Deaths',
'Other' : 'Other',
'B.1.1.7 Alpha' : 'B.1.1.7',
'B.1.351 Beta' : 'B.1.351',
'P.1 Gamma' : 'P.1',
'B.1.617.2 Delta' : 'B.1.617.2',
'AY.2 Delta' : 'AY.2',
'AY.1 Delta' : 'AY.1',
'B.1.429' : 'B.1.429',
'B.1.427' : 'B.1.427',
'B.1.1.529 Omicron' : 'BA.1',
'BA.2 Omicron' : 'BA.2',
'BA.2.12.1 Omicron' : 'BA.2.12.1',
'BA.4 Omicron' : 'BA.4',
'BA.5 Omicron' : 'BA.5',
'BA.4.6 Omicron' : 'BA.4.6',
'BF.7 Omicron' : 'BF.7',
'BA.2.75 Omicron' : 'BA.2.75',
'BA.2.75.2 Omicron' : 'BA.2.75.2',
'BQ.1 Omicron' : 'BQ.1',
'BQ.1.1 Omicron' : 'BQ.1.1',
'BA.5.2.6 Omicron' : 'BA.5.2.6',
'BN.1 Omicron' : 'BN.1',
'BF.11 Omicron' : 'BF.11',
'CH.1.1 Omicron' : 'CH.1.1',
'XBB Omicron' : 'XBB',
'XBB.1.5 Omicron' : 'XBB.1.5',
'XBB.1.5.1 Omicron' : 'XBB.1.5.1',
'XBB.1.9.1 Omicron' : 'XBB.1.9.1',
'XBB.1.9.2 Omicron' : 'XBB.1.9.2',
'XBB.1.16 Omicron' : 'XBB.1.16',
'FD.2 Omicron' : 'FD.2',
'XBB.2.3 Omicron' : 'XBB.2.3',
'XBB.1.5.10 Omicron' : 'XBB.1.5.10',
'XBB.1.16.1 Omicron' : 'XBB.1.16.1',
'EU.1.1 Omicron' : 'EU.1.1',
'XBB.1.5.68 Omicron' : 'XBB.1.5.68',
'EG.5 Omicron' : 'EG.5',
'XBB.1.5.59 Omicron' : 'XBB.1.5.59',
'FE.1.1 Omicron' : 'FE.1.1',
'XBB.1.16.6 Omicron' : 'XBB.1.16.6',
'XBB.1.5.72 Omicron' : 'XBB.1.5.72',
'FL.1.5.1 Omicron' : 'FL.1.5.1',
'GE.1 Omicron' : 'GE.1',
'FD.1.1 Omicron' : 'FD.1.1',
'XBB.1.5.70 Omicron' : 'XBB.1.5.70',
'XBB.1.16.11 Omicron': 'XBB.1.16.11',
'EG.6.1 Omicron' : 'EG.6.1',
'XBB.2.3.8 Omicron' : 'XBB.2.3.8',
'HV.1 Omicron' : 'HV.1',
'XBB.1.42.2 Omicron' : 'XBB.1.42.2',
}
stateFields = list(fieldMap)[:5]
variantFields = list(fieldMap)[5:]
headers = [
'Last Updated' ,
'Date' , '', '',
'First Dose' , '% ', '', '',
'All Doses' , '% ', '', '',
'First Booster' , '% ', '', '',
'Second Booster' , '% ', '', '',
'Omicron Doses' , '% ',
'Date' ,
'Confirmed Cases' ,
'Under Investigation' , '',
'by date of illness onset', ' ',
'by date reported' , '',
'by date of death' , '',
'Tests' , ' ',
'Positive %' ,
]
counties = [
'Denver',
'El Paso',
'Arapahoe',
'Jefferson',
'Adams',
'Larimer',
'Douglas',
'Boulder',
'Weld',
'Pueblo',
'Mesa',
'Broomfield',
'Other',
]
def extendHeaders(titles):
headers.extend(titles)
for county in counties:
headers.append(county)
extendHeaders(['Cases' , 'Colorado'])
extendHeaders(['Weekly Cases' , 'Colorado'])
extendHeaders(['Deaths' , 'Colorado'])
extendHeaders(['Weekly Deaths' , 'Colorado'])
extendHeaders(['Tests' , 'Colorado'])
extendHeaders(['Weekly Tests' , 'Colorado'])
extendHeaders(['Positive %' , 'Colorado'])
extendHeaders(['Weekly Positive %', 'Colorado'])
variantHeaders = [fieldMap[field] for field in variantFields]
def printNow(*message):
print(*message, flush=True)
firstRun = True
lastHours = ''
lastHospitalDate = ''
lastStateDate = ''
lastVariantDate = ''
lastVariantReportDate = ''
lastVariantData = {}
lastUpdated = ['', '', '']
vaccineData = {}
vaccineDates = []
with open('vaccine_data.csv') as file:
vaccineCsv = reader(file)
for row in vaccineCsv:
vaccineDates.append(row[0])
vaccineData[row[0]] = row[1:]
testingData = {}
testDates = []
with open('testing_data.csv') as file:
testingCsv = reader(file)
for row in testingCsv:
testDates.append(row[0])
testingData[row[0]] = row[1:]
countyData = {}
countyDates = []
with open('county_data.csv') as file:
countyCsv = reader(file)
for row in countyCsv:
countyDates.append(row[0])
countyData[row[0]] = row[1:]
with open('variant_data.json') as file:
variantJson = json.load(file)
while True:
if not firstRun:
sleep(60)
firstRun = False
now = str(datetime.datetime.now())[:16]
hours = now[11:13]
if hours == lastHours:
continue
lastHours = hours
if now[-5:] == '00:00':
printNow('')
for i in range(len(lastUpdated)):
if not lastUpdated[i]:
lastUpdated[i] = now
data = {
'Colorado': {
'First Dose' : {},
'All Doses' : {},
'First Booster' : {},
'Second Booster' : {},
'Omicron Doses' : {},
'Confirmed' : {},
'Under Investigation': {},
'Cases by Onset' : {},
'Cases' : {},
'Deaths' : {},
'Tests' : {},
}
}
def formatDate(date):
return date[6:10] + '-' + date[0:2] + '-' + date[3:5]
def twoWeekEnd(date):
return str(datetime.date(int(date[0:4]), int(date[5:7]), int(date[8:10])) + datetime.timedelta(days=14))
def parseHospitalData(hospitalData):
readFields = True
for row in hospitalData:
if readFields:
icategory = row.index('category')
idescription = row.index('description')
iregion = row.index('region')
idate = row.index('date')
imetric = row.index('metric')
ivalue = row.index('value')
readFields = False
continue
category = row[icategory]
description = row[idescription]
region = row[iregion]
date = row[idate]
metric = row[imetric]
value = row[ivalue]
if category == 'Hospital Level' and description == 'Currently Hospitalized' and region == 'Colorado' and metric in stateFields:
data['Colorado'][fieldMap[metric]][date[:10].replace('/','-')] = int(value)
# CDPHE COVID19 Hospital Data
# https://data-cdphe.opendata.arcgis.com/datasets/CDPHE::cdphe-covid19-hospital-data
def getHospitalData():
try:
response = urlopen('https://opendata.arcgis.com/api/v3/datasets/bdf90453c5ca46338c51143a2edd810d_0/downloads/data?format=csv&spatialRefId=4326&where=1=1')
hospitalData = reader(iterdecode(response, 'utf-8-sig'))
parseHospitalData(hospitalData)
with open('covid19_hospital_data_2022-03-15.csv') as file:
hospitalData = reader(file)
parseHospitalData(hospitalData)
return True
except HTTPError as e:
printNow(now, '-- Error getting hospital data:', e.code)
return False
except Exception as e:
if str(e) == '[WinError 10053] An established connection was aborted by the software in your host machine':
sleep(1)
return getHospitalData()
else:
printNow(now, '-- Error getting hospital data:', str(e))
return False
if not getHospitalData():
continue
hospitalDates = sorted(list(set(data['Colorado']['Confirmed']) | set(data['Colorado']['Under Investigation'])))
if hospitalDates[-1] != lastHospitalDate:
updateData = True
lastHospitalDate = hospitalDates[-1]
lastUpdated[0] = now
printNow('Hospital data updated to', lastHospitalDate[5:])
# CDPHE COVID19 State-Level Expanded Case Data
# https://data-cdphe.opendata.arcgis.com/datasets/cdphe-covid19-state-level-expanded-case-data
try:
response = urlopen('https://opendata.arcgis.com/api/v3/datasets/cc2c6500f01e460690a1a25aa41528d3_0/downloads/data?format=csv&spatialRefId=4326&where=1=1')
stateData = reader(iterdecode(response, 'utf-8-sig'))
readFields = True
for row in stateData:
if readFields:
idescription = row.index('description')
idate = row.index('date')
ivalue = row.index('value')
readFields = False
continue
description = row[idescription]
date = row[idate]
value = row[ivalue]
if description in stateFields:
data['Colorado'][fieldMap[description]][date[:10].replace('/','-')] = int(value)
except HTTPError as e:
printNow(now, '-- Error getting state data:', e.code)
continue
except Exception as e:
printNow(now, '-- Error getting state data:', str(e))
continue
stateDates = sorted(list(set(data['Colorado']['Cases by Onset']) | set(data['Colorado']['Cases']) | set(data['Colorado']['Deaths'])))
if stateDates[-1] != lastStateDate:
updateData = True
lastStateDate = stateDates[-1]
lastUpdated[1] = now
printNow('State data updated to', lastStateDate[5:])
# Colorado SARS-CoV-2 Variant Sentinel Surveillance
# https://data-cdphe.opendata.arcgis.com/datasets/CDPHE::cdphe-covid19-sentinel-surveillance
try:
response = urlopen('https://opendata.arcgis.com/api/v3/datasets/2b58e4b5263342c6a6d75f3395bc18a9_0/downloads/data?format=csv&spatialRefId=4326&where=1=1')
variantData = reader(iterdecode(response, 'utf-8-sig'))
newVariantData = {}
readFields = True
for row in variantData:
if readFields:
iweek_start = row.index('week_start')
ivariant = row.index('variant')
inumber = row.index('number')
ipublish_date = row.index('publish_date')
readFields = False
continue
week_start = row[iweek_start]
variant = row[ivariant].replace('\n', ' ')
number = row[inumber]
publish_date = row[ipublish_date][:10].replace('/','-')
two_week_end = twoWeekEnd(week_start)
if two_week_end >= '2023-04-01':
if two_week_end not in newVariantData:
newVariantData[two_week_end] = {'Total': 0}
newVariantData[two_week_end]['Total'] += int(number)
if variant in variantFields:
newVariantData[two_week_end][fieldMap[variant]] = int(number)
else:
newVariantData[two_week_end][variant] = int(number)
except HTTPError as e:
printNow(now, '-- Error getting variant data:', e.code)
continue
except Exception as e:
printNow(now, '-- Error getting variant data:', str(e))
continue
if lastVariantReportDate != publish_date:
lastVariantReportDate = publish_date
printNow('Variant report published for', publish_date[5:])
if newVariantData != lastVariantData:
updateData = True
lastVariantData = deepcopy(newVariantData)
lastUpdated[2] = now
printNow('Variant data updated to', sorted(list(set(newVariantData)))[-1][5:])
with open('variant_data.json') as file:
variantJson = json.load(file)
for date in newVariantData:
variantJson[date] = newVariantData[date]
newVariants = {}
for date in variantJson:
for variant in variantJson[date]:
if variant != 'Total' and variant not in variantHeaders:
if variant in variantFields:
variantJson[date][fieldMap[variant]] = variantJson[date][variant]
del variantJson[date][variant]
else:
newVariants[variant] = True
if len(newVariants):
printNow('New variants:', list(newVariants))
with open('variant_data.json', 'w') as file:
json.dump(variantJson, file)
variantDates = sorted(list(set(variantJson)))
dates = sorted(list(set(vaccineDates) | set(hospitalDates) | set(stateDates) | set(testDates) | set(countyDates)))
if not updateData:
continue
def daysDiff(region, field, i, days):
if dates[i] not in data[region][field] or dates[i-days] not in data[region][field]:
return 0
if i > days - 1:
return max(0, data[region][field][dates[i]] - data[region][field][dates[i-days]])
else:
return max(0, data[region][field][dates[i]])
def strAverage(num, days):
if num == '':
return ''
return str(round(num/days, 3))
sheetData = [headers]
for i in range(len(dates)):
date = dates[i]
if i>0:
for field in stateFields:
if fieldMap[field] != 'Confirmed' and date not in data['Colorado'][fieldMap[field]] and dates[i-1] in data['Colorado'][fieldMap[field]]:
for j in range(i+1, len(dates)):
if dates[j] in data['Colorado'][fieldMap[field]]:
data['Colorado'][fieldMap[field]][date] = 0
break
if date < '2020-03-01':
continue
row = ['', date]
if date in vaccineDates:
row.extend(vaccineData[date])
else:
row.extend(['']*20)
if date in data['Colorado']['Confirmed'] or date == '2020-03-01' or date == dates[-1]:
row.append(date)
else:
row.append('')
for field in ['Confirmed', 'Under Investigation']:
if date in data['Colorado'][field]:
row.append(str(data['Colorado'][field][date]))
else:
row.append('')
for field in ['Cases by Onset', 'Cases', 'Deaths']:
row.extend([str(daysDiff('Colorado', field, i, 1)), strAverage(daysDiff('Colorado', field, i, 7), 7)])
if date in testDates:
row.extend(testingData[date])
else:
row.extend(['']*4)
if date in countyDates:
row.extend(countyData[date])
else:
row.extend(['']*120)
sheetData.append(row)
for i in range(len(lastUpdated)):
sheetData[i+1][0] = '\'' + lastUpdated[i]
variantData = [['Date', 'All Cases', 'Sampled %', 'Total'] + variantHeaders]
for date in variantDates:
if date < '2023-04-01':
days = 7
else:
days = 14
allCases = daysDiff('Colorado', 'Cases by Onset', dates.index(date), days) or daysDiff('Colorado', 'Cases', dates.index(date), days)
row = [
date,
strAverage(allCases, days),
str(round(variantJson[date]['Total']/allCases*100, 3)),
str(variantJson[date]['Total']),
]
for variant in variantHeaders:
if variant in variantJson[date]:
row.append(str(variantJson[date][variant]))
else:
row.append('')
variantData.append(row)
variantData.append([dates[-1]])
def updateSpreadsheet():
try:
service.spreadsheets().values().update(
spreadsheetId = '1dfP3WLeU9T2InpIzNyo65R8d_e7NpPea9zKaldEdYRA',
valueInputOption = 'USER_ENTERED',
range = 'Data!A1:EY',
body = dict(
majorDimension = 'ROWS',
values = sheetData,
),
).execute()
service.spreadsheets().values().update(
spreadsheetId = '1dfP3WLeU9T2InpIzNyo65R8d_e7NpPea9zKaldEdYRA',
valueInputOption = 'USER_ENTERED',
range = 'Data!JT1:LU',
body = dict(
majorDimension = 'ROWS',
values = variantData,
),
).execute()
return True
except Exception as e:
if str(e) == '[WinError 10053] An established connection was aborted by the software in your host machine':
sleep(1)
return updateSpreadsheet()
else:
printNow(now, '-- Error updating spreadsheet:', str(e))
return False
if not updateSpreadsheet():
continue
printNow(now, '-- Spreadsheet updated')
updateData = False