forked from covid19india/api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_raw_data.py
executable file
·279 lines (229 loc) · 9.41 KB
/
build_raw_data.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
import pandas as pd # pylint: disable=import-error
import re
from pathlib import Path
import logging
import sys
import os
from urllib.error import HTTPError
# Set logging level
logging.basicConfig(stream=sys.stdout,
format="%(message)s",
level=logging.INFO)
def fetch_raw_data_from_api():
'''
Read all raw data and death and recovery files
Pass the latest version of raw data
'''
i = 1
raw_d = []
while True:
try:
url = f"https://api.covid19india.org/csv/latest/raw_data{i}.csv"
df = pd.read_csv(url)
df.to_csv(f'./tmp/csv/latest/raw_data{i}.csv',index=False)
raw_d.append(df)
logging.info(f"Fetched raw_data{i} ")
i = i+1
except HTTPError:
current_ver = i-1
break
death_rec = []
logging.info(f"Fetching deaths_and_recoveries")
url = f"https://api.covid19india.org/csv/latest/death_and_recovered"
df = pd.read_csv(f"{url}1.csv")
death_rec.append(df)
df.to_csv('./tmp/csv/latest/death_and_recovered1.csv',index=False)
df = pd.read_csv(f"{url}2.csv")
death_rec.append(df)
df.to_csv('./tmp/csv/latest/death_and_recovered2.csv',index=False)
return raw_d,death_rec,current_ver
def fetch_raw_data():
'''
Read all raw data and death and recovery files
Return the latest number of raw data files
'''
raw_d = []
death_rec = []
fpath = Path('tmp/csv/latest')
i = 1
while True:
try:
df = pd.read_csv(fpath / f"raw_data{i}.csv")
raw_d.append(df)
logging.info(f"Fetched raw_data{i} ")
i = i+1
except FileNotFoundError:
current_ver = i-1
break
i = 1
while True:
try:
df = pd.read_csv(fpath / f"death_and_recovered{i}.csv")
death_rec.append(df)
logging.info(f"Fetched death_and_recovered{i} ")
i = i+1
except FileNotFoundError:
break
logging.info(f"Data read complete")
return raw_d,death_rec,current_ver
def fix_rawdata1and2(raw,rec,col_list,sheet_version):
'''
Raw Data 1 and 2 had different format
Select necessary columns and change data types
Add death and recovery data to raw_data
'''
print(f"V{sheet_version} Shape \t: {raw.shape}")
# Only choose the valid current statuses
raw = raw[raw['Current Status'].isin( ['Hospitalized','Recovered','Deceased','Migrated','Migrated_Other'])].copy()
#Prepare neceassary columns
raw['Num Cases'] = 1
raw['Entry_ID'] = 0
raw['Current Status'] = "Hospitalized"
raw = raw.fillna('')
raw = raw[col_list]
# If Detected State is not available, entry is invalid
raw = raw[raw['Detected State'] != ''].copy()
# Convert Date Announced string to datetime
raw['Date Announced'] = pd.to_datetime(raw['Date Announced'],format='%d/%m/%Y')
# Add Sheet Version Column
raw['Sheet_Version'] = sheet_version
# Only choose the valid current statuses
rec = rec[rec['Patient_Status'].isin(['Hospitalized','Recovered','Deceased','Migrated','Migrated_Other'])].copy()
# Prepare necessary columns
rec['Num Cases'] = 1
rec['Entry_ID'] = 0
rec['Current Status'] = rec['Patient_Status']
rec['Date Announced'] = rec['Date']
rec['State code'] = rec['Statecode']
rec['Detected City'] = rec['City']
rec['Status Change Date'] = ''
rec['Contracted from which Patient (Suspected)'] = ''
rec['Detected State'] = rec['State']
rec['Detected District'] = rec['District']
rec['Patient Number'] = rec['Patient_Number (Could be mapped later)']
rec['State Patient Number'] = ''
rec['Type of transmission'] = ''
rec = rec.fillna('')
rec = rec[col_list]
# If Detected State is not available, entry is invalid
rec = rec[rec['Detected State'] != ''].copy()
# Convert Date column from string to date
rec['Date Announced'] = pd.to_datetime(rec['Date Announced'],format='%d/%m/%Y')
# Add sheet version
rec['Sheet_Version'] = sheet_version
# Add deaths and recoveries to raw data
raw = pd.concat([raw,rec],sort=True)
return raw
def merge_alldata(current_ver):
'''
Merge it all together
'''
col_list = ['Entry_ID', 'State Patient Number', 'Date Announced', 'Age Bracket',
'Gender', 'Detected City', 'Detected District', 'Detected State',
'State code', 'Num Cases', 'Current Status',
'Contracted from which Patient (Suspected)', 'Notes', 'Source_1',
'Source_2', 'Source_3', 'Nationality', 'Type of transmission',
'Status Change Date', 'Patient Number']
allraw = fix_rawdata1and2(raw_d[0],death_rec[0],col_list,sheet_version=1)
tmp = fix_rawdata1and2(raw_d[1],death_rec[1],col_list,sheet_version=2)
allraw = pd.concat([allraw,tmp],sort=True)
for i in range(2,current_ver):
print(f"V{i+1} Shape \t: {tmp.shape}")
tmp = raw_d[i]
tmp = tmp.fillna('')
# Remove rows that doesn't have
# any State mentioned.
# This handles the situation at
# the tail of most recent sheet
tmp = tmp[tmp['Detected State'] != ''].copy()
# Select only necessary columns
tmp = tmp[col_list]
# Convert date string to datetime
tmp['Date Announced'] = pd.to_datetime(tmp['Date Announced'],format='%d/%m/%Y')
# Add sheet version
tmp['Sheet_Version'] = i+1
allraw = pd.concat([allraw,tmp],sort=True)
# Try to fix age to float
allraw['Age Bracket'] = allraw['Age Bracket'].map(lambda x : fix_age(x))
# Try to fix gender column
allraw['Gender'] = allraw['Gender'].map(lambda x : fix_gender(x))
print(f"Raw Data Shape \t: {allraw.shape}")
return allraw
def fix_age(age):
'''
Age entries are sometimes entered in months.
Change them to fraction
'''
rgx_month = re.compile(r"([0-9]*)( month?.)")
rgx_day = re.compile(r"([0-9]*)( day?.)")
res_month = rgx_month.search(str(age).lower())
res_day = rgx_day.search(str(age).lower())
if res_month:
age_corr = float(res_month.group(1))/12
return round(age_corr,2)
elif res_day:
age_corr = float(res_day.group(1))/365.25
return round(age_corr,2)
return float(age)
def fix_gender(g):
'''
Fix any invalid entries in gender column
'''
rgx_F = re.compile(r"[w,W]|[f,F]emale")
rgx_M = re.compile(r"[m,M]ale")
g = str(g)
g = re.sub(rgx_F,"F",g)
g = re.sub(rgx_M,"M",g)
return g
def compare_with_gospel():
'''
Till April 26th, the districtwise sheet was managed
separately. i.e, Raw Data till then do not truly represent
the district values till then.
This function compares the entries in Raw Data with gospel
Note that this function ignores the blank districts.
'''
# Read merged data
df = pd.read_csv('./tmp/csv/latest/raw_data.csv',low_memory=False)
df.head()
df['Date Announced'] = pd.to_datetime(df['Date Announced'])
df = df[df['Date Announced'] <= '2020-04-26']
df['District_Key'] = df['State code'] + "_" + df['Detected District']
df['Num Cases'] = pd.to_numeric(df['Num Cases'], errors='coerce')
dis_counts = pd.pivot_table(df,values = 'Num Cases',
index = 'District_Key',
columns='Current Status',
aggfunc = sum).reset_index()
dis_counts.rename(columns={'Hospitalized':'Confirmed'},inplace=True)
# Read gospel
url = "https://raw.githubusercontent.com/covid19india/api/gh-pages/csv/latest/districts_26apr_gospel.csv"
gospel = pd.read_csv(url)
compare = pd.merge(gospel,dis_counts,on='District_Key', suffixes=("_gospel","_v1v2"))
compare.fillna(0,inplace=True)
compare['Conf_Diff'] = compare['Confirmed_gospel'] - compare['Confirmed_v1v2']
compare['Reco_Diff'] = compare['Recovered_gospel'] - compare['Recovered_v1v2']
compare['Dece_Diff'] = compare['Deceased_gospel'] - compare['Deceased_v1v2']
compare.to_csv("./tmp/csv/compare_gospel_v1v2.csv",index=False)
logging.info('Comparison file saved as ./tmp/csv/compare_gospel_v1v2.csv')
return compare
if __name__ == "__main__":
logging.info('''----------------------------------------------------------------------''')
logging.info('''Build one true raw data''')
logging.info('''----------------------------------------------------------------------''')
os.makedirs('./tmp/csv/latest/',exist_ok=True)
try:
# raw_d,death_rec,current_ver = fetch_raw_data()
# If remote fetch is required
raw_d,death_rec,current_ver = fetch_raw_data_from_api()
except Exception as e:
logging.error(f"Error while reading the files")
raise
logging.info('''----------------------------------------------------------------------''')
allraw = merge_alldata(current_ver)
allraw.to_csv('./tmp/csv/latest/raw_data.csv',index=False)
logging.info('''----------------------------------------------------------------------''')
logging.info('''Raw Data saved''')
logging.info('''----------------------------------------------------------------------''')
logging.info('''Comparing with Gospel''')
_ = compare_with_gospel()
logging.info('''----------------------------------------------------------------------''')