Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython_template.py
More file actions
Latest commit
226 lines (184 loc) · 7 KB
/
Copy pathpython_template.py
File metadata and controls
226 lines (184 loc) · 7 KB
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
#! /usr/bin/env python3
importsys
importos
importargparse
importcsv
importjson
importtime
fromdatetimeimportdatetime
fromdateutil.parserimportparseasdateparse
importsignal
importrandom
importhashlib
# =========================
classmapper:
# ----------------------------------------
def__init__(self):
self.load_reference_data()
self.stat_pack= {}
# ----------------------------------------
defmap(self, raw_data, input_row_num=None):
json_data= {}
# --clean values
forattributeinraw_data:
raw_data[attribute] =self.clean_value(raw_data[attribute])
# --place any filters needed here
# --place any calculations needed here
# --mandatory attributes
json_data["DATA_SOURCE"] ="<supply>"
# --the record_id should be unique, remove this mapping if there is not one
json_data["RECORD_ID"] ="<remove_or_supply>"
# --record type is not mandatory, but should be PERSON or ORGANIZATION
# --json_data['RECORD_TYPE'] = 'PERSON'
# --column mappings
# --remove empty attributes and capture the stats
json_data=self.remove_empty_tags(json_data)
self.capture_mapped_stats(json_data)
returnjson_data
# ----------------------------------------
defload_reference_data(self):
# --garbage values
self.variant_data= {}
self.variant_data["GARBAGE_VALUES"] = ["NULL", "NUL", "N/A"]
# -----------------------------------
defclean_value(self, raw_value):
ifnotraw_value:
return""
new_value=" ".join(str(raw_value).strip().split())
ifnew_value.upper() inself.variant_data["GARBAGE_VALUES"]:
return""
returnnew_value
# -----------------------------------
defcompute_record_hash(self, target_dict, attr_list=None):
ifattr_list:
string_to_hash=""
forattr_nameinsorted(attr_list):
string_to_hash+= (
" ".join(str(target_dict[attr_name]).split()).upper()
ifattr_nameintarget_dictandtarget_dict[attr_name]
else""
) +"|"
else:
string_to_hash=json.dumps(target_dict, sort_keys=True)
returnhashlib.md5(bytes(string_to_hash, "utf-8")).hexdigest()
# ----------------------------------------
defformat_date(self, raw_date):
try:
returndatetime.strftime(dateparse(raw_date), "%Y-%m-%d")
except:
self.update_stat("!INFO", "BAD_DATE", raw_date)
return""
# ----------------------------------------
defremove_empty_tags(self, d):
ifisinstance(d, dict):
fork, vinlist(d.items()):
ifvisNoneorlen(str(v).strip()) ==0:
deld[k]
else:
self.remove_empty_tags(v)
ifisinstance(d, list):
forvind:
self.remove_empty_tags(v)
returnd
# ----------------------------------------
defupdate_stat(self, cat1, cat2, example=None):
ifcat1notinself.stat_pack:
self.stat_pack[cat1] = {}
ifcat2notinself.stat_pack[cat1]:
self.stat_pack[cat1][cat2] = {}
self.stat_pack[cat1][cat2]["count"] =0
self.stat_pack[cat1][cat2]["count"] +=1
ifexample:
if"examples"notinself.stat_pack[cat1][cat2]:
self.stat_pack[cat1][cat2]["examples"] = []
ifexamplenotinself.stat_pack[cat1][cat2]["examples"]:
iflen(self.stat_pack[cat1][cat2]["examples"]) <5:
self.stat_pack[cat1][cat2]["examples"].append(example)
else:
randomSampleI=random.randint(2, 4)
self.stat_pack[cat1][cat2]["examples"][randomSampleI] =example
return
# ----------------------------------------
defcapture_mapped_stats(self, json_data):
if"DATA_SOURCE"injson_data:
data_source=json_data["DATA_SOURCE"]
else:
data_source="UNKNOWN_DSRC"
forkey1injson_data:
iftype(json_data[key1]) !=list:
self.update_stat(data_source, key1, json_data[key1])
else:
forsubrecordinjson_data[key1]:
forkey2insubrecord:
self.update_stat(data_source, key2, subrecord[key2])
# ----------------------------------------
defsignal_handler(signal, frame):
print("USER INTERRUPT! Shutting down ... (please wait)")
globalshut_down
shut_down=True
return
# ----------------------------------------
if__name__=="__main__":
proc_start_time=time.time()
shut_down=False
signal.signal(signal.SIGINT, signal_handler)
input_file="<input_file_name>"
csv_dialect="<dialect>"
parser=argparse.ArgumentParser()
parser.add_argument(
"-i",
"--input_file",
dest="input_file",
default=input_file,
help="the name of the input file",
)
parser.add_argument(
"-o", "--output_file", dest="output_file", help="the name of the output file"
)
parser.add_argument(
"-l",
"--log_file",
dest="log_file",
help="optional name of the statistics log file",
)
args=parser.parse_args()
ifnotargs.input_fileornotos.path.exists(args.input_file):
print("\nPlease supply a valid input file name on the command line\n")
sys.exit(1)
ifnotargs.output_file:
print("\nPlease supply a valid output file name on the command line\n")
sys.exit(1)
input_file_handle=open(args.input_file, "r")
output_file_handle=open(args.output_file, "w", encoding="utf-8")
mapper=mapper()
input_row_count=0
output_row_count=0
forinput_rowincsv.DictReader(input_file_handle, dialect=csv_dialect):
input_row_count+=1
json_data=mapper.map(input_row, input_row_count)
ifjson_data:
output_file_handle.write(json.dumps(json_data) +"\n")
output_row_count+=1
ifinput_row_count%1000==0:
print(
"%s rows processed, %s rows written"
% (input_row_count, output_row_count)
)
ifshut_down:
break
elapsed_mins=round((time.time() -proc_start_time) /60, 1)
run_status= (
"completed in"ifnotshut_downelse"aborted after"
) +" %s minutes"%elapsed_mins
print(
"%s rows processed, %s rows written, %s\n"
% (input_row_count, output_row_count, run_status)
)
output_file_handle.close()
input_file_handle.close()
# --write statistics file
ifargs.log_file:
withopen(args.log_file, "w") asoutfile:
json.dump(mapper.stat_pack, outfile, indent=4, sort_keys=True)
print("Mapping stats written to %s\n"%args.log_file)
sys.exit(0)