-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_extractor.py
162 lines (160 loc) · 7.98 KB
/
data_extractor.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
import pandas as pd
import requests
import json
from datetime import datetime
from copy import deepcopy
import ast
def modify(data, data_source):
# `data` format = [{}]
new_data = []
transform = {
'phone_1': "phone",
'phone_2': "phone2",
'external_id': "external_uuid",
'data_name': "source2",
'pin_code': "pincode",
"city": "location_raw",
}
preserve = [
"district",
"title",
"email",
"state",
"pincode",
"address",
"price",
"category",
"source_link"
]
if(data_source=="coronasafe"):
for record in data:
new_dict = {'source': "coronasafe.network"}
for (key, value) in record.items():
if isinstance(value, str):
value = value.strip().strip("-").strip(",")
if value:
if(key in preserve):
new_dict[key] = value
elif(key in transform):
new_dict[transform[key]] = value
elif(key in {"created_on","last_verified_on"}):
try:
dt = pd.to_datetime(value.replace("Z", ""))
if dt > datetime.now():
dt = pd.to_datetime(value.replace("Z", ""), dayfirst=True)
new_dict[key] = dt
except:
pass
elif(key in {"resource_type","resource type","resource type_2"}):
if("resource_raw" not in new_dict):
new_dict["resource_raw"] = ""
new_dict["resource_raw"] += "{}".format(value)
elif(key in {"Details","description","Other comments","comment","Sales/Renta/Charity"}):
if("comments" not in new_dict):
new_dict["comments"] = ""
if(key == "Sales/Renta/Charity"):
value = "Sales or Rental or Charity? - " + value
new_dict["comments"] = "\n".join(filter(None, [new_dict['comments'], value]))
elif(key=="quantity_available"):
new_dict['available'] = (value not in ["Unavailable","Undetermined","no beds currently avilable","NIL",""])
new_dict['quantity_text'] = value
elif(key=="verification_status"):
new_dict["verified"] = value.lower().startswith("verified") or ("and verified" in value.lower()) or ("but verified" in value.lower())
# outside of the loop, we check which of the 4 hospital w/ bed types have values and build a list of (key,value) pairs
hospital_beds = [(key, record[key]) for key in ["hospital_available_normal_beds",
"hospital_available_ventilator_beds",
"hospital_available_icu_beds",
"hospital_available_oxygen_beds"]
if record.get(key, "").strip()]
for (i, (key, value)) in enumerate(hospital_beds):
# crude way to check if best are available (does not start with "not" and "no")
available = not value.lower().startswith("no")
resource_raw = key.replace("available", "with").replace("_", " ")
# store comments so far (so we can add to them in the loop)
orig_comments = new_dict.get('comments', "")
# generate new comments from resource type text
comments = ""
if value.isdigit():
new_dict['quantity'] = int(value)
if value.lower().strip() not in ["available", "yes", "no", ""]:
comments = "{}: {}".format(resource_raw, value)
# if we're on first out of 4 possible hospital w/ bed types, use the dict we were creating so far
if i==0:
new_dict['available'] = available
new_dict['comments'] = "\n".join(filter(None, [orig_comments, comments]))
new_dict['resource_raw'] = resource_raw
# otherwise create a new dict from existing data and add it to `new_data`
else:
if not available:
continue
extra_dict = deepcopy(new_dict)
extra_dict['available'] = available
extra_dict['comments'] = "\n".join(filter(None, [orig_comments, comments]))
extra_dict['resource_raw'] = resource_raw
new_data.append(extra_dict)
new_data.append(new_dict)
del new_dict
elif(data_source=="nlp_supply"):
for record in data:
new_dict = {'source': "nlp_supply"}
for (key, value) in record.items():
if isinstance(value, str):
value = value.strip().strip("-").strip(",")
if value or value==0:
if(key in {"Resource Type","Resource Category"}):
if("resource_raw" not in new_dict):
new_dict["resource_raw"] = ""
if(value):
new_dict["resource_raw"] += value.replace("Hopital","hospital")
elif(key in {"row_num"}):
new_dict[key] = value
elif(key=="Contact Number"):
new_dict["phone"] = value
elif(key=="City"):
new_dict["location_raw"] = value
elif(key=="Timestamp"): # TODO: CHECK THE TIMEZONE AND CONVERT TO IST
try:
new_dict["created_on"] = pd.to_datetime(value)
except:
pass
elif(key=="Source"):
new_dict["source2"] = value
new_data.append(new_dict)
del new_dict
elif(data_source=="nlp_demand"):
for record in data:
new_dict = {'source': "nlp_demand"}
for (key,value) in record.items():
if isinstance(value, str):
value = value.strip().strip("-").strip(",")
if value or value==0:
if(key in {"Resource Type","Resource Category"}):
if("resource_raw" not in new_dict):
new_dict["resource_raw"] = ""
if(value):
new_dict["resource_raw"] += f" {value.replace('Hopital','hospital')}"
elif(key in {"row_num"}):
new_dict[key] = value
elif(key=="Contact Number"):
new_dict["phone"] = value
elif(key=="City"):
new_dict["location_raw"] = value
elif(key=="Timestamp"): # TODO: CHECK THE TIMEZONE AND CONVERT TO IST
try:
new_dict["created_on"] = pd.to_datetime(value)
except:
pass
elif(key=="Source"):
new_dict["source2"] = value
elif(key=="Username"):
new_dict["name"] = value
# elif(key=="Metadata"):
# new_dict["source"] = "telegram"
# if(value):
# value_dict = ast.literal_eval(value)
# new_dict["tg_user_id"] = value_dict['from_user']['id']
# new_dict["tg_user_handle"] = value_dict['from_user']['username']
# new_dict["group_id"] = value_dict['chat']['id']
new_data.append(new_dict)
del new_dict
return new_data