Skip to content

Commit b324d59

Browse files
committed
feat: anonymize_table script
1 parent d438116 commit b324d59

File tree

1 file changed

+151
-0
lines changed

1 file changed

+151
-0
lines changed

anonymize_table.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
#!/usr/bin/env python3
2+
3+
import re
4+
import random
5+
import string
6+
import logging
7+
import numpy as np
8+
from pathlib import Path
9+
10+
import ontoweaver
11+
12+
def write_table(df, fd, ext="csv", **kwargs):
13+
14+
read_funcs = {
15+
'csv' : df.to_csv,
16+
'tsv' : df.to_csv,
17+
'txt' : df.to_csv,
18+
19+
'xls' : df.to_excel,
20+
'xlsx' : df.to_excel,
21+
'xlsm' : df.to_excel,
22+
'xlsb' : df.to_excel,
23+
'odf' : df.to_excel,
24+
'ods' : df.to_excel,
25+
'odt' : df.to_excel,
26+
27+
'json' : df.to_json,
28+
'html' : df.to_html,
29+
'xml' : df.to_xml,
30+
'hdf' : df.to_hdf,
31+
'feather': df.to_feather,
32+
'parquet': df.to_parquet,
33+
'pickle' : df.to_pickle,
34+
'orc' : df.to_orc,
35+
'stata' : df.to_stata,
36+
}
37+
38+
if ext not in read_funcs:
39+
msg = f"File format '{ext}' of file '{filename}' is not supported (I can only write one of: {' ,'.join(read_funcs.keys())})"
40+
logger.error(msg)
41+
raise RuntimeError(msg)
42+
43+
return read_funcs[ext](path_or_buf=fd, **kwargs)
44+
45+
46+
def shuffle(df):
47+
# df.apply(np.random.shuffle, axis = 0) # columns
48+
return df.apply(lambda col: col.sample(frac=1).values)
49+
50+
51+
def anonymize_value(value, remove_site = False):
52+
assert(";" not in str(value))
53+
if remove_site:
54+
value = re.sub("_DNA[1-2]*$", "", value)
55+
m = re.search("^([A-Z]{1,2}[0-9]{3})", value)
56+
if m:
57+
code = m.group(1)
58+
return re.sub(code, random_code(), value)
59+
else:
60+
return value
61+
62+
63+
def anonymize_all(df, columns=None, remove_site = False):
64+
if not columns:
65+
columns = df.columns.values.tolist()
66+
for i,row in df.iterrows():
67+
for col in columns:
68+
value = row[col]
69+
if type(value) == str:
70+
if ";" in value:
71+
vals = []
72+
for val in value.split(";"):
73+
new = anonymize_value(val, remove_site)
74+
vals.append(new)
75+
new_val = ";".join(vals)
76+
else:
77+
new_val = anonymize_value(value, remove_site)
78+
79+
if value and new_val:
80+
df.loc[i,col] = new_val
81+
82+
83+
def random_code():
84+
return "CC" + "".join(random.choices(string.digits, k=4))
85+
86+
87+
if __name__ == "__main__":
88+
import argparse
89+
import os
90+
import sys
91+
92+
do = argparse.ArgumentParser(
93+
formatter_class=argparse.RawTextHelpFormatter,
94+
description="""Anonymize or pseudonymize a data table.""",
95+
epilog=f"Example:\n\t./{os.path.basename(sys.argv[0])} data.csv --args index:False --remove-sample-site --format csv > data_anon.csv")
96+
97+
do.add_argument("--log-level",
98+
default="INFO",
99+
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
100+
help="Configure the log level (default: %(default)s).",
101+
)
102+
103+
do.add_argument('-c', '--columns', nargs='+', default=None,
104+
help="Columns names in which to anonymize cohort codes (default: all).")
105+
106+
do.add_argument('-s', '--remove-sample-site', action="store_true")
107+
108+
do.add_argument('-S', '--no-shuffle', action="store_true")
109+
110+
# do.add_argument('-c', '--eoc', help="Use the given (;-separated) mapping instead of generating a random one.", metavar="EOC_FILE")
111+
112+
do.add_argument('-f', '--format', help="File format to export the altered data (default: same as input).", default=None, metavar="FMT")
113+
114+
do.add_argument('-a', '--args', help="Additional argument to pass to the pandas.DataFrame.to_* write function (default: none).", default=None, nargs='+', metavar="KEY:VAL")
115+
116+
117+
do.add_argument("filename", metavar="DATABASE_FILE")
118+
119+
asked = do.parse_args()
120+
121+
logging.basicConfig(level = asked.log_level)
122+
123+
if not asked.format:
124+
asked.format = Path(asked.filename).suffix[1:]
125+
126+
more_args = {}
127+
if asked.args:
128+
for kv in asked.args:
129+
k,v = kv.split(":")
130+
131+
if v == "False":
132+
v = False
133+
elif v == "True":
134+
v = True
135+
136+
more_args[k] = v
137+
138+
logging.info("Load file...")
139+
df = ontoweaver.read_file(asked.filename)
140+
print(df, file=sys.stderr)
141+
142+
if not asked.no_shuffle:
143+
logging.info("Shuffle columns...")
144+
df = shuffle(df)
145+
146+
logging.info("Alter cohort codes...")
147+
anonymize_all(df, columns = asked.columns, remove_site = asked.remove_sample_site)
148+
149+
logging.info("Write data...")
150+
write_table(df, sys.stdout, ext=asked.format, **more_args)
151+

0 commit comments

Comments
 (0)